Upload 43 files
Browse files- Version2_Context/2/admin_panel.py +1232 -0
- Version2_Context/2/data_manager.py +672 -0
- Version2_Context/2/fix_data.py +79 -0
- Version2_Context/2/keep_alive.py +23 -0
- Version2_Context/2/main.py +660 -0
- Version2_Context/2/render.yaml +12 -0
- Version2_Context/2/requirements.txt +11 -0
- Version2_Context/admin_panel.py +961 -0
- Version2_Context/data_manager.py +329 -0
- Version2_Context/keep_alive.py +23 -0
- Version2_Context/main.py +225 -0
- Version2_Context/render-main/admin_panel.py +961 -0
- Version2_Context/render-main/data_manager.py +328 -0
- Version2_Context/render-main/keep_alive.py +23 -0
- Version2_Context/render-main/main.py +225 -0
- Version2_Context/render-main/render.yaml +12 -0
- Version2_Context/render-main/requirements.txt +11 -0
- Version2_Context/render-main2.zip +3 -0
- Version2_Context/render.yaml +12 -0
- Version2_Context/requirements.txt +11 -0
- Version3_Context_Instrunction/admin_panel.py +961 -0
- Version3_Context_Instrunction/data_manager.py +337 -0
- Version3_Context_Instrunction/keep_alive.py +23 -0
- Version3_Context_Instrunction/main.py +222 -0
- Version3_Context_Instrunction/render.yaml +12 -0
- Version3_Context_Instrunction/requirements.txt +11 -0
- Version3_Context_Instrunction/restart.py +13 -0
- Version4/render-main.zip +3 -0
- Version4/render-main/STORED.py +441 -0
- Version4/render-main/admin_panel.py +1130 -0
- Version4/render-main/data_manager.py +328 -0
- Version4/render-main/keep_alive.py +23 -0
- Version4/render-main/main.py +446 -0
- Version4/render-main/render.yaml +12 -0
- Version4/render-main/requirements.txt +16 -0
- Version4/render-main/restart.py +13 -0
- Version4/render-main/smart_context.py +1180 -0
- render-main/admin_panel.py +880 -0
- render-main/data_manager.py +179 -0
- render-main/keep_alive.py +23 -0
- render-main/main.py +167 -0
- render-main/render.yaml +12 -0
- render-main/requirements.txt +10 -0
Version2_Context/2/admin_panel.py
ADDED
|
@@ -0,0 +1,1232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"📋 `/commands` - نمایش این لیست دستورات"
|
| 79 |
+
)
|
| 80 |
+
await update.message.reply_text(commands_text, parse_mode='Markdown')
|
| 81 |
+
|
| 82 |
+
@admin_only
|
| 83 |
+
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 84 |
+
"""آمار ربات را نمایش میدهد."""
|
| 85 |
+
total_users = len(data_manager.DATA['users'])
|
| 86 |
+
total_groups = len(data_manager.DATA['groups'])
|
| 87 |
+
total_messages = data_manager.DATA['stats']['total_messages']
|
| 88 |
+
banned_count = len(data_manager.DATA['banned_users'])
|
| 89 |
+
|
| 90 |
+
now = datetime.now()
|
| 91 |
+
active_24h = sum(1 for user in data_manager.DATA['users'].values()
|
| 92 |
+
if 'last_seen' in user and
|
| 93 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
|
| 94 |
+
|
| 95 |
+
active_7d = 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(days=7))
|
| 98 |
+
|
| 99 |
+
active_users = sorted(
|
| 100 |
+
data_manager.DATA['users'].items(),
|
| 101 |
+
key=lambda item: item[1].get('last_seen', ''),
|
| 102 |
+
reverse=True
|
| 103 |
+
)[:5]
|
| 104 |
+
|
| 105 |
+
active_users_text = "\n".join(
|
| 106 |
+
[f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
|
| 107 |
+
for user_id, info in active_users]
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# آمار context
|
| 111 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values()
|
| 112 |
+
if user.get('context') and len(user['context']) > 0)
|
| 113 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 114 |
+
|
| 115 |
+
# آمار ریپلایها
|
| 116 |
+
total_replies = 0
|
| 117 |
+
for user in data_manager.DATA['users'].values():
|
| 118 |
+
if 'context' in user:
|
| 119 |
+
total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
|
| 120 |
+
|
| 121 |
+
# آمار گروهها
|
| 122 |
+
groups_with_context = sum(1 for group in data_manager.DATA['groups'].values()
|
| 123 |
+
if group.get('context') and len(group['context']) > 0)
|
| 124 |
+
|
| 125 |
+
text = (
|
| 126 |
+
f"📊 **آمار ربات**\n\n"
|
| 127 |
+
f"👥 **تعداد کل کاربران:** `{total_users}`\n"
|
| 128 |
+
f"👥 **تعداد کل گروهها:** `{total_groups}`\n"
|
| 129 |
+
f"📝 **تعداد کل پیامها:** `{total_messages}`\n"
|
| 130 |
+
f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
|
| 131 |
+
f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
|
| 132 |
+
f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
|
| 133 |
+
f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
|
| 134 |
+
f"💬 **گروههای با context فعال:** `{groups_with_context}`\n"
|
| 135 |
+
f"📝 **کل پیامهای context:** `{total_context_messages}`\n"
|
| 136 |
+
f"📎 **کل ریپلایهای ثبت شده:** `{total_replies}`\n"
|
| 137 |
+
f"🔄 **حالت context فعلی:** `{data_manager.get_context_mode()}`\n\n"
|
| 138 |
+
f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
|
| 139 |
+
)
|
| 140 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 141 |
+
|
| 142 |
+
@admin_only
|
| 143 |
+
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 144 |
+
"""یک پیام را به تمام کاربران ارسال میکند."""
|
| 145 |
+
if not context.args:
|
| 146 |
+
await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
message_text = " ".join(context.args)
|
| 150 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 151 |
+
total_sent = 0
|
| 152 |
+
total_failed = 0
|
| 153 |
+
|
| 154 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
|
| 155 |
+
|
| 156 |
+
for user_id_str in user_ids:
|
| 157 |
+
try:
|
| 158 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 159 |
+
total_sent += 1
|
| 160 |
+
await asyncio.sleep(0.05)
|
| 161 |
+
except TelegramError as e:
|
| 162 |
+
logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
|
| 163 |
+
total_failed += 1
|
| 164 |
+
|
| 165 |
+
result_text = (
|
| 166 |
+
f"✅ **ارسال همگانی تمام شد**\n\n"
|
| 167 |
+
f"✅ موفق: `{total_sent}`\n"
|
| 168 |
+
f"❌ ناموفق: `{total_failed}`"
|
| 169 |
+
)
|
| 170 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 171 |
+
|
| 172 |
+
@admin_only
|
| 173 |
+
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 174 |
+
"""ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
|
| 175 |
+
if len(context.args) < 3:
|
| 176 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
|
| 177 |
+
"معیارهای موجود: `active_days`, `message_count`, `banned`")
|
| 178 |
+
return
|
| 179 |
+
|
| 180 |
+
criteria = context.args[0].lower()
|
| 181 |
+
value = context.args[1]
|
| 182 |
+
message_text = " ".join(context.args[2:])
|
| 183 |
+
|
| 184 |
+
target_users = []
|
| 185 |
+
|
| 186 |
+
if criteria == "active_days":
|
| 187 |
+
try:
|
| 188 |
+
days = int(value)
|
| 189 |
+
target_users = data_manager.get_active_users(days)
|
| 190 |
+
except ValueError:
|
| 191 |
+
await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
|
| 192 |
+
return
|
| 193 |
+
|
| 194 |
+
elif criteria == "message_count":
|
| 195 |
+
try:
|
| 196 |
+
min_count = int(value)
|
| 197 |
+
target_users = data_manager.get_users_by_message_count(min_count)
|
| 198 |
+
except ValueError:
|
| 199 |
+
await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
elif criteria == "banned":
|
| 203 |
+
if value.lower() == "true":
|
| 204 |
+
target_users = list(data_manager.DATA['banned_users'])
|
| 205 |
+
elif value.lower() == "false":
|
| 206 |
+
for user_id in data_manager.DATA['users']:
|
| 207 |
+
if int(user_id) not in data_manager.DATA['banned_users']:
|
| 208 |
+
target_users.append(int(user_id))
|
| 209 |
+
else:
|
| 210 |
+
await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
|
| 211 |
+
return
|
| 212 |
+
|
| 213 |
+
else:
|
| 214 |
+
await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
|
| 215 |
+
return
|
| 216 |
+
|
| 217 |
+
if not target_users:
|
| 218 |
+
await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
|
| 219 |
+
return
|
| 220 |
+
|
| 221 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
|
| 222 |
+
|
| 223 |
+
total_sent, total_failed = 0, 0
|
| 224 |
+
for user_id in target_users:
|
| 225 |
+
try:
|
| 226 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 227 |
+
total_sent += 1
|
| 228 |
+
await asyncio.sleep(0.05)
|
| 229 |
+
except TelegramError as e:
|
| 230 |
+
logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
|
| 231 |
+
total_failed += 1
|
| 232 |
+
|
| 233 |
+
result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
|
| 234 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 235 |
+
|
| 236 |
+
@admin_only
|
| 237 |
+
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 238 |
+
"""تنظیم ارسال برنامهریزی شده پیام به همه کاربران."""
|
| 239 |
+
if len(context.args) < 3:
|
| 240 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
try:
|
| 244 |
+
date_str, time_str = context.args[0], context.args[1]
|
| 245 |
+
message_text = " ".join(context.args[2:])
|
| 246 |
+
|
| 247 |
+
scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
|
| 248 |
+
|
| 249 |
+
if scheduled_time <= datetime.now():
|
| 250 |
+
await update.message.reply_text("⚠️ زمان برنامهریزی شده باید در آینده باشد.")
|
| 251 |
+
return
|
| 252 |
+
|
| 253 |
+
data_manager.DATA['scheduled_broadcasts'].append({
|
| 254 |
+
'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 255 |
+
'message': message_text,
|
| 256 |
+
'status': 'pending'
|
| 257 |
+
})
|
| 258 |
+
data_manager.save_data()
|
| 259 |
+
|
| 260 |
+
await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامهریزی شد.")
|
| 261 |
+
|
| 262 |
+
except ValueError:
|
| 263 |
+
await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
|
| 264 |
+
|
| 265 |
+
@admin_only
|
| 266 |
+
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 267 |
+
"""نمایش لیست ارسالهای برنامهریزی شده."""
|
| 268 |
+
if not data_manager.DATA['scheduled_broadcasts']:
|
| 269 |
+
await update.message.reply_text("هیچ ارسال برنامهریزی شدهای وجود ندارد.")
|
| 270 |
+
return
|
| 271 |
+
|
| 272 |
+
broadcasts_text = "📅 **لیست ارسالهای برنامهریزی شده:**\n\n"
|
| 273 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
|
| 274 |
+
status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
|
| 275 |
+
broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
|
| 276 |
+
|
| 277 |
+
await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
|
| 278 |
+
|
| 279 |
+
@admin_only
|
| 280 |
+
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 281 |
+
"""حذف یک ارسال برنامهریزی شده."""
|
| 282 |
+
if not context.args or not context.args[0].isdigit():
|
| 283 |
+
await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامهریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
|
| 284 |
+
return
|
| 285 |
+
|
| 286 |
+
index = int(context.args[0]) - 1
|
| 287 |
+
|
| 288 |
+
if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
|
| 289 |
+
await update.message.reply_text("⚠️ شماره ارسال برنامهریزی شده نامعتبر است.")
|
| 290 |
+
return
|
| 291 |
+
|
| 292 |
+
removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
|
| 293 |
+
data_manager.save_data()
|
| 294 |
+
|
| 295 |
+
await update.message.reply_text(f"✅ ارسال برنامهریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
|
| 296 |
+
|
| 297 |
+
@admin_only
|
| 298 |
+
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 299 |
+
"""یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع میدهد."""
|
| 300 |
+
if not context.args or not context.args[0].isdigit():
|
| 301 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
|
| 302 |
+
return
|
| 303 |
+
|
| 304 |
+
user_id_to_ban = int(context.args[0])
|
| 305 |
+
|
| 306 |
+
if user_id_to_ban in ADMIN_IDS:
|
| 307 |
+
await update.message.reply_text("🛡️ شما نمیتوانید یک ادمین را مسدود کنید!")
|
| 308 |
+
return
|
| 309 |
+
|
| 310 |
+
if data_manager.is_user_banned(user_id_to_ban):
|
| 311 |
+
await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
|
| 312 |
+
return
|
| 313 |
+
|
| 314 |
+
data_manager.ban_user(user_id_to_ban)
|
| 315 |
+
|
| 316 |
+
# ارسال پیام به کاربر مسدود شده
|
| 317 |
+
try:
|
| 318 |
+
await context.bot.send_message(
|
| 319 |
+
chat_id=user_id_to_ban,
|
| 320 |
+
text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمیتوانید از خدمات ربات استفاده کنید."
|
| 321 |
+
)
|
| 322 |
+
except TelegramError as e:
|
| 323 |
+
logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
|
| 324 |
+
|
| 325 |
+
await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
|
| 326 |
+
|
| 327 |
+
@admin_only
|
| 328 |
+
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 329 |
+
"""مسدودیت یک کاربر را برمیدارد و به او اطلاع میدهد."""
|
| 330 |
+
if not context.args or not context.args[0].isdigit():
|
| 331 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
|
| 332 |
+
return
|
| 333 |
+
|
| 334 |
+
user_id_to_unban = int(context.args[0])
|
| 335 |
+
|
| 336 |
+
if not data_manager.is_user_banned(user_id_to_unban):
|
| 337 |
+
await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شدهها وجود ندارد.")
|
| 338 |
+
return
|
| 339 |
+
|
| 340 |
+
data_manager.unban_user(user_id_to_unban)
|
| 341 |
+
|
| 342 |
+
# ارسال پیام به کاربر برای رفع مسدودیت
|
| 343 |
+
try:
|
| 344 |
+
await context.bot.send_message(
|
| 345 |
+
chat_id=user_id_to_unban,
|
| 346 |
+
text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. میتوانید دوباره از ربات استفاده کنید."
|
| 347 |
+
)
|
| 348 |
+
except TelegramError as e:
|
| 349 |
+
logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
|
| 350 |
+
|
| 351 |
+
await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
|
| 352 |
+
|
| 353 |
+
@admin_only
|
| 354 |
+
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 355 |
+
"""ارسال پیام مستقیم به یک کاربر خاص."""
|
| 356 |
+
if len(context.args) < 2:
|
| 357 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
user_id_str = context.args[0]
|
| 361 |
+
if not user_id_str.isdigit():
|
| 362 |
+
await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
|
| 363 |
+
return
|
| 364 |
+
|
| 365 |
+
message_text = " ".join(context.args[1:])
|
| 366 |
+
user_id = int(user_id_str)
|
| 367 |
+
|
| 368 |
+
try:
|
| 369 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 370 |
+
await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
|
| 371 |
+
except TelegramError as e:
|
| 372 |
+
await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
|
| 373 |
+
|
| 374 |
+
@admin_only
|
| 375 |
+
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 376 |
+
"""اطلاعات یک کاربر خاص را نمایش میدهد."""
|
| 377 |
+
if not context.args or not context.args[0].isdigit():
|
| 378 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
user_id = int(context.args[0])
|
| 382 |
+
user_info = data_manager.DATA['users'].get(str(user_id))
|
| 383 |
+
|
| 384 |
+
if not user_info:
|
| 385 |
+
await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
|
| 386 |
+
return
|
| 387 |
+
|
| 388 |
+
is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
|
| 389 |
+
|
| 390 |
+
if 'first_seen' in user_info and 'last_seen' in user_info:
|
| 391 |
+
try:
|
| 392 |
+
first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
|
| 393 |
+
last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 394 |
+
days_active = max(1, (last_date - first_date).days)
|
| 395 |
+
avg_messages = user_info.get('message_count', 0) / days_active
|
| 396 |
+
except:
|
| 397 |
+
avg_messages = user_info.get('message_count', 0)
|
| 398 |
+
else:
|
| 399 |
+
avg_messages = user_info.get('message_count', 0)
|
| 400 |
+
|
| 401 |
+
# اطلاعات context
|
| 402 |
+
context_messages = len(user_info.get('context', []))
|
| 403 |
+
context_tokens = data_manager.get_context_token_count(user_id)
|
| 404 |
+
|
| 405 |
+
# اطلاعات ریپلایها
|
| 406 |
+
reply_count = 0
|
| 407 |
+
if 'context' in user_info:
|
| 408 |
+
reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
|
| 409 |
+
|
| 410 |
+
text = (
|
| 411 |
+
f"ℹ️ **اطلاعات کاربر**\n\n"
|
| 412 |
+
f"🆔 **آیدی:** `{user_id}`\n"
|
| 413 |
+
f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
|
| 414 |
+
f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
|
| 415 |
+
f"📊 **تعداد پیامها:** `{user_info.get('message_count', 0)}`\n"
|
| 416 |
+
f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
|
| 417 |
+
f"📎 **تعداد ریپلایها:** `{reply_count}`\n"
|
| 418 |
+
f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
|
| 419 |
+
f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
|
| 420 |
+
f"💭 **پیامهای context:** `{context_messages}`\n"
|
| 421 |
+
f"🔢 **توکنهای context:** `{context_tokens}`\n"
|
| 422 |
+
f"🚫 **وضعیت مسدودیت:** {is_banned}"
|
| 423 |
+
)
|
| 424 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 425 |
+
|
| 426 |
+
@admin_only
|
| 427 |
+
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 428 |
+
"""آخرین خطوط لاگ ربات را ارسال میکند."""
|
| 429 |
+
try:
|
| 430 |
+
with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
|
| 431 |
+
lines = f.readlines()
|
| 432 |
+
last_lines = lines[-30:]
|
| 433 |
+
log_text = "".join(last_lines)
|
| 434 |
+
if not log_text:
|
| 435 |
+
await update.message.reply_text("فایل لاگ خالی است.")
|
| 436 |
+
return
|
| 437 |
+
|
| 438 |
+
if len(log_text) > 4096:
|
| 439 |
+
for i in range(0, len(log_text), 4096):
|
| 440 |
+
await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
|
| 441 |
+
else:
|
| 442 |
+
await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
|
| 443 |
+
|
| 444 |
+
except FileNotFoundError:
|
| 445 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 446 |
+
except Exception as e:
|
| 447 |
+
await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
|
| 448 |
+
|
| 449 |
+
@admin_only
|
| 450 |
+
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 451 |
+
"""فایل کامل لاگ ربات را ارسال میکند."""
|
| 452 |
+
try:
|
| 453 |
+
await update.message.reply_document(
|
| 454 |
+
document=open(data_manager.LOG_FILE, 'rb'),
|
| 455 |
+
caption="📂 فایل کامل لاگهای ربات"
|
| 456 |
+
)
|
| 457 |
+
except FileNotFoundError:
|
| 458 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 459 |
+
except Exception as e:
|
| 460 |
+
await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
|
| 461 |
+
|
| 462 |
+
@admin_only
|
| 463 |
+
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 464 |
+
"""نمایش لیست کامل کاربران با صفحهبندی."""
|
| 465 |
+
users = data_manager.DATA['users']
|
| 466 |
+
|
| 467 |
+
page = 1
|
| 468 |
+
if context.args and context.args[0].isdigit():
|
| 469 |
+
page = int(context.args[0])
|
| 470 |
+
if page < 1: page = 1
|
| 471 |
+
|
| 472 |
+
users_per_page = 20
|
| 473 |
+
total_users = len(users)
|
| 474 |
+
total_pages = (total_users + users_per_page - 1) // users_per_page
|
| 475 |
+
|
| 476 |
+
if page > total_pages: page = total_pages
|
| 477 |
+
|
| 478 |
+
start_idx = (page - 1) * users_per_page
|
| 479 |
+
end_idx = min(start_idx + users_per_page, total_users)
|
| 480 |
+
|
| 481 |
+
sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
|
| 482 |
+
|
| 483 |
+
users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
|
| 484 |
+
|
| 485 |
+
for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
|
| 486 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 487 |
+
username = user_info.get('username', 'N/A')
|
| 488 |
+
first_name = user_info.get('first_name', 'N/A')
|
| 489 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 490 |
+
message_count = user_info.get('message_count', 0)
|
| 491 |
+
context_count = len(user_info.get('context', []))
|
| 492 |
+
|
| 493 |
+
# تعداد ریپلایها
|
| 494 |
+
reply_count = 0
|
| 495 |
+
if 'context' in user_info:
|
| 496 |
+
reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
|
| 497 |
+
|
| 498 |
+
users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
|
| 499 |
+
users_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلایها: `{reply_count}`\n"
|
| 500 |
+
users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 501 |
+
|
| 502 |
+
keyboard = []
|
| 503 |
+
if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
|
| 504 |
+
if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
|
| 505 |
+
|
| 506 |
+
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
|
| 507 |
+
await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
|
| 508 |
+
|
| 509 |
+
@admin_only
|
| 510 |
+
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 511 |
+
"""جستجوی کاربر بر اساس نام یا نام کاربری."""
|
| 512 |
+
if not context.args:
|
| 513 |
+
await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
|
| 514 |
+
return
|
| 515 |
+
|
| 516 |
+
search_term = " ".join(context.args).lower()
|
| 517 |
+
users = data_manager.DATA['users']
|
| 518 |
+
|
| 519 |
+
matching_users = []
|
| 520 |
+
for user_id, user_info in users.items():
|
| 521 |
+
first_name = (user_info.get('first_name') or '').lower()
|
| 522 |
+
username = (user_info.get('username') or '').lower()
|
| 523 |
+
|
| 524 |
+
if search_term in first_name or search_term in username:
|
| 525 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 526 |
+
matching_users.append((user_id, user_info, is_banned))
|
| 527 |
+
|
| 528 |
+
if not matching_users:
|
| 529 |
+
await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
|
| 530 |
+
return
|
| 531 |
+
|
| 532 |
+
results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
|
| 533 |
+
|
| 534 |
+
for user_id, user_info, is_banned in matching_users:
|
| 535 |
+
username_display = user_info.get('username', 'N/A')
|
| 536 |
+
first_name_display = user_info.get('first_name', 'N/A')
|
| 537 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 538 |
+
message_count = user_info.get('message_count', 0)
|
| 539 |
+
context_count = len(user_info.get('context', []))
|
| 540 |
+
|
| 541 |
+
# تعداد ریپلایها
|
| 542 |
+
reply_count = 0
|
| 543 |
+
if 'context' in user_info:
|
| 544 |
+
reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
|
| 545 |
+
|
| 546 |
+
results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
|
| 547 |
+
results_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلایها: `{reply_count}`\n"
|
| 548 |
+
results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 549 |
+
|
| 550 |
+
await update.message.reply_text(results_text, parse_mode='Markdown')
|
| 551 |
+
|
| 552 |
+
@admin_only
|
| 553 |
+
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 554 |
+
"""ایجاد نسخه پشتیبان از دادههای ربات."""
|
| 555 |
+
try:
|
| 556 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 557 |
+
backup_file = f"bot_backup_{timestamp}.json"
|
| 558 |
+
|
| 559 |
+
data_to_backup = data_manager.DATA.copy()
|
| 560 |
+
data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
|
| 561 |
+
|
| 562 |
+
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 563 |
+
json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
|
| 564 |
+
|
| 565 |
+
await update.message.reply_document(
|
| 566 |
+
document=open(backup_file, 'rb'),
|
| 567 |
+
caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
logger.info(f"Backup created: {backup_file}")
|
| 571 |
+
os.remove(backup_file)
|
| 572 |
+
except Exception as e:
|
| 573 |
+
await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
|
| 574 |
+
logger.error(f"Error creating backup: {e}")
|
| 575 |
+
|
| 576 |
+
@admin_only
|
| 577 |
+
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 578 |
+
"""ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
|
| 579 |
+
users = data_manager.DATA['users']
|
| 580 |
+
|
| 581 |
+
df_data = []
|
| 582 |
+
for user_id, user_info in users.items():
|
| 583 |
+
is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
|
| 584 |
+
context_count = len(user_info.get('context', []))
|
| 585 |
+
context_tokens = data_manager.get_context_token_count(int(user_id))
|
| 586 |
+
|
| 587 |
+
# تعداد ریپلایها
|
| 588 |
+
reply_count = 0
|
| 589 |
+
if 'context' in user_info:
|
| 590 |
+
reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
|
| 591 |
+
|
| 592 |
+
df_data.append({
|
| 593 |
+
'User ID': user_id,
|
| 594 |
+
'First Name': user_info.get('first_name', 'N/A'),
|
| 595 |
+
'Username': user_info.get('username', 'N/A'),
|
| 596 |
+
'Message Count': user_info.get('message_count', 0),
|
| 597 |
+
'Context Messages': context_count,
|
| 598 |
+
'Context Tokens': context_tokens,
|
| 599 |
+
'Reply Count': reply_count,
|
| 600 |
+
'First Seen': user_info.get('first_seen', 'N/A'),
|
| 601 |
+
'Last Seen': user_info.get('last_seen', 'N/A'),
|
| 602 |
+
'Banned': is_banned
|
| 603 |
+
})
|
| 604 |
+
|
| 605 |
+
df = pd.DataFrame(df_data)
|
| 606 |
+
|
| 607 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
|
| 608 |
+
df.to_csv(f.name, index=False)
|
| 609 |
+
temp_file_path = f.name
|
| 610 |
+
|
| 611 |
+
await update.message.reply_document(
|
| 612 |
+
document=open(temp_file_path, 'rb'),
|
| 613 |
+
caption="📊 فایل CSV اطلاعات کاربران"
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
os.unlink(temp_file_path)
|
| 617 |
+
|
| 618 |
+
@admin_only
|
| 619 |
+
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 620 |
+
"""حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع میدهد."""
|
| 621 |
+
if not context.args or context.args[0].lower() not in ['on', 'off']:
|
| 622 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
|
| 623 |
+
return
|
| 624 |
+
|
| 625 |
+
status = context.args[0].lower()
|
| 626 |
+
|
| 627 |
+
if status == 'on':
|
| 628 |
+
if data_manager.DATA.get('maintenance_mode', False):
|
| 629 |
+
await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
|
| 630 |
+
return
|
| 631 |
+
|
| 632 |
+
data_manager.DATA['maintenance_mode'] = True
|
| 633 |
+
data_manager.save_data()
|
| 634 |
+
|
| 635 |
+
await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاعرسانی به کاربران...")
|
| 636 |
+
|
| 637 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 638 |
+
for user_id_str in user_ids:
|
| 639 |
+
try:
|
| 640 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 641 |
+
await context.bot.send_message(
|
| 642 |
+
chat_id=int(user_id_str),
|
| 643 |
+
text="🔧 ربات در حال حاضر در حالت بهروزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
|
| 644 |
+
)
|
| 645 |
+
await asyncio.sleep(0.05)
|
| 646 |
+
except TelegramError:
|
| 647 |
+
continue
|
| 648 |
+
|
| 649 |
+
elif status == 'off':
|
| 650 |
+
if not data_manager.DATA.get('maintenance_mode', False):
|
| 651 |
+
await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
data_manager.DATA['maintenance_mode'] = False
|
| 655 |
+
data_manager.save_data()
|
| 656 |
+
|
| 657 |
+
await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاعرسانی به کاربران...")
|
| 658 |
+
|
| 659 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 660 |
+
for user_id_str in user_ids:
|
| 661 |
+
try:
|
| 662 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 663 |
+
await context.bot.send_message(
|
| 664 |
+
chat_id=int(user_id_str),
|
| 665 |
+
text="✅ بهروزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! میتوانید دوباره از ربات استفاده کنید."
|
| 666 |
+
)
|
| 667 |
+
await asyncio.sleep(0.05)
|
| 668 |
+
except TelegramError:
|
| 669 |
+
continue
|
| 670 |
+
|
| 671 |
+
@admin_only
|
| 672 |
+
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 673 |
+
"""تنظیم پیام خوشامدگویی جدید."""
|
| 674 |
+
if not context.args:
|
| 675 |
+
await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
|
| 676 |
+
"مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
|
| 677 |
+
return
|
| 678 |
+
|
| 679 |
+
new_message = " ".join(context.args)
|
| 680 |
+
data_manager.DATA['welcome_message'] = new_message
|
| 681 |
+
data_manager.save_data()
|
| 682 |
+
|
| 683 |
+
await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت بهروزرسانی شد.")
|
| 684 |
+
|
| 685 |
+
@admin_only
|
| 686 |
+
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 687 |
+
"""تنظیم پیام خداحافظی جدید."""
|
| 688 |
+
if not context.args:
|
| 689 |
+
await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
|
| 690 |
+
"مثال: `/set_goodbye {user_mention}، خداحافظ!`")
|
| 691 |
+
return
|
| 692 |
+
|
| 693 |
+
new_message = " ".join(context.args)
|
| 694 |
+
data_manager.DATA['goodbye_message'] = new_message
|
| 695 |
+
data_manager.save_data()
|
| 696 |
+
|
| 697 |
+
await update.message.reply_text("✅ پیام خداحافظی با موفقیت بهروزرسانی شد.")
|
| 698 |
+
|
| 699 |
+
@admin_only
|
| 700 |
+
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 701 |
+
"""ایجاد و ارسال نمودار فعالیت کاربران."""
|
| 702 |
+
users = data_manager.DATA['users']
|
| 703 |
+
activity_hours = [0] * 24
|
| 704 |
+
|
| 705 |
+
for user_info in users.values():
|
| 706 |
+
if 'last_seen' in user_info:
|
| 707 |
+
try:
|
| 708 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 709 |
+
activity_hours[last_seen.hour] += 1
|
| 710 |
+
except ValueError:
|
| 711 |
+
continue
|
| 712 |
+
|
| 713 |
+
plt.figure(figsize=(12, 6))
|
| 714 |
+
plt.bar(range(24), activity_hours, color='skyblue')
|
| 715 |
+
plt.title('نمودار فعالیت کاربران بر اساس ساعت')
|
| 716 |
+
plt.xlabel('ساعت')
|
| 717 |
+
plt.ylabel('تعداد کاربران فعال')
|
| 718 |
+
plt.xticks(range(24))
|
| 719 |
+
plt.grid(axis='y', alpha=0.3)
|
| 720 |
+
|
| 721 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
|
| 722 |
+
plt.savefig(f.name, bbox_inches='tight')
|
| 723 |
+
temp_file_path = f.name
|
| 724 |
+
|
| 725 |
+
plt.close()
|
| 726 |
+
|
| 727 |
+
await update.message.reply_photo(
|
| 728 |
+
photo=open(temp_file_path, 'rb'),
|
| 729 |
+
caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
os.unlink(temp_file_path)
|
| 733 |
+
|
| 734 |
+
@admin_only
|
| 735 |
+
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 736 |
+
"""نمایش آمار زمان پاسخگویی ربات."""
|
| 737 |
+
stats = data_manager.DATA['stats']
|
| 738 |
+
await update.message.reply_text(
|
| 739 |
+
"📈 **آمار زمان پاسخگویی ربات**\n\n"
|
| 740 |
+
f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
|
| 741 |
+
f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
|
| 742 |
+
f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
|
| 743 |
+
f"📊 کل پاسخهای ثبت شده: `{stats.get('total_responses', 0)}`"
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
@admin_only
|
| 747 |
+
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 748 |
+
"""افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
|
| 749 |
+
if not context.args:
|
| 750 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 751 |
+
"مثال: `/add_blocked_word کلمه_نامناسب`")
|
| 752 |
+
return
|
| 753 |
+
|
| 754 |
+
word = " ".join(context.args).lower()
|
| 755 |
+
|
| 756 |
+
if word in data_manager.DATA['blocked_words']:
|
| 757 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
|
| 758 |
+
return
|
| 759 |
+
|
| 760 |
+
data_manager.DATA['blocked_words'].append(word)
|
| 761 |
+
data_manager.save_data()
|
| 762 |
+
|
| 763 |
+
await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
|
| 764 |
+
|
| 765 |
+
@admin_only
|
| 766 |
+
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 767 |
+
"""حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
|
| 768 |
+
if not context.args:
|
| 769 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 770 |
+
"مثال: `/remove_blocked_word کلمه_نامناسب`")
|
| 771 |
+
return
|
| 772 |
+
|
| 773 |
+
word = " ".join(context.args).lower()
|
| 774 |
+
|
| 775 |
+
if word not in data_manager.DATA['blocked_words']:
|
| 776 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
|
| 777 |
+
return
|
| 778 |
+
|
| 779 |
+
data_manager.DATA['blocked_words'].remove(word)
|
| 780 |
+
data_manager.save_data()
|
| 781 |
+
|
| 782 |
+
await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
|
| 783 |
+
|
| 784 |
+
@admin_only
|
| 785 |
+
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 786 |
+
"""نمایش لیست کلمات مسدود شده."""
|
| 787 |
+
if not data_manager.DATA['blocked_words']:
|
| 788 |
+
await update.message.reply_text("هیچ کلمه مسدود شدهای در لیست وجود ندارد.")
|
| 789 |
+
return
|
| 790 |
+
|
| 791 |
+
words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
|
| 792 |
+
await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
|
| 793 |
+
|
| 794 |
+
@admin_only
|
| 795 |
+
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 796 |
+
"""نمایش اطلاعات سیستم و منابع."""
|
| 797 |
+
bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
|
| 798 |
+
try:
|
| 799 |
+
bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
|
| 800 |
+
uptime = datetime.now() - bot_start_time
|
| 801 |
+
except:
|
| 802 |
+
uptime = "نامشخص"
|
| 803 |
+
|
| 804 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 805 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
|
| 806 |
+
|
| 807 |
+
# تعداد کل ریپلایها
|
| 808 |
+
total_replies = 0
|
| 809 |
+
for user in data_manager.DATA['users'].values():
|
| 810 |
+
if 'context' in user:
|
| 811 |
+
total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
|
| 812 |
+
|
| 813 |
+
system_info = (
|
| 814 |
+
f"💻 **اطلاعات سیستم:**\n\n"
|
| 815 |
+
f"🖥️ سیستمعامل: {platform.system()} {platform.release()}\n"
|
| 816 |
+
f"🐍 نسخه پایتون: {platform.python_version()}\n"
|
| 817 |
+
f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
|
| 818 |
+
f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
|
| 819 |
+
f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
|
| 820 |
+
f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
|
| 821 |
+
f"⏱️ زمان اجرای ربات: {uptime}\n"
|
| 822 |
+
f"💭 کاربران با context: {users_with_context}\n"
|
| 823 |
+
f"💬 کل پیامهای context: {total_context_messages}\n"
|
| 824 |
+
f"📎 کل ریپلایهای ثبت شده: {total_replies}"
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
await update.message.reply_text(system_info, parse_mode='Markdown')
|
| 828 |
+
|
| 829 |
+
@admin_only
|
| 830 |
+
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 831 |
+
"""ریست کردن آمار ربات."""
|
| 832 |
+
if not context.args:
|
| 833 |
+
await update.message.reply_text("⚠️ لطفاً نوع آماری که میخواهید ریست کنید را مشخص کنید.\n"
|
| 834 |
+
"مثال: `/reset_stats messages` یا `/reset_stats all`")
|
| 835 |
+
return
|
| 836 |
+
|
| 837 |
+
stat_type = context.args[0].lower()
|
| 838 |
+
|
| 839 |
+
if stat_type == "messages":
|
| 840 |
+
data_manager.DATA['stats']['total_messages'] = 0
|
| 841 |
+
for user_id in data_manager.DATA['users']:
|
| 842 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 843 |
+
await update.message.reply_text("✅ آمار پیامها با موفقیت ریست شد.")
|
| 844 |
+
|
| 845 |
+
elif stat_type == "all":
|
| 846 |
+
data_manager.DATA['stats'] = {
|
| 847 |
+
'total_messages': 0,
|
| 848 |
+
'total_users': len(data_manager.DATA['users']),
|
| 849 |
+
'total_groups': len(data_manager.DATA['groups']),
|
| 850 |
+
'avg_response_time': 0,
|
| 851 |
+
'max_response_time': 0,
|
| 852 |
+
'min_response_time': 0,
|
| 853 |
+
'total_responses': 0
|
| 854 |
+
}
|
| 855 |
+
for user_id in data_manager.DATA['users']:
|
| 856 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 857 |
+
await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
|
| 858 |
+
|
| 859 |
+
else:
|
| 860 |
+
await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینههای موجود: messages, all")
|
| 861 |
+
return
|
| 862 |
+
|
| 863 |
+
data_manager.save_data()
|
| 864 |
+
|
| 865 |
+
# --- دستورات مدیریت context ---
|
| 866 |
+
@admin_only
|
| 867 |
+
async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 868 |
+
"""پاک کردن context یک کاربر"""
|
| 869 |
+
if not context.args or not context.args[0].isdigit():
|
| 870 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
|
| 871 |
+
return
|
| 872 |
+
|
| 873 |
+
user_id = int(context.args[0])
|
| 874 |
+
data_manager.clear_user_context(user_id)
|
| 875 |
+
|
| 876 |
+
await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
|
| 877 |
+
|
| 878 |
+
@admin_only
|
| 879 |
+
async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 880 |
+
"""مشاهده context یک کاربر"""
|
| 881 |
+
if not context.args or not context.args[0].isdigit():
|
| 882 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
|
| 883 |
+
return
|
| 884 |
+
|
| 885 |
+
user_id = int(context.args[0])
|
| 886 |
+
user_context = data_manager.get_user_context(user_id)
|
| 887 |
+
|
| 888 |
+
if not user_context:
|
| 889 |
+
await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
|
| 890 |
+
return
|
| 891 |
+
|
| 892 |
+
context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
|
| 893 |
+
total_tokens = 0
|
| 894 |
+
reply_count = 0
|
| 895 |
+
|
| 896 |
+
for i, msg in enumerate(user_context, 1):
|
| 897 |
+
role_emoji = "👤" if msg['role'] == 'user' else "🤖"
|
| 898 |
+
tokens = data_manager.count_tokens(msg['content'])
|
| 899 |
+
total_tokens += tokens
|
| 900 |
+
|
| 901 |
+
# بررسی ریپلای
|
| 902 |
+
has_reply = msg.get('has_reply', False)
|
| 903 |
+
if has_reply:
|
| 904 |
+
reply_count += 1
|
| 905 |
+
reply_emoji = "📎"
|
| 906 |
+
else:
|
| 907 |
+
reply_emoji = ""
|
| 908 |
+
|
| 909 |
+
content_preview = msg['content']
|
| 910 |
+
if len(content_preview) > 100:
|
| 911 |
+
content_preview = content_preview[:100] + "..."
|
| 912 |
+
|
| 913 |
+
context_text += f"{i}. {role_emoji} {reply_emoji} **{msg['role']}** ({tokens} توکن)\n"
|
| 914 |
+
context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
|
| 915 |
+
|
| 916 |
+
if has_reply:
|
| 917 |
+
context_text += f" 📎 ریپلای به: {msg.get('reply_to_user_name', 'Unknown')}\n"
|
| 918 |
+
|
| 919 |
+
context_text += f" 📝 {content_preview}\n\n"
|
| 920 |
+
|
| 921 |
+
context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن، {reply_count} ریپلای"
|
| 922 |
+
|
| 923 |
+
await update.message.reply_text(context_text, parse_mode='Markdown')
|
| 924 |
+
|
| 925 |
+
@admin_only
|
| 926 |
+
async def admin_view_replies(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 927 |
+
"""مشاهده ریپلایهای یک کاربر یا گروه"""
|
| 928 |
+
if len(context.args) < 2:
|
| 929 |
+
await update.message.reply_text(
|
| 930 |
+
"⚠️ فرمت صحیح: `/view_replies [user|group] [آیدی]`\n"
|
| 931 |
+
"مثال: `/view_replies user 123456789`\n"
|
| 932 |
+
"مثال: `/view_replies group -1001234567890`"
|
| 933 |
+
)
|
| 934 |
+
return
|
| 935 |
+
|
| 936 |
+
entity_type = context.args[0].lower()
|
| 937 |
+
entity_id = context.args[1]
|
| 938 |
+
|
| 939 |
+
if entity_type == 'user':
|
| 940 |
+
try:
|
| 941 |
+
user_id = int(entity_id)
|
| 942 |
+
user_context = data_manager.get_user_context(user_id)
|
| 943 |
+
if not user_context:
|
| 944 |
+
await update.message.reply_text(f"کاربر `{entity_id}` context ندارد.")
|
| 945 |
+
return
|
| 946 |
+
|
| 947 |
+
replies = [msg for msg in user_context if msg.get('has_reply', False)]
|
| 948 |
+
|
| 949 |
+
if not replies:
|
| 950 |
+
await update.message.reply_text(f"کاربر `{entity_id}` هیچ ریپلایای ثبت نکرده است.")
|
| 951 |
+
return
|
| 952 |
+
|
| 953 |
+
text = f"📋 **ریپلایهای کاربر `{entity_id}`**\n\n"
|
| 954 |
+
for i, msg in enumerate(replies, 1):
|
| 955 |
+
text += f"{i}. **زمان:** {msg.get('timestamp', 'N/A')}\n"
|
| 956 |
+
text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
|
| 957 |
+
if msg.get('is_reply_to_bot', False):
|
| 958 |
+
text += f" **نوع:** ریپلای به ربات 🤖\n"
|
| 959 |
+
else:
|
| 960 |
+
text += f" **نوع:** ریپلای به کاربر\n"
|
| 961 |
+
text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
|
| 962 |
+
text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
|
| 963 |
+
|
| 964 |
+
text += f"📊 **مجموع:** {len(replies)} ریپلای"
|
| 965 |
+
|
| 966 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 967 |
+
except ValueError:
|
| 968 |
+
await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
|
| 969 |
+
|
| 970 |
+
elif entity_type == 'group':
|
| 971 |
+
try:
|
| 972 |
+
chat_id = int(entity_id)
|
| 973 |
+
group_context = data_manager.get_group_context(chat_id)
|
| 974 |
+
if not group_context:
|
| 975 |
+
await update.message.reply_text(f"گروه `{entity_id}` context ندارد.")
|
| 976 |
+
return
|
| 977 |
+
|
| 978 |
+
replies = [msg for msg in group_context if msg.get('has_reply', False)]
|
| 979 |
+
|
| 980 |
+
if not replies:
|
| 981 |
+
await update.message.reply_text(f"گروه `{entity_id}` هیچ ریپلایای ثبت نکرده است.")
|
| 982 |
+
return
|
| 983 |
+
|
| 984 |
+
text = f"📋 **ریپلایهای گروه `{entity_id}`**\n\n"
|
| 985 |
+
for i, msg in enumerate(replies, 1):
|
| 986 |
+
user_name = msg.get('user_name', 'Unknown')
|
| 987 |
+
text += f"{i}. **کاربر:** {user_name}\n"
|
| 988 |
+
text += f" **زمان:** {msg.get('timestamp', 'N/A')}\n"
|
| 989 |
+
text += f" **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
|
| 990 |
+
if msg.get('is_reply_to_bot', False):
|
| 991 |
+
text += f" **نوع:** ریپلای به ربات 🤖\n"
|
| 992 |
+
else:
|
| 993 |
+
text += f" **نوع:** ریپلای به کاربر\n"
|
| 994 |
+
text += f" **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
|
| 995 |
+
text += f" **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
|
| 996 |
+
|
| 997 |
+
text += f"📊 **مجموع:** {len(replies)} ریپلای"
|
| 998 |
+
|
| 999 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 1000 |
+
except ValueError:
|
| 1001 |
+
await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
|
| 1002 |
+
|
| 1003 |
+
else:
|
| 1004 |
+
await update.message.reply_text("⚠️ نوع نامعتبر. فقط 'user' یا 'group' مجاز است.")
|
| 1005 |
+
|
| 1006 |
+
# --- دستورات جدید برای مدیریت گروهها ---
|
| 1007 |
+
@admin_only
|
| 1008 |
+
async def admin_set_context_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 1009 |
+
"""تنظیم حالت context ربات"""
|
| 1010 |
+
if not context.args or context.args[0].lower() not in ['separate', 'group_shared', 'hybrid']:
|
| 1011 |
+
await update.message.reply_text(
|
| 1012 |
+
"⚠️ فرمت صحیح: `/set_context_mode [separate|group_shared|hybrid]`\n\n"
|
| 1013 |
+
"• **separate**: هر کاربر context جداگانه دارد (8192 توکن)\n"
|
| 1014 |
+
"• **group_shared**: همه کاربران در یک گروه context مشترک دارند (16384 توکن)\n"
|
| 1015 |
+
"• **hybrid**: ترکیبی از context شخصی و گروهی\n\n"
|
| 1016 |
+
"💡 **توجه:** حالت group_shared حافظه بیشتری برای گروهها فراهم میکند."
|
| 1017 |
+
)
|
| 1018 |
+
return
|
| 1019 |
+
|
| 1020 |
+
mode = context.args[0].lower()
|
| 1021 |
+
if data_manager.set_context_mode(mode):
|
| 1022 |
+
await update.message.reply_text(f"✅ حالت context به `{mode}` تغییر یافت.")
|
| 1023 |
+
else:
|
| 1024 |
+
await update.message.reply_text("❌ خطا در تغییر حالت context.")
|
| 1025 |
+
|
| 1026 |
+
@admin_only
|
| 1027 |
+
async def admin_group_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 1028 |
+
"""نمایش اطلاعات یک گروه"""
|
| 1029 |
+
if not context.args or not context.args[0].lstrip('-').isdigit():
|
| 1030 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی گروه را وارد کنید.\nمثال: `/group_info -1001234567890`")
|
| 1031 |
+
return
|
| 1032 |
+
|
| 1033 |
+
chat_id = int(context.args[0])
|
| 1034 |
+
group_info = data_manager.DATA['groups'].get(str(chat_id))
|
| 1035 |
+
|
| 1036 |
+
if not group_info:
|
| 1037 |
+
await update.message.reply_text(f"گروهی با آیدی `{chat_id}` در دیتابیس یافت نشد.")
|
| 1038 |
+
return
|
| 1039 |
+
|
| 1040 |
+
# تبدیل set اعضا به لیست برای نمایش
|
| 1041 |
+
members = list(group_info.get('members', set()))
|
| 1042 |
+
members_count = len(members)
|
| 1043 |
+
|
| 1044 |
+
# اطلاعات context گروه
|
| 1045 |
+
context_messages = len(group_info.get('context', []))
|
| 1046 |
+
total_tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info.get('context', []))
|
| 1047 |
+
|
| 1048 |
+
# تعداد ریپلایها در گروه
|
| 1049 |
+
reply_count = 0
|
| 1050 |
+
if 'context' in group_info:
|
| 1051 |
+
reply_count = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
|
| 1052 |
+
|
| 1053 |
+
text = (
|
| 1054 |
+
f"📊 **اطلاعات گروه**\n\n"
|
| 1055 |
+
f"🆔 **آیدی:** `{chat_id}`\n"
|
| 1056 |
+
f"🏷️ **عنوان:** {group_info.get('title', 'N/A')}\n"
|
| 1057 |
+
f"📝 **تعداد پیامها:** `{group_info.get('message_count', 0)}`\n"
|
| 1058 |
+
f"👥 **تعداد اعضا:** `{members_count}`\n"
|
| 1059 |
+
f"💭 **پیامهای context:** `{context_messages}`\n"
|
| 1060 |
+
f"📎 **تعداد ریپلایها:** `{reply_count}`\n"
|
| 1061 |
+
f"🔢 **توکنهای context:** `{total_tokens}`\n"
|
| 1062 |
+
f"📅 **اولین فعالیت:** {group_info.get('first_seen', 'N/A')}\n"
|
| 1063 |
+
f"🕒 **آخرین فعالیت:** {group_info.get('last_seen', 'N/A')}"
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 1067 |
+
|
| 1068 |
+
@admin_only
|
| 1069 |
+
async def admin_clear_group_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 1070 |
+
"""پاک کردن context یک گروه"""
|
| 1071 |
+
if not context.args or not context.args[0].lstrip('-').isdigit():
|
| 1072 |
+
await update.message.reply_text("⚠️ لطفاً آیدی گروه را وارد کنید.\nمثال: `/clear_group_context -1001234567890`")
|
| 1073 |
+
return
|
| 1074 |
+
|
| 1075 |
+
chat_id = int(context.args[0])
|
| 1076 |
+
data_manager.clear_group_context(chat_id)
|
| 1077 |
+
|
| 1078 |
+
await update.message.reply_text(f"✅ context گروه `{chat_id}` با موفقیت پاک شد.")
|
| 1079 |
+
|
| 1080 |
+
@admin_only
|
| 1081 |
+
async def admin_memory_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 1082 |
+
"""نمایش وضعیت حافظه و context گروهها"""
|
| 1083 |
+
groups = data_manager.DATA['groups']
|
| 1084 |
+
|
| 1085 |
+
if not groups:
|
| 1086 |
+
await update.message.reply_text("هیچ گروهی در دیتابیس وجود ندارد.")
|
| 1087 |
+
return
|
| 1088 |
+
|
| 1089 |
+
# محاسبه آمار
|
| 1090 |
+
total_groups = len(groups)
|
| 1091 |
+
groups_with_context = sum(1 for g in groups.values() if g.get('context'))
|
| 1092 |
+
total_context_messages = sum(len(g.get('context', [])) for g in groups.values())
|
| 1093 |
+
total_context_tokens = 0
|
| 1094 |
+
total_replies = 0
|
| 1095 |
+
|
| 1096 |
+
for group_id, group_info in groups.items():
|
| 1097 |
+
if 'context' in group_info:
|
| 1098 |
+
total_context_tokens += sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
|
| 1099 |
+
total_replies += sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
|
| 1100 |
+
|
| 1101 |
+
# لیست گروههایی که بیشترین استفاده از حافظه را دارند
|
| 1102 |
+
groups_by_tokens = []
|
| 1103 |
+
for group_id, group_info in groups.items():
|
| 1104 |
+
if 'context' in group_info:
|
| 1105 |
+
tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
|
| 1106 |
+
messages = len(group_info['context'])
|
| 1107 |
+
replies = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
|
| 1108 |
+
groups_by_tokens.append((group_id, tokens, messages, replies))
|
| 1109 |
+
|
| 1110 |
+
# مرتبسازی بر اساس تعداد توکن
|
| 1111 |
+
groups_by_tokens.sort(key=lambda x: x[1], reverse=True)
|
| 1112 |
+
|
| 1113 |
+
status_text = (
|
| 1114 |
+
f"💾 **وضعیت حافظه گروهها**\n\n"
|
| 1115 |
+
f"📊 **آمار کلی:**\n"
|
| 1116 |
+
f"• تعداد کل گروهها: `{total_groups}`\n"
|
| 1117 |
+
f"• گروههای دارای context: `{groups_with_context}`\n"
|
| 1118 |
+
f"• کل پیامهای context: `{total_context_messages}`\n"
|
| 1119 |
+
f"• کل ریپلایها: `{total_replies}`\n"
|
| 1120 |
+
f"• کل توکنهای استفاده شده: `{total_context_tokens}`\n"
|
| 1121 |
+
f"• میانگین توکن per گروه: `{total_context_tokens/max(1, groups_with_context):.0f}`\n\n"
|
| 1122 |
+
f"🏆 **گروههای با بیشترین استفاده از حافظه:**\n"
|
| 1123 |
+
)
|
| 1124 |
+
|
| 1125 |
+
for i, (group_id, tokens, messages, replies) in enumerate(groups_by_tokens[:10], 1):
|
| 1126 |
+
usage_percent = (tokens / 16384) * 100
|
| 1127 |
+
status_text += f"{i}. گروه `{group_id}`: {messages} پیام، {replies} ریپلای، {tokens} توکن ({usage_percent:.1f}%)\n"
|
| 1128 |
+
|
| 1129 |
+
await update.message.reply_text(status_text, parse_mode='Markdown')
|
| 1130 |
+
|
| 1131 |
+
# --- هندلر برای دکمههای صفحهبندی ---
|
| 1132 |
+
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 1133 |
+
"""پردازش دکمههای صفحهبندی لیست کاربران."""
|
| 1134 |
+
query = update.callback_query
|
| 1135 |
+
await query.answer()
|
| 1136 |
+
|
| 1137 |
+
if query.data.startswith("users_list:"):
|
| 1138 |
+
page = int(query.data.split(":")[1])
|
| 1139 |
+
context.args = [str(page)]
|
| 1140 |
+
await admin_users_list(update, context)
|
| 1141 |
+
|
| 1142 |
+
# --- تابع برای پردازش ارسالهای ��رنامهریزی شده ---
|
| 1143 |
+
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
|
| 1144 |
+
"""پردازش ارسالهای برنامهریزی شده و ارسال پیامها در زمان مقرر."""
|
| 1145 |
+
now = datetime.now()
|
| 1146 |
+
broadcasts_to_send_indices = []
|
| 1147 |
+
|
| 1148 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
|
| 1149 |
+
if broadcast['status'] == 'pending':
|
| 1150 |
+
broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
|
| 1151 |
+
if broadcast_time <= now:
|
| 1152 |
+
broadcasts_to_send_indices.append(i)
|
| 1153 |
+
|
| 1154 |
+
if not broadcasts_to_send_indices:
|
| 1155 |
+
return
|
| 1156 |
+
|
| 1157 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 1158 |
+
|
| 1159 |
+
for index in broadcasts_to_send_indices:
|
| 1160 |
+
broadcast = data_manager.DATA['scheduled_broadcasts'][index]
|
| 1161 |
+
message_text = broadcast['message']
|
| 1162 |
+
total_sent, total_failed = 0, 0
|
| 1163 |
+
|
| 1164 |
+
for user_id_str in user_ids:
|
| 1165 |
+
try:
|
| 1166 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 1167 |
+
total_sent += 1
|
| 1168 |
+
await asyncio.sleep(0.05)
|
| 1169 |
+
except TelegramError as e:
|
| 1170 |
+
logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
|
| 1171 |
+
total_failed += 1
|
| 1172 |
+
|
| 1173 |
+
# بهروزرسانی وضعیت ارسال
|
| 1174 |
+
data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
|
| 1175 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
|
| 1176 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
|
| 1177 |
+
data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
|
| 1178 |
+
|
| 1179 |
+
logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
|
| 1180 |
+
|
| 1181 |
+
data_manager.save_data()
|
| 1182 |
+
|
| 1183 |
+
# --- تابع راهاندازی هندلرها ---
|
| 1184 |
+
def setup_admin_handlers(application):
|
| 1185 |
+
"""هندلرهای پنل ادمین را به اپلیکیشن اضافه میکند."""
|
| 1186 |
+
# هندلرهای اصلی
|
| 1187 |
+
application.add_handler(CommandHandler("commands", admin_commands))
|
| 1188 |
+
application.add_handler(CommandHandler("stats", admin_stats))
|
| 1189 |
+
application.add_handler(CommandHandler("broadcast", admin_broadcast))
|
| 1190 |
+
application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
|
| 1191 |
+
application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
|
| 1192 |
+
application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
|
| 1193 |
+
application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
|
| 1194 |
+
application.add_handler(CommandHandler("ban", admin_ban))
|
| 1195 |
+
application.add_handler(CommandHandler("unban", admin_unban))
|
| 1196 |
+
application.add_handler(CommandHandler("direct_message", admin_direct_message))
|
| 1197 |
+
application.add_handler(CommandHandler("user_info", admin_userinfo))
|
| 1198 |
+
application.add_handler(CommandHandler("logs", admin_logs))
|
| 1199 |
+
application.add_handler(CommandHandler("logs_file", admin_logs_file))
|
| 1200 |
+
application.add_handler(CommandHandler("users_list", admin_users_list))
|
| 1201 |
+
application.add_handler(CommandHandler("user_search", admin_user_search))
|
| 1202 |
+
application.add_handler(CommandHandler("backup", admin_backup))
|
| 1203 |
+
application.add_handler(CommandHandler("export_csv", admin_export_csv))
|
| 1204 |
+
application.add_handler(CommandHandler("maintenance", admin_maintenance))
|
| 1205 |
+
application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
|
| 1206 |
+
application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
|
| 1207 |
+
application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
|
| 1208 |
+
application.add_handler(CommandHandler("response_stats", admin_response_stats))
|
| 1209 |
+
application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
|
| 1210 |
+
application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
|
| 1211 |
+
application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
|
| 1212 |
+
application.add_handler(CommandHandler("system_info", admin_system_info))
|
| 1213 |
+
application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
|
| 1214 |
+
|
| 1215 |
+
# هندلرهای مدیریت context
|
| 1216 |
+
application.add_handler(CommandHandler("clear_context", admin_clear_context))
|
| 1217 |
+
application.add_handler(CommandHandler("view_context", admin_view_context))
|
| 1218 |
+
application.add_handler(CommandHandler("view_replies", admin_view_replies))
|
| 1219 |
+
|
| 1220 |
+
# هندلرهای جدید برای مدیریت گروهها
|
| 1221 |
+
application.add_handler(CommandHandler("set_context_mode", admin_set_context_mode))
|
| 1222 |
+
application.add_handler(CommandHandler("group_info", admin_group_info))
|
| 1223 |
+
application.add_handler(CommandHandler("clear_group_context", admin_clear_group_context))
|
| 1224 |
+
application.add_handler(CommandHandler("memory_status", admin_memory_status))
|
| 1225 |
+
|
| 1226 |
+
# هندلر برای دکمههای صفحهبندی
|
| 1227 |
+
application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
|
| 1228 |
+
|
| 1229 |
+
# شروع وظیفه دورهای برای بررسی ارسالهای برنامهریزی شده
|
| 1230 |
+
application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
|
| 1231 |
+
|
| 1232 |
+
logger.info("Admin panel handlers have been set up.")
|
Version2_Context/2/data_manager.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
}
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
# --- توابع کمکی ---
|
| 41 |
+
def count_tokens(text: str) -> int:
|
| 42 |
+
"""شمارش تعداد توکنهای متن با استفاده از tokenizer"""
|
| 43 |
+
try:
|
| 44 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 45 |
+
return len(encoding.encode(text))
|
| 46 |
+
except Exception as e:
|
| 47 |
+
logger.warning(f"Error counting tokens: {e}, using fallback")
|
| 48 |
+
return max(1, len(text) // 4)
|
| 49 |
+
|
| 50 |
+
def load_data():
|
| 51 |
+
"""دادهها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره میکند."""
|
| 52 |
+
global DATA
|
| 53 |
+
try:
|
| 54 |
+
if not os.path.exists(DATA_FILE):
|
| 55 |
+
logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد میشود.")
|
| 56 |
+
save_data()
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
| 60 |
+
loaded_data = json.load(f)
|
| 61 |
+
loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
|
| 62 |
+
|
| 63 |
+
# اطمینان از وجود کلیدهای جدید
|
| 64 |
+
if 'groups' not in loaded_data: loaded_data['groups'] = {}
|
| 65 |
+
if 'context_mode' not in loaded_data: loaded_data['context_mode'] = 'separate'
|
| 66 |
+
if 'group_welcome_message' not in loaded_data:
|
| 67 |
+
loaded_data['group_welcome_message'] = "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم..."
|
| 68 |
+
if 'total_groups' not in loaded_data.get('stats', {}):
|
| 69 |
+
if 'stats' not in loaded_data: loaded_data['stats'] = {}
|
| 70 |
+
loaded_data['stats']['total_groups'] = len(loaded_data.get('groups', {}))
|
| 71 |
+
|
| 72 |
+
# تبدیل اعضای گروه از list به set
|
| 73 |
+
for group_id in loaded_data.get('groups', {}):
|
| 74 |
+
if 'members' in loaded_data['groups'][group_id]:
|
| 75 |
+
# اگر members یک list است، آن را به set تبدیل کن
|
| 76 |
+
if isinstance(loaded_data['groups'][group_id]['members'], list):
|
| 77 |
+
loaded_data['groups'][group_id]['members'] = set(loaded_data['groups'][group_id]['members'])
|
| 78 |
+
elif not isinstance(loaded_data['groups'][group_id]['members'], set):
|
| 79 |
+
# اگر نه list است نه set، آن را set خالی کن
|
| 80 |
+
loaded_data['groups'][group_id]['members'] = set()
|
| 81 |
+
else:
|
| 82 |
+
loaded_data['groups'][group_id]['members'] = set()
|
| 83 |
+
|
| 84 |
+
# اطمینان از وجود context برای گروههای قدیمی
|
| 85 |
+
for group_id in loaded_data.get('groups', {}):
|
| 86 |
+
if 'context' not in loaded_data['groups'][group_id]:
|
| 87 |
+
loaded_data['groups'][group_id]['context'] = []
|
| 88 |
+
|
| 89 |
+
# اطمینان از وجود context برای کاربران قدیمی
|
| 90 |
+
for user_id in loaded_data.get('users', {}):
|
| 91 |
+
if 'context' not in loaded_data['users'][user_id]:
|
| 92 |
+
loaded_data['users'][user_id]['context'] = []
|
| 93 |
+
|
| 94 |
+
# اطمینان از وجود کلیدهای آمار پاسخگویی
|
| 95 |
+
if 'stats' in loaded_data:
|
| 96 |
+
stats_keys = ['avg_response_time', 'max_response_time', 'min_response_time', 'total_responses']
|
| 97 |
+
for key in stats_keys:
|
| 98 |
+
if key not in loaded_data['stats']:
|
| 99 |
+
if key == 'min_response_time':
|
| 100 |
+
loaded_data['stats'][key] = float('inf')
|
| 101 |
+
else:
|
| 102 |
+
loaded_data['stats'][key] = 0.0
|
| 103 |
+
|
| 104 |
+
DATA.update(loaded_data)
|
| 105 |
+
logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.")
|
| 106 |
+
|
| 107 |
+
except json.JSONDecodeError as e:
|
| 108 |
+
logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 109 |
+
except Exception as e:
|
| 110 |
+
logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 111 |
+
|
| 112 |
+
def save_data():
|
| 113 |
+
"""کش گلوبال دادهها را در فایل JSON ذخیره میکند."""
|
| 114 |
+
global DATA
|
| 115 |
+
try:
|
| 116 |
+
data_to_save = DATA.copy()
|
| 117 |
+
data_to_save['banned_users'] = list(DATA['banned_users'])
|
| 118 |
+
|
| 119 |
+
# تبدیل set اعضای گروه به list برای ذخیره JSON
|
| 120 |
+
for group_id in data_to_save.get('groups', {}):
|
| 121 |
+
if 'members' in data_to_save['groups'][group_id]:
|
| 122 |
+
# اگر members یک set است، آن را به list تبدیل کن
|
| 123 |
+
if isinstance(data_to_save['groups'][group_id]['members'], set):
|
| 124 |
+
data_to_save['groups'][group_id]['members'] = list(data_to_save['groups'][group_id]['members'])
|
| 125 |
+
elif not isinstance(data_to_save['groups'][group_id]['members'], list):
|
| 126 |
+
# اگر نه set است نه list، آن را list خالی کن
|
| 127 |
+
data_to_save['groups'][group_id]['members'] = []
|
| 128 |
+
|
| 129 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 130 |
+
json.dump(data_to_save, f, indent=4, ensure_ascii=False)
|
| 131 |
+
logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.")
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}")
|
| 134 |
+
|
| 135 |
+
# --- توابع مدیریت کاربران ---
|
| 136 |
+
def update_user_stats(user_id: int, user):
|
| 137 |
+
"""آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند."""
|
| 138 |
+
global DATA
|
| 139 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 140 |
+
user_id_str = str(user_id)
|
| 141 |
+
|
| 142 |
+
if user_id_str not in DATA['users']:
|
| 143 |
+
DATA['users'][user_id_str] = {
|
| 144 |
+
'first_name': user.first_name,
|
| 145 |
+
'username': user.username,
|
| 146 |
+
'first_seen': now_str,
|
| 147 |
+
'message_count': 0,
|
| 148 |
+
'context': []
|
| 149 |
+
}
|
| 150 |
+
DATA['stats']['total_users'] += 1
|
| 151 |
+
logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
|
| 152 |
+
|
| 153 |
+
DATA['users'][user_id_str]['last_seen'] = now_str
|
| 154 |
+
DATA['users'][user_id_str]['message_count'] += 1
|
| 155 |
+
DATA['stats']['total_messages'] += 1
|
| 156 |
+
|
| 157 |
+
save_data()
|
| 158 |
+
|
| 159 |
+
def update_response_stats(response_time: float):
|
| 160 |
+
"""آمار زمان پاسخگویی را بهروز میکند."""
|
| 161 |
+
global DATA
|
| 162 |
+
|
| 163 |
+
if DATA['stats']['total_responses'] == 0:
|
| 164 |
+
DATA['stats']['min_response_time'] = response_time
|
| 165 |
+
|
| 166 |
+
DATA['stats']['total_responses'] += 1
|
| 167 |
+
|
| 168 |
+
# محاسبه میانگین جدید
|
| 169 |
+
current_avg = DATA['stats']['avg_response_time']
|
| 170 |
+
total_responses = DATA['stats']['total_responses']
|
| 171 |
+
new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
|
| 172 |
+
DATA['stats']['avg_response_time'] = new_avg
|
| 173 |
+
|
| 174 |
+
# بهروزرسانی حداکثر و حداقل زمان پاسخگویی
|
| 175 |
+
if response_time > DATA['stats']['max_response_time']:
|
| 176 |
+
DATA['stats']['max_response_time'] = response_time
|
| 177 |
+
|
| 178 |
+
if response_time < DATA['stats']['min_response_time']:
|
| 179 |
+
DATA['stats']['min_response_time'] = response_time
|
| 180 |
+
|
| 181 |
+
save_data()
|
| 182 |
+
|
| 183 |
+
# --- توابع مدیریت مسدودیت ---
|
| 184 |
+
def is_user_banned(user_id: int) -> bool:
|
| 185 |
+
"""بررسی میکند آیا کاربر مسدود شده است یا خیر."""
|
| 186 |
+
return user_id in DATA['banned_users']
|
| 187 |
+
|
| 188 |
+
def ban_user(user_id: int):
|
| 189 |
+
"""کاربر را مسدود کرده و ذخیره میکند."""
|
| 190 |
+
DATA['banned_users'].add(user_id)
|
| 191 |
+
save_data()
|
| 192 |
+
|
| 193 |
+
def unban_user(user_id: int):
|
| 194 |
+
"""مسدودیت کاربر را برداشته و ذخیره میکند."""
|
| 195 |
+
DATA['banned_users'].discard(user_id)
|
| 196 |
+
save_data()
|
| 197 |
+
|
| 198 |
+
def contains_blocked_words(text: str) -> bool:
|
| 199 |
+
"""بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر."""
|
| 200 |
+
if not DATA['blocked_words']:
|
| 201 |
+
return False
|
| 202 |
+
|
| 203 |
+
text_lower = text.lower()
|
| 204 |
+
for word in DATA['blocked_words']:
|
| 205 |
+
if word in text_lower:
|
| 206 |
+
return True
|
| 207 |
+
|
| 208 |
+
return False
|
| 209 |
+
|
| 210 |
+
# --- توابع مدیریت کاربران و گروهها ---
|
| 211 |
+
def get_active_users(days: int) -> list:
|
| 212 |
+
"""لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند."""
|
| 213 |
+
now = datetime.now()
|
| 214 |
+
cutoff_date = now - timedelta(days=days)
|
| 215 |
+
|
| 216 |
+
active_users = []
|
| 217 |
+
for user_id, user_info in DATA['users'].items():
|
| 218 |
+
if 'last_seen' in user_info:
|
| 219 |
+
try:
|
| 220 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 221 |
+
if last_seen >= cutoff_date:
|
| 222 |
+
active_users.append(int(user_id))
|
| 223 |
+
except ValueError:
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
return active_users
|
| 227 |
+
|
| 228 |
+
def get_users_by_message_count(min_count: int) -> list:
|
| 229 |
+
"""لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند."""
|
| 230 |
+
users = []
|
| 231 |
+
for user_id, user_info in DATA['users'].items():
|
| 232 |
+
if user_info.get('message_count', 0) >= min_count:
|
| 233 |
+
users.append(int(user_id))
|
| 234 |
+
|
| 235 |
+
return users
|
| 236 |
+
|
| 237 |
+
# --- توابع مدیریت context کاربران ---
|
| 238 |
+
def add_to_user_context(user_id: int, role: str, content: str):
|
| 239 |
+
"""اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن"""
|
| 240 |
+
add_to_user_context_with_reply(user_id, role, content, None)
|
| 241 |
+
|
| 242 |
+
def add_to_user_context_with_reply(user_id: int, role: str, content: str, reply_info: dict = None):
|
| 243 |
+
"""اضافه کردن پیام به context کاربر با اطلاعات ریپلای"""
|
| 244 |
+
user_id_str = str(user_id)
|
| 245 |
+
|
| 246 |
+
if user_id_str not in DATA['users']:
|
| 247 |
+
return
|
| 248 |
+
|
| 249 |
+
if 'context' not in DATA['users'][user_id_str]:
|
| 250 |
+
DATA['users'][user_id_str]['context'] = []
|
| 251 |
+
|
| 252 |
+
# اضافه کردن پیام جدید
|
| 253 |
+
message = {
|
| 254 |
+
'role': role,
|
| 255 |
+
'content': content,
|
| 256 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 257 |
+
'has_reply': False
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
|
| 261 |
+
message['has_reply'] = True
|
| 262 |
+
message['reply_to_user_id'] = reply_info.get('replied_user_id')
|
| 263 |
+
message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
|
| 264 |
+
message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن
|
| 265 |
+
message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
|
| 266 |
+
message['reply_timestamp'] = reply_info.get('timestamp', time.time())
|
| 267 |
+
|
| 268 |
+
DATA['users'][user_id_str]['context'].append(message)
|
| 269 |
+
|
| 270 |
+
# محدود کردن context به 8192 توکن
|
| 271 |
+
trim_user_context(user_id, max_tokens=8192)
|
| 272 |
+
|
| 273 |
+
save_data()
|
| 274 |
+
|
| 275 |
+
def trim_user_context(user_id: int, max_tokens: int = 8192):
|
| 276 |
+
"""کوتاه کردن context کاربر به تعداد توکن مشخص"""
|
| 277 |
+
user_id_str = str(user_id)
|
| 278 |
+
|
| 279 |
+
if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
|
| 280 |
+
return
|
| 281 |
+
|
| 282 |
+
context = DATA['users'][user_id_str]['context']
|
| 283 |
+
|
| 284 |
+
if not context:
|
| 285 |
+
return
|
| 286 |
+
|
| 287 |
+
# محاسبه توکنهای کل
|
| 288 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 289 |
+
|
| 290 |
+
# حذف قدیمیترین پیامها تا زمانی که توکنها زیر حد مجاز باشد
|
| 291 |
+
while total_tokens > max_tokens and len(context) > 1:
|
| 292 |
+
removed_message = context.pop(0)
|
| 293 |
+
total_tokens -= count_tokens(removed_message['content'])
|
| 294 |
+
|
| 295 |
+
# اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن
|
| 296 |
+
if total_tokens > max_tokens and context:
|
| 297 |
+
last_message = context[-1]
|
| 298 |
+
content = last_message['content']
|
| 299 |
+
|
| 300 |
+
tokens = count_tokens(content)
|
| 301 |
+
if tokens > max_tokens:
|
| 302 |
+
context.pop()
|
| 303 |
+
else:
|
| 304 |
+
while tokens > (max_tokens - (total_tokens - tokens)) and content:
|
| 305 |
+
words = content.split()
|
| 306 |
+
if len(words) > 1:
|
| 307 |
+
content = ' '.join(words[:-1])
|
| 308 |
+
else:
|
| 309 |
+
content = content[:-1] if len(content) > 1 else ''
|
| 310 |
+
tokens = count_tokens(content)
|
| 311 |
+
|
| 312 |
+
if content:
|
| 313 |
+
context[-1]['content'] = content
|
| 314 |
+
else:
|
| 315 |
+
context.pop()
|
| 316 |
+
|
| 317 |
+
save_data()
|
| 318 |
+
|
| 319 |
+
def get_user_context(user_id: int) -> list:
|
| 320 |
+
"""دریافت context کاربر"""
|
| 321 |
+
user_id_str = str(user_id)
|
| 322 |
+
|
| 323 |
+
if user_id_str not in DATA['users']:
|
| 324 |
+
return []
|
| 325 |
+
|
| 326 |
+
return DATA['users'][user_id_str].get('context', [])
|
| 327 |
+
|
| 328 |
+
def clear_user_context(user_id: int):
|
| 329 |
+
"""پاک کردن context کاربر"""
|
| 330 |
+
user_id_str = str(user_id)
|
| 331 |
+
|
| 332 |
+
if user_id_str in DATA['users']:
|
| 333 |
+
if 'context' in DATA['users'][user_id_str]:
|
| 334 |
+
DATA['users'][user_id_str]['context'] = []
|
| 335 |
+
save_data()
|
| 336 |
+
logger.info(f"Context cleared for user {user_id}")
|
| 337 |
+
|
| 338 |
+
def get_context_summary(user_id: int) -> str:
|
| 339 |
+
"""خلاصهای از context کاربر"""
|
| 340 |
+
context = get_user_context(user_id)
|
| 341 |
+
if not context:
|
| 342 |
+
return "بدون تاریخچه"
|
| 343 |
+
|
| 344 |
+
total_messages = len(context)
|
| 345 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 346 |
+
|
| 347 |
+
# تعداد ریپلای��ها
|
| 348 |
+
reply_count = sum(1 for msg in context if msg.get('has_reply', False))
|
| 349 |
+
|
| 350 |
+
# نمایش آخرین پیام
|
| 351 |
+
last_message = context[-1] if context else {}
|
| 352 |
+
last_content = last_message.get('content', '')[:50]
|
| 353 |
+
if len(last_message.get('content', '')) > 50:
|
| 354 |
+
last_content += "..."
|
| 355 |
+
|
| 356 |
+
return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('role', '')}: {last_content}"
|
| 357 |
+
|
| 358 |
+
def get_context_for_api(user_id: int) -> list:
|
| 359 |
+
"""فرمت context برای ارسال به API"""
|
| 360 |
+
context = get_user_context(user_id)
|
| 361 |
+
|
| 362 |
+
api_context = []
|
| 363 |
+
for msg in context:
|
| 364 |
+
api_context.append({
|
| 365 |
+
'role': msg['role'],
|
| 366 |
+
'content': msg['content']
|
| 367 |
+
})
|
| 368 |
+
|
| 369 |
+
return api_context
|
| 370 |
+
|
| 371 |
+
def get_context_token_count(user_id: int) -> int:
|
| 372 |
+
"""تعداد کل توکنهای context کاربر"""
|
| 373 |
+
context = get_user_context(user_id)
|
| 374 |
+
return sum(count_tokens(msg['content']) for msg in context)
|
| 375 |
+
|
| 376 |
+
# --- توابع مدیریت گروهها ---
|
| 377 |
+
def update_group_stats(chat_id: int, chat, user_id: int = None):
|
| 378 |
+
"""آمار گروه را بهروز کرده و دادهها را ذخیره میکند."""
|
| 379 |
+
global DATA
|
| 380 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 381 |
+
chat_id_str = str(chat_id)
|
| 382 |
+
|
| 383 |
+
if chat_id_str not in DATA['groups']:
|
| 384 |
+
DATA['groups'][chat_id_str] = {
|
| 385 |
+
'title': chat.title if hasattr(chat, 'title') else 'Private Group',
|
| 386 |
+
'type': chat.type,
|
| 387 |
+
'first_seen': now_str,
|
| 388 |
+
'message_count': 0,
|
| 389 |
+
'members': set(),
|
| 390 |
+
'context': []
|
| 391 |
+
}
|
| 392 |
+
DATA['stats']['total_groups'] += 1
|
| 393 |
+
logger.info(f"گروه جدید ثبت شد: {chat_id} ({chat.title if hasattr(chat, 'title') else 'Private'})")
|
| 394 |
+
|
| 395 |
+
DATA['groups'][chat_id_str]['last_seen'] = now_str
|
| 396 |
+
DATA['groups'][chat_id_str]['message_count'] += 1
|
| 397 |
+
|
| 398 |
+
# اضافه کردن کاربر به لیست اعضای گروه
|
| 399 |
+
if user_id is not None:
|
| 400 |
+
# اطمینان از اینکه members یک set است
|
| 401 |
+
if 'members' not in DATA['groups'][chat_id_str]:
|
| 402 |
+
DATA['groups'][chat_id_str]['members'] = set()
|
| 403 |
+
elif isinstance(DATA['groups'][chat_id_str]['members'], list):
|
| 404 |
+
# اگر members یک list است، آن را به set تبدیل کن
|
| 405 |
+
DATA['groups'][chat_id_str]['members'] = set(DATA['groups'][chat_id_str]['members'])
|
| 406 |
+
|
| 407 |
+
# اکنون اضافه کردن کاربر
|
| 408 |
+
DATA['groups'][chat_id_str]['members'].add(user_id)
|
| 409 |
+
|
| 410 |
+
save_data()
|
| 411 |
+
|
| 412 |
+
def add_to_group_context(chat_id: int, role: str, content: str, user_name: str = None):
|
| 413 |
+
"""اضافه کردن پیام به context گروه و محدود کردن به 8192 توکن"""
|
| 414 |
+
add_to_group_context_with_reply(chat_id, role, content, user_name, None)
|
| 415 |
+
|
| 416 |
+
def add_to_group_context_with_reply(chat_id: int, role: str, content: str, user_name: str = None, reply_info: dict = None):
|
| 417 |
+
"""اضافه کردن پیام به context گروه با اطلاعات ریپلای"""
|
| 418 |
+
chat_id_str = str(chat_id)
|
| 419 |
+
|
| 420 |
+
if chat_id_str not in DATA['groups']:
|
| 421 |
+
return
|
| 422 |
+
|
| 423 |
+
if 'context' not in DATA['groups'][chat_id_str]:
|
| 424 |
+
DATA['groups'][chat_id_str]['context'] = []
|
| 425 |
+
|
| 426 |
+
# اضافه کردن نام کاربر به محتوا اگر مشخص باشد
|
| 427 |
+
if user_name and role == 'user':
|
| 428 |
+
content_with_name = f"{user_name}: {content}"
|
| 429 |
+
else:
|
| 430 |
+
content_with_name = content
|
| 431 |
+
|
| 432 |
+
# اضافه کردن پیام جدید با اطلاعات ریپلای
|
| 433 |
+
message = {
|
| 434 |
+
'role': role,
|
| 435 |
+
'content': content_with_name if role == 'user' else content,
|
| 436 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 437 |
+
'user_name': user_name if role == 'user' else None,
|
| 438 |
+
'has_reply': False
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
|
| 442 |
+
message['has_reply'] = True
|
| 443 |
+
message['reply_to_user_id'] = reply_info.get('replied_user_id')
|
| 444 |
+
message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
|
| 445 |
+
message['reply_to_content'] = reply_info['replied_text'] # ذخیره قسمتی از متن
|
| 446 |
+
message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
|
| 447 |
+
message['reply_timestamp'] = reply_info.get('timestamp', time.time())
|
| 448 |
+
|
| 449 |
+
DATA['groups'][chat_id_str]['context'].append(message)
|
| 450 |
+
|
| 451 |
+
# محدود کردن context به 16384 توکن
|
| 452 |
+
trim_group_context(chat_id, max_tokens=16384)
|
| 453 |
+
|
| 454 |
+
save_data()
|
| 455 |
+
|
| 456 |
+
def optimize_group_context(chat_id: int):
|
| 457 |
+
"""بهینهسازی context گروه برای حفظ مهمترین پیامها"""
|
| 458 |
+
chat_id_str = str(chat_id)
|
| 459 |
+
|
| 460 |
+
if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
|
| 461 |
+
return
|
| 462 |
+
|
| 463 |
+
context = DATA['groups'][chat_id_str]['context']
|
| 464 |
+
if len(context) <= 10:
|
| 465 |
+
return
|
| 466 |
+
|
| 467 |
+
# محاسبه اهمیت هر پیام بر اساس عوامل مختلف
|
| 468 |
+
scored_messages = []
|
| 469 |
+
for i, msg in enumerate(context):
|
| 470 |
+
score = 0
|
| 471 |
+
|
| 472 |
+
# امتیاز بر اساس طول
|
| 473 |
+
content_length = len(msg['content'])
|
| 474 |
+
score += min(content_length / 100, 10)
|
| 475 |
+
|
| 476 |
+
# امتیاز بر اساس تازگی
|
| 477 |
+
recency = len(context) - i
|
| 478 |
+
score += min(recency / 10, 20)
|
| 479 |
+
|
| 480 |
+
# امتیاز بیشتر برای پاسخهای هوش مصنوعی
|
| 481 |
+
if msg['role'] == 'assistant':
|
| 482 |
+
score += 15
|
| 483 |
+
|
| 484 |
+
# امتیاز بیشتر برای پیامهای دارای ریپلای (مهمتر هستند)
|
| 485 |
+
if msg.get('has_reply', False):
|
| 486 |
+
score += 10
|
| 487 |
+
|
| 488 |
+
# امتیاز منفی برای پیامهای کوتاه و کممحتوا
|
| 489 |
+
if content_length < 20:
|
| 490 |
+
score -= 5
|
| 491 |
+
|
| 492 |
+
scored_messages.append((score, msg))
|
| 493 |
+
|
| 494 |
+
# مرتبسازی بر اساس امتیاز
|
| 495 |
+
scored_messages.sort(key=lambda x: x[0], reverse=True)
|
| 496 |
+
|
| 497 |
+
# حفظ 70% از پیامهای با بالاترین امتیاز
|
| 498 |
+
keep_count = int(len(scored_messages) * 0.7)
|
| 499 |
+
kept_messages = [msg for _, msg in scored_messages[:keep_count]]
|
| 500 |
+
|
| 501 |
+
# مرتبسازی مجدد بر اساس زمان
|
| 502 |
+
kept_messages.sort(key=lambda x: x.get('timestamp', ''))
|
| 503 |
+
|
| 504 |
+
DATA['groups'][chat_id_str]['context'] = kept_messages
|
| 505 |
+
save_data()
|
| 506 |
+
|
| 507 |
+
logger.info(f"Optimized group {chat_id} context: {len(context)} -> {len(kept_messages)} messages")
|
| 508 |
+
|
| 509 |
+
def trim_group_context(chat_id: int, max_tokens: int = 16384):
|
| 510 |
+
"""کوتاه کردن context گروه به تعداد توکن مشخص"""
|
| 511 |
+
chat_id_str = str(chat_id)
|
| 512 |
+
|
| 513 |
+
if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
|
| 514 |
+
return
|
| 515 |
+
|
| 516 |
+
context = DATA['groups'][chat_id_str]['context']
|
| 517 |
+
|
| 518 |
+
if not context:
|
| 519 |
+
return
|
| 520 |
+
|
| 521 |
+
# محاسبه توکنهای کل
|
| 522 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 523 |
+
|
| 524 |
+
# اگر تعداد توکنها بیش از حد مجاز است، ابتدا بهینهسازی کن
|
| 525 |
+
if total_tokens > max_tokens * 1.5:
|
| 526 |
+
optimize_group_context(chat_id)
|
| 527 |
+
context = DATA['groups'][chat_id_str]['context']
|
| 528 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 529 |
+
|
| 530 |
+
# حذف قدیمیترین پیامها
|
| 531 |
+
while total_tokens > max_tokens and len(context) > 1:
|
| 532 |
+
removed_message = context.pop(0)
|
| 533 |
+
total_tokens -= count_tokens(removed_message['content'])
|
| 534 |
+
|
| 535 |
+
# اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن
|
| 536 |
+
if total_tokens > max_tokens and context:
|
| 537 |
+
last_message = context[-1]
|
| 538 |
+
content = last_message['content']
|
| 539 |
+
|
| 540 |
+
tokens = count_tokens(content)
|
| 541 |
+
if tokens > max_tokens:
|
| 542 |
+
context.pop()
|
| 543 |
+
else:
|
| 544 |
+
while tokens > (max_tokens - (total_tokens - tokens)) and content:
|
| 545 |
+
words = content.split()
|
| 546 |
+
if len(words) > 1:
|
| 547 |
+
content = ' '.join(words[:-1])
|
| 548 |
+
else:
|
| 549 |
+
content = content[:-1] if len(content) > 1 else ''
|
| 550 |
+
tokens = count_tokens(content)
|
| 551 |
+
|
| 552 |
+
if content:
|
| 553 |
+
context[-1]['content'] = content
|
| 554 |
+
else:
|
| 555 |
+
context.pop()
|
| 556 |
+
|
| 557 |
+
save_data()
|
| 558 |
+
|
| 559 |
+
def get_group_context(chat_id: int) -> list:
|
| 560 |
+
"""دریافت context گروه"""
|
| 561 |
+
chat_id_str = str(chat_id)
|
| 562 |
+
|
| 563 |
+
if chat_id_str not in DATA['groups']:
|
| 564 |
+
return []
|
| 565 |
+
|
| 566 |
+
return DATA['groups'][chat_id_str].get('context', [])
|
| 567 |
+
|
| 568 |
+
def get_context_for_api_group(chat_id: int) -> list:
|
| 569 |
+
"""فرمت context گروه برای ارسال به API"""
|
| 570 |
+
context = get_group_context(chat_id)
|
| 571 |
+
|
| 572 |
+
api_context = []
|
| 573 |
+
for msg in context:
|
| 574 |
+
api_context.append({
|
| 575 |
+
'role': msg['role'],
|
| 576 |
+
'content': msg['content']
|
| 577 |
+
})
|
| 578 |
+
|
| 579 |
+
return api_context
|
| 580 |
+
|
| 581 |
+
def clear_group_context(chat_id: int):
|
| 582 |
+
"""پاک کردن context گروه"""
|
| 583 |
+
chat_id_str = str(chat_id)
|
| 584 |
+
|
| 585 |
+
if chat_id_str in DATA['groups']:
|
| 586 |
+
if 'context' in DATA['groups'][chat_id_str]:
|
| 587 |
+
DATA['groups'][chat_id_str]['context'] = []
|
| 588 |
+
save_data()
|
| 589 |
+
logger.info(f"Context cleared for group {chat_id}")
|
| 590 |
+
|
| 591 |
+
def get_group_context_summary(chat_id: int) -> str:
|
| 592 |
+
"""خلاصهای از context گروه"""
|
| 593 |
+
context = get_group_context(chat_id)
|
| 594 |
+
if not context:
|
| 595 |
+
return "بدون تاریخچه"
|
| 596 |
+
|
| 597 |
+
total_messages = len(context)
|
| 598 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 599 |
+
|
| 600 |
+
# تعداد ریپلایها
|
| 601 |
+
reply_count = sum(1 for msg in context if msg.get('has_reply', False))
|
| 602 |
+
|
| 603 |
+
last_message = context[-1] if context else {}
|
| 604 |
+
last_content = last_message.get('content', '')[:50]
|
| 605 |
+
if len(last_message.get('content', '')) > 50:
|
| 606 |
+
last_content += "..."
|
| 607 |
+
|
| 608 |
+
return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('user_name', last_message.get('role', ''))}: {last_content}"
|
| 609 |
+
|
| 610 |
+
# --- توابع ترکیبی (User + Group) ---
|
| 611 |
+
def add_to_hybrid_context(user_id: int, chat_id: int, role: str, content: str, user_name: str = None):
|
| 612 |
+
"""
|
| 613 |
+
اضافه کردن پیام به context ترکیبی
|
| 614 |
+
هم در context کاربر و هم در context گروه ذخیره میشود
|
| 615 |
+
"""
|
| 616 |
+
# ذخیره در context کاربر
|
| 617 |
+
add_to_user_context(user_id, role, content)
|
| 618 |
+
|
| 619 |
+
# ذخیره در context گروه
|
| 620 |
+
add_to_group_context(chat_id, role, content, user_name)
|
| 621 |
+
|
| 622 |
+
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):
|
| 623 |
+
"""
|
| 624 |
+
اضافه کردن پیام به context ترکیبی با اطلاعات ریپلای
|
| 625 |
+
هم در context کاربر و هم در context گروه ذخیره میشود
|
| 626 |
+
"""
|
| 627 |
+
# ذخیره در context کاربر
|
| 628 |
+
add_to_user_context_with_reply(user_id, role, content, reply_info)
|
| 629 |
+
|
| 630 |
+
# ذخیره در context گروه
|
| 631 |
+
add_to_group_context_with_reply(chat_id, role, content, user_name, reply_info)
|
| 632 |
+
|
| 633 |
+
def get_hybrid_context_for_api(user_id: int, chat_id: int) -> list:
|
| 634 |
+
"""
|
| 635 |
+
دریافت context ترکیبی برای ارسال به API
|
| 636 |
+
اولویت با context گروه است، اما از context کاربر هم استفاده میکند
|
| 637 |
+
"""
|
| 638 |
+
group_context = get_context_for_api_group(chat_id)
|
| 639 |
+
user_context = get_context_for_api(user_id)
|
| 640 |
+
|
| 641 |
+
# ترکیب contextها
|
| 642 |
+
combined_context = []
|
| 643 |
+
|
| 644 |
+
# ابتدا context گروه
|
| 645 |
+
combined_context.extend(group_context)
|
| 646 |
+
|
| 647 |
+
# سپس context کاربر - فقط پیامهای اخیر کاربر
|
| 648 |
+
recent_user_messages = [msg for msg in user_context[-3:] if msg['role'] == 'user']
|
| 649 |
+
combined_context.extend(recent_user_messages)
|
| 650 |
+
|
| 651 |
+
return combined_context
|
| 652 |
+
|
| 653 |
+
# --- توابع مدیریت حالت context ---
|
| 654 |
+
def get_context_mode() -> str:
|
| 655 |
+
"""دریافت حالت فعلی context"""
|
| 656 |
+
return DATA.get('context_mode', 'separate')
|
| 657 |
+
|
| 658 |
+
def set_context_mode(mode: str):
|
| 659 |
+
"""تنظیم حالت context"""
|
| 660 |
+
valid_modes = ['separate', 'group_shared', 'hybrid']
|
| 661 |
+
if mode in valid_modes:
|
| 662 |
+
DATA['context_mode'] = mode
|
| 663 |
+
save_data()
|
| 664 |
+
logger.info(f"Context mode changed to: {mode}")
|
| 665 |
+
return True
|
| 666 |
+
return False
|
| 667 |
+
|
| 668 |
+
# بارگذاری اولیه دادهها
|
| 669 |
+
load_data()
|
| 670 |
+
|
| 671 |
+
# برای جلوگیری از خطای time در توابع
|
| 672 |
+
import time
|
Version2_Context/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()
|
Version2_Context/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()
|
Version2_Context/2/main.py
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# شروع سرویس نگه داشتن ربات فعال
|
| 18 |
+
start_keep_alive()
|
| 19 |
+
|
| 20 |
+
# --- بهبود لاگینگ ---
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
filename=data_manager.LOG_FILE,
|
| 25 |
+
filemode='a'
|
| 26 |
+
)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
with open(data_manager.LOG_FILE, 'a') as f:
|
| 31 |
+
f.write("")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
|
| 34 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 35 |
+
|
| 36 |
+
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
|
| 37 |
+
http_client = httpx.AsyncClient(
|
| 38 |
+
http2=True,
|
| 39 |
+
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
|
| 40 |
+
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# کلاینت OpenAI (HuggingFace)
|
| 44 |
+
client = AsyncOpenAI(
|
| 45 |
+
base_url="https://router.huggingface.co/v1",
|
| 46 |
+
api_key=os.environ["HF_TOKEN"],
|
| 47 |
+
http_client=http_client
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
|
| 51 |
+
user_tasks = {}
|
| 52 |
+
group_tasks = {}
|
| 53 |
+
|
| 54 |
+
# --- توابع کمکی برای مدیریت ریپلای ---
|
| 55 |
+
def extract_reply_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> tuple:
|
| 56 |
+
"""استخراج اطلاعات از ریپلای"""
|
| 57 |
+
message = update.message
|
| 58 |
+
|
| 59 |
+
# اگر ریپلای وجود نداشت
|
| 60 |
+
if not message or not message.reply_to_message:
|
| 61 |
+
return None, None, None, None
|
| 62 |
+
|
| 63 |
+
replied_message = message.reply_to_message
|
| 64 |
+
|
| 65 |
+
# اطلاعات پیام ریپلای شده
|
| 66 |
+
replied_user_id = replied_message.from_user.id if replied_message.from_user else None
|
| 67 |
+
replied_user_name = replied_message.from_user.first_name if replied_message.from_user else "Unknown"
|
| 68 |
+
|
| 69 |
+
# استخراج متن پیام ریپلای شده
|
| 70 |
+
replied_text = ""
|
| 71 |
+
if replied_message.text:
|
| 72 |
+
replied_text = replied_message.text
|
| 73 |
+
elif replied_message.caption:
|
| 74 |
+
replied_text = replied_message.caption
|
| 75 |
+
|
| 76 |
+
# بررسی اینکه آیا ریپلای به ربات است
|
| 77 |
+
is_reply_to_bot = False
|
| 78 |
+
if replied_message.from_user:
|
| 79 |
+
# بررسی اینکه آیا پیام از خود ربات است
|
| 80 |
+
if replied_message.from_user.is_bot:
|
| 81 |
+
is_reply_to_bot = True
|
| 82 |
+
# یا آیا پیام حاوی منشن ربات است
|
| 83 |
+
elif context.bot and context.bot.username and replied_message.text:
|
| 84 |
+
if f"@{context.bot.username}" in replied_message.text:
|
| 85 |
+
is_reply_to_bot = True
|
| 86 |
+
|
| 87 |
+
return replied_user_id, replied_user_name, replied_text, is_reply_to_bot
|
| 88 |
+
|
| 89 |
+
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:
|
| 90 |
+
"""فرمتدهی پیام با در نظر گرفتن ریپلای"""
|
| 91 |
+
if not replied_text:
|
| 92 |
+
return user_message
|
| 93 |
+
|
| 94 |
+
# محدود کردن طول متن ریپلای شده
|
| 95 |
+
if len(replied_text) > 100:
|
| 96 |
+
replied_preview = replied_text[:97] + "..."
|
| 97 |
+
else:
|
| 98 |
+
replied_preview = replied_text
|
| 99 |
+
|
| 100 |
+
# حذف منشن ربات از متن ریپلای شده اگر وجود دارد
|
| 101 |
+
replied_preview = replied_preview.replace("@", "(at)") # جایگزین موقت برای جلوگیری از منشن
|
| 102 |
+
|
| 103 |
+
if is_reply_to_bot:
|
| 104 |
+
# ریپلای به ربات
|
| 105 |
+
if current_user_name:
|
| 106 |
+
return f"📎 {current_user_name} در پاسخ به ربات: «{replied_preview}»\n\n{user_message}"
|
| 107 |
+
else:
|
| 108 |
+
return f"📎 ریپلای به ربات: «{replied_preview}»\n\n{user_message}"
|
| 109 |
+
else:
|
| 110 |
+
# ریپلای به کاربر دیگر
|
| 111 |
+
if current_user_name:
|
| 112 |
+
return f"📎 {current_user_name} در پاسخ به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
|
| 113 |
+
else:
|
| 114 |
+
return f"📎 ریپلای به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
|
| 115 |
+
|
| 116 |
+
def create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot):
|
| 117 |
+
"""ایجاد دیکشنری اطلاعات ریپلای"""
|
| 118 |
+
if not replied_text:
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
return {
|
| 122 |
+
'replied_user_id': replied_user_id,
|
| 123 |
+
'replied_user_name': replied_user_name,
|
| 124 |
+
'replied_text': replied_text[:500], # محدود کردن طول
|
| 125 |
+
'is_reply_to_bot': is_reply_to_bot,
|
| 126 |
+
'timestamp': time.time()
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
# --- توا��ع کمکی برای مدیریت وظایف ---
|
| 130 |
+
def _cleanup_task(task: asyncio.Task, task_dict: dict, task_id: int):
|
| 131 |
+
if task_id in task_dict and task_dict[task_id] == task:
|
| 132 |
+
del task_dict[task_id]
|
| 133 |
+
logger.info(f"Cleaned up finished task for ID {task_id}.")
|
| 134 |
+
try:
|
| 135 |
+
exception = task.exception()
|
| 136 |
+
if exception:
|
| 137 |
+
logger.error(f"Background task for ID {task_id} failed: {exception}")
|
| 138 |
+
except asyncio.CancelledError:
|
| 139 |
+
logger.info(f"Task for ID {task_id} was cancelled.")
|
| 140 |
+
except asyncio.InvalidStateError:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None):
|
| 144 |
+
"""پردازش درخواست کاربر در چت خصوصی"""
|
| 145 |
+
chat_id = update.effective_chat.id
|
| 146 |
+
user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
|
| 147 |
+
user_id = update.effective_user.id
|
| 148 |
+
|
| 149 |
+
if not user_message:
|
| 150 |
+
logger.warning(f"No message content for user {user_id}")
|
| 151 |
+
return
|
| 152 |
+
|
| 153 |
+
# اگر reply_info از بیرون داده نشده، استخراج کن
|
| 154 |
+
if reply_info is None:
|
| 155 |
+
replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
|
| 156 |
+
reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
|
| 157 |
+
|
| 158 |
+
# اگر ریپلای وجود داشت، متن را فرمت کن
|
| 159 |
+
if reply_info and reply_info.get('replied_text'):
|
| 160 |
+
formatted_message = format_reply_message(
|
| 161 |
+
user_message,
|
| 162 |
+
reply_info.get('replied_user_name', 'Unknown'),
|
| 163 |
+
reply_info.get('replied_text'),
|
| 164 |
+
reply_info.get('is_reply_to_bot', False)
|
| 165 |
+
)
|
| 166 |
+
else:
|
| 167 |
+
formatted_message = user_message
|
| 168 |
+
|
| 169 |
+
start_time = time.time()
|
| 170 |
+
|
| 171 |
+
try:
|
| 172 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 173 |
+
|
| 174 |
+
# دریافت context کاربر
|
| 175 |
+
user_context = data_manager.get_context_for_api(user_id)
|
| 176 |
+
|
| 177 |
+
# اضافه کردن پیام کاربر به context (با فرمت ریپلای اگر وجود داشت)
|
| 178 |
+
data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
|
| 179 |
+
|
| 180 |
+
# ایجاد لیست پیامها برای API
|
| 181 |
+
messages = user_context.copy()
|
| 182 |
+
messages.append({"role": "user", "content": formatted_message})
|
| 183 |
+
|
| 184 |
+
logger.info(f"User {user_id} sending {len(messages)} messages to AI")
|
| 185 |
+
if reply_info and reply_info.get('replied_text'):
|
| 186 |
+
logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
|
| 187 |
+
|
| 188 |
+
response = await client.chat.completions.create(
|
| 189 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 190 |
+
messages=messages,
|
| 191 |
+
temperature=0.7,
|
| 192 |
+
top_p=0.95,
|
| 193 |
+
stream=False,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
end_time = time.time()
|
| 197 |
+
response_time = end_time - start_time
|
| 198 |
+
data_manager.update_response_stats(response_time)
|
| 199 |
+
|
| 200 |
+
ai_response = response.choices[0].message.content
|
| 201 |
+
|
| 202 |
+
# اضافه کردن پاسخ هوش مصنوعی به context
|
| 203 |
+
data_manager.add_to_user_context(user_id, "assistant", ai_response)
|
| 204 |
+
|
| 205 |
+
await update.message.reply_text(ai_response)
|
| 206 |
+
data_manager.update_user_stats(user_id, update.effective_user)
|
| 207 |
+
|
| 208 |
+
except httpx.TimeoutException:
|
| 209 |
+
logger.warning(f"Request timed out for user {user_id}.")
|
| 210 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 211 |
+
except Exception as e:
|
| 212 |
+
logger.error(f"Error while processing message for user {user_id}: {e}")
|
| 213 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 214 |
+
|
| 215 |
+
async def _process_group_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None):
|
| 216 |
+
"""پردازش درخواست در گروه"""
|
| 217 |
+
chat_id = update.effective_chat.id
|
| 218 |
+
user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
|
| 219 |
+
user_id = update.effective_user.id
|
| 220 |
+
user_name = update.effective_user.first_name
|
| 221 |
+
|
| 222 |
+
if not user_message:
|
| 223 |
+
logger.warning(f"No message content for group {chat_id}, user {user_id}")
|
| 224 |
+
return
|
| 225 |
+
|
| 226 |
+
# اگر reply_info از بیرون داده نشده، استخراج کن
|
| 227 |
+
if reply_info is None:
|
| 228 |
+
replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
|
| 229 |
+
reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
|
| 230 |
+
|
| 231 |
+
# اگر ریپلای وج��د داشت، متن را فرمت کن
|
| 232 |
+
if reply_info and reply_info.get('replied_text'):
|
| 233 |
+
formatted_message = format_reply_message(
|
| 234 |
+
user_message,
|
| 235 |
+
reply_info.get('replied_user_name', 'Unknown'),
|
| 236 |
+
reply_info.get('replied_text'),
|
| 237 |
+
reply_info.get('is_reply_to_bot', False),
|
| 238 |
+
user_name
|
| 239 |
+
)
|
| 240 |
+
else:
|
| 241 |
+
formatted_message = user_message
|
| 242 |
+
|
| 243 |
+
start_time = time.time()
|
| 244 |
+
|
| 245 |
+
try:
|
| 246 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 247 |
+
|
| 248 |
+
# بررسی حالت context
|
| 249 |
+
context_mode = data_manager.get_context_mode()
|
| 250 |
+
|
| 251 |
+
if context_mode == 'group_shared':
|
| 252 |
+
# حالت مشترک گروه: فقط از context گروه استفاده میشود
|
| 253 |
+
messages = data_manager.get_context_for_api_group(chat_id)
|
| 254 |
+
data_manager.add_to_group_context_with_reply(chat_id, "user", formatted_message, user_name, reply_info)
|
| 255 |
+
|
| 256 |
+
elif context_mode == 'hybrid':
|
| 257 |
+
# حالت ترکیبی: از هر دو context استفاده میشود
|
| 258 |
+
messages = data_manager.get_hybrid_context_for_api(user_id, chat_id)
|
| 259 |
+
data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "user", formatted_message, user_name, reply_info)
|
| 260 |
+
|
| 261 |
+
else: # separate (پیشفرض)
|
| 262 |
+
# حالت جداگانه: هر کاربر context خودش را دارد
|
| 263 |
+
messages = data_manager.get_context_for_api(user_id)
|
| 264 |
+
data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
|
| 265 |
+
|
| 266 |
+
# اضافه کردن پیام جدید
|
| 267 |
+
if context_mode == 'group_shared':
|
| 268 |
+
messages.append({"role": "user", "content": f"{user_name}: {formatted_message}"})
|
| 269 |
+
else:
|
| 270 |
+
messages.append({"role": "user", "content": formatted_message})
|
| 271 |
+
|
| 272 |
+
logger.info(f"Group {chat_id} ({context_mode} mode) sending {len(messages)} messages to AI")
|
| 273 |
+
if reply_info and reply_info.get('replied_text'):
|
| 274 |
+
logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
|
| 275 |
+
|
| 276 |
+
response = await client.chat.completions.create(
|
| 277 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 278 |
+
messages=messages,
|
| 279 |
+
temperature=0.7,
|
| 280 |
+
top_p=0.95,
|
| 281 |
+
stream=False,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
end_time = time.time()
|
| 285 |
+
response_time = end_time - start_time
|
| 286 |
+
data_manager.update_response_stats(response_time)
|
| 287 |
+
|
| 288 |
+
ai_response = response.choices[0].message.content
|
| 289 |
+
|
| 290 |
+
# ذخیره پاسخ بر اساس حالت context
|
| 291 |
+
if context_mode == 'group_shared':
|
| 292 |
+
data_manager.add_to_group_context(chat_id, "assistant", ai_response)
|
| 293 |
+
elif context_mode == 'hybrid':
|
| 294 |
+
# برای پاسخهای هوش مصنوعی، reply_info را None میکنیم
|
| 295 |
+
data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "assistant", ai_response, None, None)
|
| 296 |
+
else:
|
| 297 |
+
data_manager.add_to_user_context(user_id, "assistant", ai_response)
|
| 298 |
+
|
| 299 |
+
# بهروزرسانی آمار گروه با user_id
|
| 300 |
+
data_manager.update_group_stats(chat_id, update.effective_chat, user_id)
|
| 301 |
+
|
| 302 |
+
await update.message.reply_text(ai_response)
|
| 303 |
+
|
| 304 |
+
except httpx.TimeoutException:
|
| 305 |
+
logger.warning(f"Request timed out for group {chat_id}.")
|
| 306 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 307 |
+
except Exception as e:
|
| 308 |
+
logger.error(f"Error while processing message for group {chat_id}: {e}")
|
| 309 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 310 |
+
|
| 311 |
+
# --- هندلرهای اصلی ربات ---
|
| 312 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 313 |
+
user = update.effective_user
|
| 314 |
+
user_id = user.id
|
| 315 |
+
chat = update.effective_chat
|
| 316 |
+
|
| 317 |
+
if chat.type in ['group', 'supergroup']:
|
| 318 |
+
# در گروه
|
| 319 |
+
data_manager.update_group_stats(chat.id, chat, user_id)
|
| 320 |
+
|
| 321 |
+
welcome_msg = data_manager.DATA.get('group_welcome_message',
|
| 322 |
+
"سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید\n3. یا روی پیامها ریپلای کنید")
|
| 323 |
+
|
| 324 |
+
context_mode = data_manager.get_context_mode()
|
| 325 |
+
mode_info = ""
|
| 326 |
+
if context_mode == 'group_shared':
|
| 327 |
+
mode_info = "\n\n📝 **نکته:** در این گروه از context مشترک استفاده میشود. همه کاربران تاریخچه مکالمه یکسانی دارند (تا 16384 توکن)."
|
| 328 |
+
elif context_mode == 'hybrid':
|
| 329 |
+
mode_info = "\n\n📝 **نکته:** در این گروه از context ترکیبی استفاده میشود."
|
| 330 |
+
|
| 331 |
+
await update.message.reply_html(
|
| 332 |
+
welcome_msg + mode_info,
|
| 333 |
+
disable_web_page_preview=True
|
| 334 |
+
)
|
| 335 |
+
else:
|
| 336 |
+
# در چت خصوصی
|
| 337 |
+
data_manager.update_user_stats(user_id, user)
|
| 338 |
+
|
| 339 |
+
welcome_msg = data_manager.DATA.get('welcome_message',
|
| 340 |
+
"سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.\n\n💡 **نکته:** میتوانید روی پیامهای من ریپلای کنید تا من ارتباط را بهتر بفهمم.")
|
| 341 |
+
|
| 342 |
+
await update.message.reply_html(
|
| 343 |
+
welcome_msg.format(user_mention=user.mention_html()),
|
| 344 |
+
disable_web_page_preview=True
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 348 |
+
"""پاک کردن تاریخچه چت"""
|
| 349 |
+
user_id = update.effective_user.id
|
| 350 |
+
chat = update.effective_chat
|
| 351 |
+
|
| 352 |
+
if chat.type in ['group', 'supergroup']:
|
| 353 |
+
# پاک کردن context گروه
|
| 354 |
+
data_manager.clear_group_context(chat.id)
|
| 355 |
+
|
| 356 |
+
context_mode = data_manager.get_context_mode()
|
| 357 |
+
if context_mode == 'group_shared':
|
| 358 |
+
await update.message.reply_text(
|
| 359 |
+
"🧹 تاریخچه مکالمه گروه پاک شد.\n"
|
| 360 |
+
"از این لحظه مکالمه جدیدی برای همه اعضای گروه شروع خواهد شد."
|
| 361 |
+
)
|
| 362 |
+
else:
|
| 363 |
+
await update.message.reply_text(
|
| 364 |
+
"🧹 تاریخچه مکالمه شخصی شما در این گروه پاک شد.\n"
|
| 365 |
+
"از این لحظه مکالمه جدیدی شروع خواهد شد."
|
| 366 |
+
)
|
| 367 |
+
else:
|
| 368 |
+
# پاک کردن context کاربر
|
| 369 |
+
data_manager.clear_user_context(user_id)
|
| 370 |
+
|
| 371 |
+
await update.message.reply_text(
|
| 372 |
+
"🧹 تاریخچه مکالمه شما پاک شد.\n"
|
| 373 |
+
"از این لحظه مکالمه جدیدی شروع خواهد شد."
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 377 |
+
"""نمایش اطلاعات context"""
|
| 378 |
+
user_id = update.effective_user.id
|
| 379 |
+
chat = update.effective_chat
|
| 380 |
+
|
| 381 |
+
if chat.type in ['group', 'supergroup']:
|
| 382 |
+
context_mode = data_manager.get_context_mode()
|
| 383 |
+
|
| 384 |
+
if context_mode == 'group_shared':
|
| 385 |
+
context_summary = data_manager.get_group_context_summary(chat.id)
|
| 386 |
+
await update.message.reply_text(
|
| 387 |
+
f"📊 **اطلاعات تاریخچه مکالمه گروه:**\n\n"
|
| 388 |
+
f"{context_summary}\n\n"
|
| 389 |
+
f"**حالت:** مشترک بین همه اعضای گروه\n"
|
| 390 |
+
f"**سقف توکن:** 16384 توکن\n"
|
| 391 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 392 |
+
)
|
| 393 |
+
elif context_mode == 'hybrid':
|
| 394 |
+
group_summary = data_manager.get_group_context_summary(chat.id)
|
| 395 |
+
user_summary = data_manager.get_context_summary(user_id)
|
| 396 |
+
await update.message.reply_text(
|
| 397 |
+
f"📊 **اطلاعات تاریخچه مکالمه (حالت ترکیبی):**\n\n"
|
| 398 |
+
f"**گروه:** {group_summary}\n"
|
| 399 |
+
f"**شخصی:** {user_summary}\n\n"
|
| 400 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 401 |
+
)
|
| 402 |
+
else:
|
| 403 |
+
context_summary = data_manager.get_context_summary(user_id)
|
| 404 |
+
await update.message.reply_text(
|
| 405 |
+
f"📊 **اطلاعات تاریخچه مکالمه شخصی شما در این گروه:**\n\n"
|
| 406 |
+
f"{context_summary}\n\n"
|
| 407 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 408 |
+
)
|
| 409 |
+
else:
|
| 410 |
+
context_summary = data_manager.get_context_summary(user_id)
|
| 411 |
+
|
| 412 |
+
await update.message.reply_text(
|
| 413 |
+
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
|
| 414 |
+
f"{context_summary}\n\n"
|
| 415 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 419 |
+
"""نمایش دستورات کمک"""
|
| 420 |
+
chat = update.effective_chat
|
| 421 |
+
|
| 422 |
+
if chat.type in ['group', 'supergroup']:
|
| 423 |
+
help_text = (
|
| 424 |
+
"🤖 **دستورات ربات در گروه:**\n\n"
|
| 425 |
+
"🟢 `/start` - شروع کار با ربات در گروه\n"
|
| 426 |
+
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
|
| 427 |
+
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
|
| 428 |
+
"🟢 `/help` - نمایش این پیام راهنما\n\n"
|
| 429 |
+
"📝 **نکته:** ربات به سه صورت کار میکند:\n"
|
| 430 |
+
"1. پاسخ به پیامهای مستقیم\n"
|
| 431 |
+
"2. پاسخ وقتی منشن میشوید\n"
|
| 432 |
+
"3. پاسخ به ریپلایها (روی پیامهای من یا دیگران)\n\n"
|
| 433 |
+
f"**حالت فعلی:** {data_manager.get_context_mode()}\n"
|
| 434 |
+
"• separate: هر کاربر تاریخچه جداگانه (8192 توکن)\n"
|
| 435 |
+
"• group_shared: تاریخچه مشترک برای همه (16384 توکن)\n"
|
| 436 |
+
"• hybrid: ترکیب هر دو\n\n"
|
| 437 |
+
"💡 **توجه:** در حالت group_shared، ربات میتواند تا 16384 توکن از تاریخچه مکالمه گروه را به خاطر بسپارد."
|
| 438 |
+
)
|
| 439 |
+
else:
|
| 440 |
+
help_text = (
|
| 441 |
+
"🤖 **دستورات ربات:**\n\n"
|
| 442 |
+
"🟢 `/start` - شروع کار با ربات\n"
|
| 443 |
+
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
|
| 444 |
+
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
|
| 445 |
+
"🟢 `/help` - نمایش این پیام راهنما\n\n"
|
| 446 |
+
"📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۲۰۴۸ توکن ذخیره میکند. "
|
| 447 |
+
"میتوانید روی پیامهای من ریپلای کنید تا من ارتباط را بهتر بفهمم.\n"
|
| 448 |
+
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
await update.message.reply_text(help_text, parse_mode='Markdown')
|
| 452 |
+
|
| 453 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 454 |
+
# بررسی وجود پیام
|
| 455 |
+
if not update.message:
|
| 456 |
+
return
|
| 457 |
+
|
| 458 |
+
user_id = update.effective_user.id
|
| 459 |
+
chat = update.effective_chat
|
| 460 |
+
|
| 461 |
+
# بررسی مسدود بودن کاربر
|
| 462 |
+
if data_manager.is_user_banned(user_id):
|
| 463 |
+
logger.info(f"Banned user {user_id} tried to send a message.")
|
| 464 |
+
return
|
| 465 |
+
|
| 466 |
+
# بررسی حالت نگهداری
|
| 467 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 468 |
+
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
|
| 469 |
+
return
|
| 470 |
+
|
| 471 |
+
# بررسی کلمات مسدود شده
|
| 472 |
+
message_text = update.message.text or update.message.caption or ""
|
| 473 |
+
if not message_text:
|
| 474 |
+
return
|
| 475 |
+
|
| 476 |
+
if data_manager.contains_blocked_words(message_text):
|
| 477 |
+
logger.info(f"User {user_id} sent a message with a blocked word.")
|
| 478 |
+
return
|
| 479 |
+
|
| 480 |
+
if chat.type in ['group', 'supergroup']:
|
| 481 |
+
# پردازش در گروه
|
| 482 |
+
if chat.id in group_tasks and not group_tasks[chat.id].done():
|
| 483 |
+
group_tasks[chat.id].cancel()
|
| 484 |
+
logger.info(f"Cancelled previous task for group {chat.id} to start a new one.")
|
| 485 |
+
|
| 486 |
+
task = asyncio.create_task(_process_group_request(update, context))
|
| 487 |
+
group_tasks[chat.id] = task
|
| 488 |
+
task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, chat.id))
|
| 489 |
+
else:
|
| 490 |
+
# پردازش در چت خصوصی
|
| 491 |
+
if user_id in user_tasks and not user_tasks[user_id].done():
|
| 492 |
+
user_tasks[user_id].cancel()
|
| 493 |
+
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
|
| 494 |
+
|
| 495 |
+
task = asyncio.create_task(_process_user_request(update, context))
|
| 496 |
+
user_tasks[user_id] = task
|
| 497 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
|
| 498 |
+
|
| 499 |
+
async def mention_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 500 |
+
"""هندلر برای زمانی که ربات در گروه منشن میشود"""
|
| 501 |
+
if not update.message:
|
| 502 |
+
return
|
| 503 |
+
|
| 504 |
+
if update.effective_chat.type in ['group', 'supergroup']:
|
| 505 |
+
# استخراج اطلاعات ریپلای
|
| 506 |
+
replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
|
| 507 |
+
reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
|
| 508 |
+
|
| 509 |
+
# حذف منشن از متن
|
| 510 |
+
message_text = update.message.text or ""
|
| 511 |
+
bot_username = context.bot.username
|
| 512 |
+
|
| 513 |
+
# حذف منشن ربات از متن
|
| 514 |
+
if bot_username and f"@{bot_username}" in message_text:
|
| 515 |
+
message_text = message_text.replace(f"@{bot_username}", "").strip()
|
| 516 |
+
|
| 517 |
+
if message_text:
|
| 518 |
+
# پردازش پیام مانند حالت عادی اما با متن فرمتشده
|
| 519 |
+
user_name = update.effective_user.first_name
|
| 520 |
+
|
| 521 |
+
# اگر ریپلای وجود داشت، متن را فرمت کن
|
| 522 |
+
if reply_info and reply_info.get('replied_text'):
|
| 523 |
+
formatted_message = format_reply_message(
|
| 524 |
+
message_text,
|
| 525 |
+
reply_info.get('replied_user_name', 'Unknown'),
|
| 526 |
+
reply_info.get('replied_text'),
|
| 527 |
+
reply_info.get('is_reply_to_bot', False),
|
| 528 |
+
user_name
|
| 529 |
+
)
|
| 530 |
+
else:
|
| 531 |
+
formatted_message = message_text
|
| 532 |
+
|
| 533 |
+
# پردازش درخواست
|
| 534 |
+
if update.effective_chat.id in group_tasks and not group_tasks[update.effective_chat.id].done():
|
| 535 |
+
group_tasks[update.effective_chat.id].cancel()
|
| 536 |
+
logger.info(f"Cancelled previous task for group {update.effective_chat.id} to start a new one.")
|
| 537 |
+
|
| 538 |
+
task = asyncio.create_task(_process_group_request(update, context, formatted_message, reply_info))
|
| 539 |
+
group_tasks[update.effective_chat.id] = task
|
| 540 |
+
task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, update.effective_chat.id))
|
| 541 |
+
else:
|
| 542 |
+
await update.message.reply_text("بله؟ چگونه میتوانم کمک کنم؟")
|
| 543 |
+
|
| 544 |
+
async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 545 |
+
"""هندلر مخصوص ریپلایها"""
|
| 546 |
+
# بررسی وجود پیام
|
| 547 |
+
if not update.message:
|
| 548 |
+
return
|
| 549 |
+
|
| 550 |
+
# فقط ریپلایهایی که متن دارند
|
| 551 |
+
message_text = update.message.text or update.message.caption or ""
|
| 552 |
+
if not message_text:
|
| 553 |
+
return
|
| 554 |
+
|
| 555 |
+
user_id = update.effective_user.id
|
| 556 |
+
chat = update.effective_chat
|
| 557 |
+
|
| 558 |
+
# بررسی مسدود بودن کاربر
|
| 559 |
+
if data_manager.is_user_banned(user_id):
|
| 560 |
+
return
|
| 561 |
+
|
| 562 |
+
# بررسی حالت نگهداری
|
| 563 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 564 |
+
return
|
| 565 |
+
|
| 566 |
+
# بررسی کلمات مسدود شده
|
| 567 |
+
if data_manager.contains_blocked_words(message_text):
|
| 568 |
+
return
|
| 569 |
+
|
| 570 |
+
if chat.type in ['group', 'supergroup']:
|
| 571 |
+
# پردازش در گروه
|
| 572 |
+
if chat.id in group_tasks and not group_tasks[chat.id].done():
|
| 573 |
+
group_tasks[chat.id].cancel()
|
| 574 |
+
logger.info(f"Cancelled previous task for group {chat.id} to start a new one.")
|
| 575 |
+
|
| 576 |
+
task = asyncio.create_task(_process_group_request(update, context))
|
| 577 |
+
group_tasks[chat.id] = task
|
| 578 |
+
task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, chat.id))
|
| 579 |
+
else:
|
| 580 |
+
# پردازش در چت خصوصی
|
| 581 |
+
if user_id in user_tasks and not user_tasks[user_id].done():
|
| 582 |
+
user_tasks[user_id].cancel()
|
| 583 |
+
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
|
| 584 |
+
|
| 585 |
+
task = asyncio.create_task(_process_user_request(update, context))
|
| 586 |
+
user_tasks[user_id] = task
|
| 587 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))
|
| 588 |
+
|
| 589 |
+
def main() -> None:
|
| 590 |
+
token = os.environ.get("BOT_TOKEN")
|
| 591 |
+
if not token:
|
| 592 |
+
logger.error("BOT_TOKEN not set in environment variables!")
|
| 593 |
+
return
|
| 594 |
+
|
| 595 |
+
application = (
|
| 596 |
+
Application.builder()
|
| 597 |
+
.token(token)
|
| 598 |
+
.concurrent_updates(True)
|
| 599 |
+
.build()
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
# هندلرهای کاربران
|
| 603 |
+
application.add_handler(CommandHandler("start", start))
|
| 604 |
+
application.add_handler(CommandHandler("clear", clear_chat))
|
| 605 |
+
application.add_handler(CommandHandler("context", context_info))
|
| 606 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 607 |
+
|
| 608 |
+
# هندلر برای ریپلایها
|
| 609 |
+
application.add_handler(MessageHandler(
|
| 610 |
+
filters.TEXT & filters.REPLY,
|
| 611 |
+
reply_handler
|
| 612 |
+
))
|
| 613 |
+
|
| 614 |
+
# هندلر برای منشن در گروه
|
| 615 |
+
application.add_handler(MessageHandler(
|
| 616 |
+
filters.TEXT & filters.Entity("mention") & filters.ChatType.GROUPS,
|
| 617 |
+
mention_handler
|
| 618 |
+
))
|
| 619 |
+
|
| 620 |
+
# هندلر برای پیامهای متنی معمولی (بدون ریپلای و بدون منشن)
|
| 621 |
+
application.add_handler(MessageHandler(
|
| 622 |
+
filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE & ~filters.REPLY,
|
| 623 |
+
handle_message
|
| 624 |
+
))
|
| 625 |
+
|
| 626 |
+
# هندلر برای پیامهای متنی در گروه (بدون منشن و بدون ریپلای)
|
| 627 |
+
application.add_handler(MessageHandler(
|
| 628 |
+
filters.TEXT & ~filters.COMMAND & filters.ChatType.GROUPS & ~filters.Entity("mention") & ~filters.REPLY,
|
| 629 |
+
handle_message
|
| 630 |
+
))
|
| 631 |
+
|
| 632 |
+
# راهاندازی و ثبت هندلرهای پنل ادمین
|
| 633 |
+
admin_panel.setup_admin_handlers(application)
|
| 634 |
+
|
| 635 |
+
# تنظیم هندلر خطا
|
| 636 |
+
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 637 |
+
logger.error(f"Exception while handling an update: {context.error}")
|
| 638 |
+
try:
|
| 639 |
+
if update and update.message:
|
| 640 |
+
await update.message.reply_text("❌ خطایی در پردازش درخواست شما رخ داد.")
|
| 641 |
+
except:
|
| 642 |
+
pass
|
| 643 |
+
|
| 644 |
+
application.add_error_handler(error_handler)
|
| 645 |
+
|
| 646 |
+
port = int(os.environ.get("PORT", 8443))
|
| 647 |
+
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
|
| 648 |
+
|
| 649 |
+
if webhook_url:
|
| 650 |
+
application.run_webhook(
|
| 651 |
+
listen="0.0.0.0",
|
| 652 |
+
port=port,
|
| 653 |
+
webhook_url=webhook_url,
|
| 654 |
+
url_path="webhook"
|
| 655 |
+
)
|
| 656 |
+
else:
|
| 657 |
+
application.run_polling()
|
| 658 |
+
|
| 659 |
+
if __name__ == "__main__":
|
| 660 |
+
main()
|
Version2_Context/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 وارد کنید
|
Version2_Context/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
|
Version2_Context/admin_panel.py
ADDED
|
@@ -0,0 +1,961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# --- کتابخانههای جدید برای ویژگیهای اضافه شده ---
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use('Agg') # تنظیم برای استفاده در محیط بدون رابط کاربری گرافیکی
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import tempfile
|
| 20 |
+
import psutil
|
| 21 |
+
import platform
|
| 22 |
+
|
| 23 |
+
# --- تنظیمات ---
|
| 24 |
+
ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
|
| 25 |
+
|
| 26 |
+
# وارد کردن مدیر دادهها
|
| 27 |
+
import data_manager
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# --- دکوراتور برای دسترسی ادمین ---
|
| 32 |
+
|
| 33 |
+
def admin_only(func):
|
| 34 |
+
"""این دکوراتور تضمین میکند که فقط ادمینها بتوانند دستور را اجرا کنند."""
|
| 35 |
+
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
| 36 |
+
if update.effective_user.id not in ADMIN_IDS:
|
| 37 |
+
await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
|
| 38 |
+
return
|
| 39 |
+
return await func(update, context, *args, **kwargs)
|
| 40 |
+
return wrapped
|
| 41 |
+
|
| 42 |
+
# --- هندلرهای دستورات ادمین ---
|
| 43 |
+
|
| 44 |
+
@admin_only
|
| 45 |
+
async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 46 |
+
"""نمایش تمام دستورات موجود ادمین."""
|
| 47 |
+
commands_text = (
|
| 48 |
+
"📋 **دستورات ادمین ربات:**\n\n"
|
| 49 |
+
"📊 `/stats` - نمایش آمار ربات\n"
|
| 50 |
+
"📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
|
| 51 |
+
"🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
|
| 52 |
+
"📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامهریزی شده\n"
|
| 53 |
+
"📋 `/list_scheduled` - نمایش لیست ارسالهای برنامهریزی شده\n"
|
| 54 |
+
"🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامهریزی شده\n"
|
| 55 |
+
"🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
|
| 56 |
+
"✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
|
| 57 |
+
"💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
|
| 58 |
+
"ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
|
| 59 |
+
"📝 `/logs` - نمایش آخرین لاگها\n"
|
| 60 |
+
"📂 `/logs_file` - دانلود فایل کامل لاگها\n"
|
| 61 |
+
"👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
|
| 62 |
+
"🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
|
| 63 |
+
"💾 `/backup` - ایجاد نسخه پشتیبان از دادهها\n"
|
| 64 |
+
"📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
|
| 65 |
+
"🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
|
| 66 |
+
"👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
|
| 67 |
+
"👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
|
| 68 |
+
"📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
|
| 69 |
+
"⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
|
| 70 |
+
"🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
|
| 71 |
+
"✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
|
| 72 |
+
"📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
|
| 73 |
+
"💻 `/system_info` - نمایش اطلاعات سیستم\n"
|
| 74 |
+
"🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
|
| 75 |
+
"🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
|
| 76 |
+
"📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
|
| 77 |
+
"📋 `/commands` - نمایش این لیست دستورات"
|
| 78 |
+
)
|
| 79 |
+
await update.message.reply_text(commands_text, parse_mode='Markdown')
|
| 80 |
+
|
| 81 |
+
@admin_only
|
| 82 |
+
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 83 |
+
"""آمار ربات را نمایش میدهد."""
|
| 84 |
+
total_users = len(data_manager.DATA['users'])
|
| 85 |
+
total_messages = data_manager.DATA['stats']['total_messages']
|
| 86 |
+
banned_count = len(data_manager.DATA['banned_users'])
|
| 87 |
+
|
| 88 |
+
now = datetime.now()
|
| 89 |
+
active_24h = sum(1 for user in data_manager.DATA['users'].values()
|
| 90 |
+
if 'last_seen' in user and
|
| 91 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
|
| 92 |
+
|
| 93 |
+
active_7d = sum(1 for user in data_manager.DATA['users'].values()
|
| 94 |
+
if 'last_seen' in user and
|
| 95 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
|
| 96 |
+
|
| 97 |
+
active_users = sorted(
|
| 98 |
+
data_manager.DATA['users'].items(),
|
| 99 |
+
key=lambda item: item[1].get('last_seen', ''),
|
| 100 |
+
reverse=True
|
| 101 |
+
)[:5]
|
| 102 |
+
|
| 103 |
+
active_users_text = "\n".join(
|
| 104 |
+
[f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
|
| 105 |
+
for user_id, info in active_users]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# آمار context
|
| 109 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values()
|
| 110 |
+
if user.get('context') and len(user['context']) > 0)
|
| 111 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 112 |
+
|
| 113 |
+
text = (
|
| 114 |
+
f"📊 **آمار ربات**\n\n"
|
| 115 |
+
f"👥 **تعداد کل کاربران:** `{total_users}`\n"
|
| 116 |
+
f"📝 **تعداد کل پیامها:** `{total_messages}`\n"
|
| 117 |
+
f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
|
| 118 |
+
f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
|
| 119 |
+
f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
|
| 120 |
+
f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
|
| 121 |
+
f"💬 **کل پیامهای context:** `{total_context_messages}`\n\n"
|
| 122 |
+
f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
|
| 123 |
+
)
|
| 124 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 125 |
+
|
| 126 |
+
@admin_only
|
| 127 |
+
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 128 |
+
"""یک پیام را به تمام کاربران ارسال میکند."""
|
| 129 |
+
if not context.args:
|
| 130 |
+
await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
message_text = " ".join(context.args)
|
| 134 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 135 |
+
total_sent = 0
|
| 136 |
+
total_failed = 0
|
| 137 |
+
|
| 138 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
|
| 139 |
+
|
| 140 |
+
for user_id_str in user_ids:
|
| 141 |
+
try:
|
| 142 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 143 |
+
total_sent += 1
|
| 144 |
+
await asyncio.sleep(0.05)
|
| 145 |
+
except TelegramError as e:
|
| 146 |
+
logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
|
| 147 |
+
total_failed += 1
|
| 148 |
+
|
| 149 |
+
result_text = (
|
| 150 |
+
f"✅ **ارسال همگانی تمام شد**\n\n"
|
| 151 |
+
f"✅ موفق: `{total_sent}`\n"
|
| 152 |
+
f"❌ ناموفق: `{total_failed}`"
|
| 153 |
+
)
|
| 154 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 155 |
+
|
| 156 |
+
@admin_only
|
| 157 |
+
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 158 |
+
"""ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
|
| 159 |
+
if len(context.args) < 3:
|
| 160 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
|
| 161 |
+
"معیارهای موجود: `active_days`, `message_count`, `banned`")
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
criteria = context.args[0].lower()
|
| 165 |
+
value = context.args[1]
|
| 166 |
+
message_text = " ".join(context.args[2:])
|
| 167 |
+
|
| 168 |
+
target_users = []
|
| 169 |
+
|
| 170 |
+
if criteria == "active_days":
|
| 171 |
+
try:
|
| 172 |
+
days = int(value)
|
| 173 |
+
target_users = data_manager.get_active_users(days)
|
| 174 |
+
except ValueError:
|
| 175 |
+
await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
elif criteria == "message_count":
|
| 179 |
+
try:
|
| 180 |
+
min_count = int(value)
|
| 181 |
+
target_users = data_manager.get_users_by_message_count(min_count)
|
| 182 |
+
except ValueError:
|
| 183 |
+
await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
|
| 184 |
+
return
|
| 185 |
+
|
| 186 |
+
elif criteria == "banned":
|
| 187 |
+
if value.lower() == "true":
|
| 188 |
+
target_users = list(data_manager.DATA['banned_users'])
|
| 189 |
+
elif value.lower() == "false":
|
| 190 |
+
for user_id in data_manager.DATA['users']:
|
| 191 |
+
if int(user_id) not in data_manager.DATA['banned_users']:
|
| 192 |
+
target_users.append(int(user_id))
|
| 193 |
+
else:
|
| 194 |
+
await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
else:
|
| 198 |
+
await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
if not target_users:
|
| 202 |
+
await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کا��بر...")
|
| 206 |
+
|
| 207 |
+
total_sent, total_failed = 0, 0
|
| 208 |
+
for user_id in target_users:
|
| 209 |
+
try:
|
| 210 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 211 |
+
total_sent += 1
|
| 212 |
+
await asyncio.sleep(0.05)
|
| 213 |
+
except TelegramError as e:
|
| 214 |
+
logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
|
| 215 |
+
total_failed += 1
|
| 216 |
+
|
| 217 |
+
result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
|
| 218 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 219 |
+
|
| 220 |
+
@admin_only
|
| 221 |
+
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 222 |
+
"""تنظیم ارسال برنامهریزی شده پیام به همه کاربران."""
|
| 223 |
+
if len(context.args) < 3:
|
| 224 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
date_str, time_str = context.args[0], context.args[1]
|
| 229 |
+
message_text = " ".join(context.args[2:])
|
| 230 |
+
|
| 231 |
+
scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
|
| 232 |
+
|
| 233 |
+
if scheduled_time <= datetime.now():
|
| 234 |
+
await update.message.reply_text("⚠️ زمان برنامهریزی شده باید در آینده باشد.")
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
data_manager.DATA['scheduled_broadcasts'].append({
|
| 238 |
+
'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 239 |
+
'message': message_text,
|
| 240 |
+
'status': 'pending'
|
| 241 |
+
})
|
| 242 |
+
data_manager.save_data()
|
| 243 |
+
|
| 244 |
+
await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامهریزی شد.")
|
| 245 |
+
|
| 246 |
+
except ValueError:
|
| 247 |
+
await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
|
| 248 |
+
|
| 249 |
+
@admin_only
|
| 250 |
+
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 251 |
+
"""نمایش لیست ارسالهای برنامهریزی شده."""
|
| 252 |
+
if not data_manager.DATA['scheduled_broadcasts']:
|
| 253 |
+
await update.message.reply_text("هیچ ارسال برنامهریزی شدهای وجود ندارد.")
|
| 254 |
+
return
|
| 255 |
+
|
| 256 |
+
broadcasts_text = "📅 **لیست ارسالهای برنامهریزی شده:**\n\n"
|
| 257 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
|
| 258 |
+
status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
|
| 259 |
+
broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
|
| 260 |
+
|
| 261 |
+
await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
|
| 262 |
+
|
| 263 |
+
@admin_only
|
| 264 |
+
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 265 |
+
"""حذف یک ارسال برنامهریزی شده."""
|
| 266 |
+
if not context.args or not context.args[0].isdigit():
|
| 267 |
+
await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامهریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
index = int(context.args[0]) - 1
|
| 271 |
+
|
| 272 |
+
if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
|
| 273 |
+
await update.message.reply_text("⚠️ شماره ارسال برنامهریزی شده نامعتبر است.")
|
| 274 |
+
return
|
| 275 |
+
|
| 276 |
+
removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
|
| 277 |
+
data_manager.save_data()
|
| 278 |
+
|
| 279 |
+
await update.message.reply_text(f"✅ ارسال برنامهریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
|
| 280 |
+
|
| 281 |
+
@admin_only
|
| 282 |
+
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 283 |
+
"""یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع میدهد."""
|
| 284 |
+
if not context.args or not context.args[0].isdigit():
|
| 285 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
|
| 286 |
+
return
|
| 287 |
+
|
| 288 |
+
user_id_to_ban = int(context.args[0])
|
| 289 |
+
|
| 290 |
+
if user_id_to_ban in ADMIN_IDS:
|
| 291 |
+
await update.message.reply_text("🛡️ شما نمیتوانید یک ادمین را مسدود کنید!")
|
| 292 |
+
return
|
| 293 |
+
|
| 294 |
+
if data_manager.is_user_banned(user_id_to_ban):
|
| 295 |
+
await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
|
| 296 |
+
return
|
| 297 |
+
|
| 298 |
+
data_manager.ban_user(user_id_to_ban)
|
| 299 |
+
|
| 300 |
+
# ارسال پیام به کاربر مسدود شده
|
| 301 |
+
try:
|
| 302 |
+
await context.bot.send_message(
|
| 303 |
+
chat_id=user_id_to_ban,
|
| 304 |
+
text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمیتوانید از خدمات ربات استفاده کنید."
|
| 305 |
+
)
|
| 306 |
+
except TelegramError as e:
|
| 307 |
+
logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
|
| 308 |
+
|
| 309 |
+
await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
|
| 310 |
+
|
| 311 |
+
@admin_only
|
| 312 |
+
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 313 |
+
"""مسدودیت یک کاربر را برمیدارد و به او اطلاع میدهد."""
|
| 314 |
+
if not context.args or not context.args[0].isdigit():
|
| 315 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
user_id_to_unban = int(context.args[0])
|
| 319 |
+
|
| 320 |
+
if not data_manager.is_user_banned(user_id_to_unban):
|
| 321 |
+
await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شدهها وجود ندارد.")
|
| 322 |
+
return
|
| 323 |
+
|
| 324 |
+
data_manager.unban_user(user_id_to_unban)
|
| 325 |
+
|
| 326 |
+
# ارسال پیام به کاربر برای رفع مسدودیت
|
| 327 |
+
try:
|
| 328 |
+
await context.bot.send_message(
|
| 329 |
+
chat_id=user_id_to_unban,
|
| 330 |
+
text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. میتوانید دوباره از ربات استفاده کنید."
|
| 331 |
+
)
|
| 332 |
+
except TelegramError as e:
|
| 333 |
+
logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
|
| 334 |
+
|
| 335 |
+
await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
|
| 336 |
+
|
| 337 |
+
@admin_only
|
| 338 |
+
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 339 |
+
"""ارسال پیام مستقیم به یک کاربر خاص."""
|
| 340 |
+
if len(context.args) < 2:
|
| 341 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
user_id_str = context.args[0]
|
| 345 |
+
if not user_id_str.isdigit():
|
| 346 |
+
await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
|
| 347 |
+
return
|
| 348 |
+
|
| 349 |
+
message_text = " ".join(context.args[1:])
|
| 350 |
+
user_id = int(user_id_str)
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 354 |
+
await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
|
| 355 |
+
except TelegramError as e:
|
| 356 |
+
await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
|
| 357 |
+
|
| 358 |
+
@admin_only
|
| 359 |
+
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 360 |
+
"""اطلاعات یک کاربر خاص را نمایش میدهد."""
|
| 361 |
+
if not context.args or not context.args[0].isdigit():
|
| 362 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
|
| 363 |
+
return
|
| 364 |
+
|
| 365 |
+
user_id = int(context.args[0])
|
| 366 |
+
user_info = data_manager.DATA['users'].get(str(user_id))
|
| 367 |
+
|
| 368 |
+
if not user_info:
|
| 369 |
+
await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
|
| 370 |
+
return
|
| 371 |
+
|
| 372 |
+
is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
|
| 373 |
+
|
| 374 |
+
if 'first_seen' in user_info and 'last_seen' in user_info:
|
| 375 |
+
first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
|
| 376 |
+
last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 377 |
+
days_active = max(1, (last_date - first_date).days)
|
| 378 |
+
avg_messages = user_info.get('message_count', 0) / days_active
|
| 379 |
+
else:
|
| 380 |
+
avg_messages = user_info.get('message_count', 0)
|
| 381 |
+
|
| 382 |
+
# اطلاعات context
|
| 383 |
+
context_messages = len(user_info.get('context', []))
|
| 384 |
+
context_tokens = data_manager.get_context_token_count(user_id)
|
| 385 |
+
|
| 386 |
+
text = (
|
| 387 |
+
f"ℹ️ **اطلاعات کاربر**\n\n"
|
| 388 |
+
f"🆔 **آیدی:** `{user_id}`\n"
|
| 389 |
+
f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
|
| 390 |
+
f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
|
| 391 |
+
f"📊 **تعداد پیامها:** `{user_info.get('message_count', 0)}`\n"
|
| 392 |
+
f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
|
| 393 |
+
f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
|
| 394 |
+
f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
|
| 395 |
+
f"💭 **پیامهای context:** `{context_messages}`\n"
|
| 396 |
+
f"🔢 **توکنهای context:** `{context_tokens}`\n"
|
| 397 |
+
f"🚫 **وضعیت مسدودیت:** {is_banned}"
|
| 398 |
+
)
|
| 399 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 400 |
+
|
| 401 |
+
@admin_only
|
| 402 |
+
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 403 |
+
"""آخرین خطوط لاگ ربات را ارسال میکند."""
|
| 404 |
+
try:
|
| 405 |
+
with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
|
| 406 |
+
lines = f.readlines()
|
| 407 |
+
last_lines = lines[-30:]
|
| 408 |
+
log_text = "".join(last_lines)
|
| 409 |
+
if not log_text:
|
| 410 |
+
await update.message.reply_text("فایل لاگ خالی است.")
|
| 411 |
+
return
|
| 412 |
+
|
| 413 |
+
if len(log_text) > 4096:
|
| 414 |
+
for i in range(0, len(log_text), 4096):
|
| 415 |
+
await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
|
| 416 |
+
else:
|
| 417 |
+
await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
|
| 418 |
+
|
| 419 |
+
except FileNotFoundError:
|
| 420 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 421 |
+
except Exception as e:
|
| 422 |
+
await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
|
| 423 |
+
|
| 424 |
+
@admin_only
|
| 425 |
+
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 426 |
+
"""فایل کامل لاگ ربات را ارسال میکند."""
|
| 427 |
+
try:
|
| 428 |
+
await update.message.reply_document(
|
| 429 |
+
document=open(data_manager.LOG_FILE, 'rb'),
|
| 430 |
+
caption="📂 فایل کامل لاگهای ربات"
|
| 431 |
+
)
|
| 432 |
+
except FileNotFoundError:
|
| 433 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 434 |
+
except Exception as e:
|
| 435 |
+
await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
|
| 436 |
+
|
| 437 |
+
@admin_only
|
| 438 |
+
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 439 |
+
"""نمایش لیست کامل کاربران با صفحهبندی."""
|
| 440 |
+
users = data_manager.DATA['users']
|
| 441 |
+
|
| 442 |
+
page = 1
|
| 443 |
+
if context.args and context.args[0].isdigit():
|
| 444 |
+
page = int(context.args[0])
|
| 445 |
+
if page < 1: page = 1
|
| 446 |
+
|
| 447 |
+
users_per_page = 20
|
| 448 |
+
total_users = len(users)
|
| 449 |
+
total_pages = (total_users + users_per_page - 1) // users_per_page
|
| 450 |
+
|
| 451 |
+
if page > total_pages: page = total_pages
|
| 452 |
+
|
| 453 |
+
start_idx = (page - 1) * users_per_page
|
| 454 |
+
end_idx = min(start_idx + users_per_page, total_users)
|
| 455 |
+
|
| 456 |
+
sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
|
| 457 |
+
|
| 458 |
+
users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
|
| 459 |
+
|
| 460 |
+
for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
|
| 461 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 462 |
+
username = user_info.get('username', 'N/A')
|
| 463 |
+
first_name = user_info.get('first_name', 'N/A')
|
| 464 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 465 |
+
message_count = user_info.get('message_count', 0)
|
| 466 |
+
context_count = len(user_info.get('context', []))
|
| 467 |
+
|
| 468 |
+
users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
|
| 469 |
+
users_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 470 |
+
users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 471 |
+
|
| 472 |
+
keyboard = []
|
| 473 |
+
if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
|
| 474 |
+
if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
|
| 475 |
+
|
| 476 |
+
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
|
| 477 |
+
await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
|
| 478 |
+
|
| 479 |
+
@admin_only
|
| 480 |
+
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 481 |
+
"""جستجوی کاربر بر اساس نام یا نام کاربری."""
|
| 482 |
+
if not context.args:
|
| 483 |
+
await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
|
| 484 |
+
return
|
| 485 |
+
|
| 486 |
+
search_term = " ".join(context.args).lower()
|
| 487 |
+
users = data_manager.DATA['users']
|
| 488 |
+
|
| 489 |
+
matching_users = []
|
| 490 |
+
for user_id, user_info in users.items():
|
| 491 |
+
# استفاده از (value or '') برای جلوگیری از خطا در صورت وجود None
|
| 492 |
+
first_name = (user_info.get('first_name') or '').lower()
|
| 493 |
+
username = (user_info.get('username') or '').lower()
|
| 494 |
+
|
| 495 |
+
if search_term in first_name or search_term in username:
|
| 496 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 497 |
+
matching_users.append((user_id, user_info, is_banned))
|
| 498 |
+
|
| 499 |
+
if not matching_users:
|
| 500 |
+
await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
|
| 501 |
+
return
|
| 502 |
+
|
| 503 |
+
results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
|
| 504 |
+
|
| 505 |
+
for user_id, user_info, is_banned in matching_users:
|
| 506 |
+
username_display = user_info.get('username', 'N/A')
|
| 507 |
+
first_name_display = user_info.get('first_name', 'N/A')
|
| 508 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 509 |
+
message_count = user_info.get('message_count', 0)
|
| 510 |
+
context_count = len(user_info.get('context', []))
|
| 511 |
+
|
| 512 |
+
results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
|
| 513 |
+
results_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 514 |
+
results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 515 |
+
|
| 516 |
+
await update.message.reply_text(results_text, parse_mode='Markdown')
|
| 517 |
+
|
| 518 |
+
@admin_only
|
| 519 |
+
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 520 |
+
"""ایجاد نسخه پشتیبان از دادههای ربات."""
|
| 521 |
+
try:
|
| 522 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 523 |
+
backup_file = f"bot_backup_{timestamp}.json"
|
| 524 |
+
|
| 525 |
+
data_to_backup = data_manager.DATA.copy()
|
| 526 |
+
data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
|
| 527 |
+
|
| 528 |
+
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 529 |
+
json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
|
| 530 |
+
|
| 531 |
+
await update.message.reply_document(
|
| 532 |
+
document=open(backup_file, 'rb'),
|
| 533 |
+
caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
logger.info(f"Backup created: {backup_file}")
|
| 537 |
+
os.remove(backup_file) # حذف فایل پس از ارسال
|
| 538 |
+
except Exception as e:
|
| 539 |
+
await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
|
| 540 |
+
logger.error(f"Error creating backup: {e}")
|
| 541 |
+
|
| 542 |
+
@admin_only
|
| 543 |
+
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 544 |
+
"""ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
|
| 545 |
+
users = data_manager.DATA['users']
|
| 546 |
+
|
| 547 |
+
df_data = []
|
| 548 |
+
for user_id, user_info in users.items():
|
| 549 |
+
is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
|
| 550 |
+
context_count = len(user_info.get('context', []))
|
| 551 |
+
context_tokens = data_manager.get_context_token_count(int(user_id))
|
| 552 |
+
|
| 553 |
+
df_data.append({
|
| 554 |
+
'User ID': user_id,
|
| 555 |
+
'First Name': user_info.get('first_name', 'N/A'),
|
| 556 |
+
'Username': user_info.get('username', 'N/A'),
|
| 557 |
+
'Message Count': user_info.get('message_count', 0),
|
| 558 |
+
'Context Messages': context_count,
|
| 559 |
+
'Context Tokens': context_tokens,
|
| 560 |
+
'First Seen': user_info.get('first_seen', 'N/A'),
|
| 561 |
+
'Last Seen': user_info.get('last_seen', 'N/A'),
|
| 562 |
+
'Banned': is_banned
|
| 563 |
+
})
|
| 564 |
+
|
| 565 |
+
df = pd.DataFrame(df_data)
|
| 566 |
+
|
| 567 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
|
| 568 |
+
df.to_csv(f.name, index=False)
|
| 569 |
+
temp_file_path = f.name
|
| 570 |
+
|
| 571 |
+
await update.message.reply_document(
|
| 572 |
+
document=open(temp_file_path, 'rb'),
|
| 573 |
+
caption="📊 فایل CSV اطلاعات کاربران"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
os.unlink(temp_file_path)
|
| 577 |
+
|
| 578 |
+
@admin_only
|
| 579 |
+
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 580 |
+
"""حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع میدهد."""
|
| 581 |
+
if not context.args or context.args[0].lower() not in ['on', 'off']:
|
| 582 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
|
| 583 |
+
return
|
| 584 |
+
|
| 585 |
+
status = context.args[0].lower()
|
| 586 |
+
|
| 587 |
+
if status == 'on':
|
| 588 |
+
if data_manager.DATA.get('maintenance_mode', False):
|
| 589 |
+
await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
|
| 590 |
+
return
|
| 591 |
+
|
| 592 |
+
data_manager.DATA['maintenance_mode'] = True
|
| 593 |
+
data_manager.save_data()
|
| 594 |
+
|
| 595 |
+
await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاعرسانی به کاربران...")
|
| 596 |
+
|
| 597 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 598 |
+
for user_id_str in user_ids:
|
| 599 |
+
try:
|
| 600 |
+
# به ادمینها پیام ارسال نشود
|
| 601 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 602 |
+
await context.bot.send_message(
|
| 603 |
+
chat_id=int(user_id_str),
|
| 604 |
+
text="🔧 ربات در حال حاضر در حالت بهروزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
|
| 605 |
+
)
|
| 606 |
+
await asyncio.sleep(0.05) # جلوگیری از محدودیت تلگرام
|
| 607 |
+
except TelegramError:
|
| 608 |
+
continue # نادیده گرفتن کاربرانی که ربات را مسدود کردهاند
|
| 609 |
+
|
| 610 |
+
elif status == 'off':
|
| 611 |
+
if not data_manager.DATA.get('maintenance_mode', False):
|
| 612 |
+
await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
|
| 613 |
+
return
|
| 614 |
+
|
| 615 |
+
data_manager.DATA['maintenance_mode'] = False
|
| 616 |
+
data_manager.save_data()
|
| 617 |
+
|
| 618 |
+
await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاعرسانی به کاربران...")
|
| 619 |
+
|
| 620 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 621 |
+
for user_id_str in user_ids:
|
| 622 |
+
try:
|
| 623 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 624 |
+
await context.bot.send_message(
|
| 625 |
+
chat_id=int(user_id_str),
|
| 626 |
+
text="✅ بهروزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! میتوانید دوباره از ربات استفاده کنید."
|
| 627 |
+
)
|
| 628 |
+
await asyncio.sleep(0.05)
|
| 629 |
+
except TelegramError:
|
| 630 |
+
continue
|
| 631 |
+
|
| 632 |
+
@admin_only
|
| 633 |
+
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 634 |
+
"""تنظیم پیام خوشامدگویی جدید."""
|
| 635 |
+
if not context.args:
|
| 636 |
+
await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
|
| 637 |
+
"مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
|
| 638 |
+
return
|
| 639 |
+
|
| 640 |
+
new_message = " ".join(context.args)
|
| 641 |
+
data_manager.DATA['welcome_message'] = new_message
|
| 642 |
+
data_manager.save_data()
|
| 643 |
+
|
| 644 |
+
await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت بهروزرسانی شد.")
|
| 645 |
+
|
| 646 |
+
@admin_only
|
| 647 |
+
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 648 |
+
"""تنظیم پیام خداحافظی جدید."""
|
| 649 |
+
if not context.args:
|
| 650 |
+
await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
|
| 651 |
+
"مثال: `/set_goodbye {user_mention}، خداحافظ!`")
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
new_message = " ".join(context.args)
|
| 655 |
+
data_manager.DATA['goodbye_message'] = new_message
|
| 656 |
+
data_manager.save_data()
|
| 657 |
+
|
| 658 |
+
await update.message.reply_text("✅ پیام خداحافظی با موفقیت بهروزرسانی شد.")
|
| 659 |
+
|
| 660 |
+
@admin_only
|
| 661 |
+
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 662 |
+
"""ایجاد و ارسال نمودار فعالیت کاربران."""
|
| 663 |
+
users = data_manager.DATA['users']
|
| 664 |
+
activity_hours = [0] * 24
|
| 665 |
+
|
| 666 |
+
for user_info in users.values():
|
| 667 |
+
if 'last_seen' in user_info:
|
| 668 |
+
try:
|
| 669 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 670 |
+
activity_hours[last_seen.hour] += 1
|
| 671 |
+
except ValueError:
|
| 672 |
+
continue
|
| 673 |
+
|
| 674 |
+
plt.figure(figsize=(12, 6))
|
| 675 |
+
plt.bar(range(24), activity_hours, color='skyblue')
|
| 676 |
+
plt.title('نمودار فعالیت کاربران بر اساس ساعت')
|
| 677 |
+
plt.xlabel('ساعت')
|
| 678 |
+
plt.ylabel('تعداد کاربران فعال')
|
| 679 |
+
plt.xticks(range(24))
|
| 680 |
+
plt.grid(axis='y', alpha=0.3)
|
| 681 |
+
|
| 682 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
|
| 683 |
+
plt.savefig(f.name, bbox_inches='tight')
|
| 684 |
+
temp_file_path = f.name
|
| 685 |
+
|
| 686 |
+
plt.close()
|
| 687 |
+
|
| 688 |
+
await update.message.reply_photo(
|
| 689 |
+
photo=open(temp_file_path, 'rb'),
|
| 690 |
+
caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
os.unlink(temp_file_path)
|
| 694 |
+
|
| 695 |
+
@admin_only
|
| 696 |
+
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 697 |
+
"""نمایش آمار زمان پاسخگویی ربات."""
|
| 698 |
+
stats = data_manager.DATA['stats']
|
| 699 |
+
await update.message.reply_text(
|
| 700 |
+
"📈 **آمار زمان پاسخگویی ربات**\n\n"
|
| 701 |
+
f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
|
| 702 |
+
f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
|
| 703 |
+
f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
|
| 704 |
+
f"📊 کل پاسخهای ثبت شده: `{stats.get('total_responses', 0)}`"
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
@admin_only
|
| 708 |
+
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 709 |
+
"""افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
|
| 710 |
+
if not context.args:
|
| 711 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 712 |
+
"مثال: `/add_blocked_word کلمه_نامناسب`")
|
| 713 |
+
return
|
| 714 |
+
|
| 715 |
+
word = " ".join(context.args).lower()
|
| 716 |
+
|
| 717 |
+
if word in data_manager.DATA['blocked_words']:
|
| 718 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
|
| 719 |
+
return
|
| 720 |
+
|
| 721 |
+
data_manager.DATA['blocked_words'].append(word)
|
| 722 |
+
data_manager.save_data()
|
| 723 |
+
|
| 724 |
+
await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
|
| 725 |
+
|
| 726 |
+
@admin_only
|
| 727 |
+
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 728 |
+
"""حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
|
| 729 |
+
if not context.args:
|
| 730 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 731 |
+
"مثال: `/remove_blocked_word کلمه_نامناسب`")
|
| 732 |
+
return
|
| 733 |
+
|
| 734 |
+
word = " ".join(context.args).lower()
|
| 735 |
+
|
| 736 |
+
if word not in data_manager.DATA['blocked_words']:
|
| 737 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
|
| 738 |
+
return
|
| 739 |
+
|
| 740 |
+
data_manager.DATA['blocked_words'].remove(word)
|
| 741 |
+
data_manager.save_data()
|
| 742 |
+
|
| 743 |
+
await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
|
| 744 |
+
|
| 745 |
+
@admin_only
|
| 746 |
+
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 747 |
+
"""نمایش لیست کلمات مسدود شده."""
|
| 748 |
+
if not data_manager.DATA['blocked_words']:
|
| 749 |
+
await update.message.reply_text("هیچ کلمه مسدود شدهای در لیست وجود ندارد.")
|
| 750 |
+
return
|
| 751 |
+
|
| 752 |
+
words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
|
| 753 |
+
await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
|
| 754 |
+
|
| 755 |
+
@admin_only
|
| 756 |
+
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 757 |
+
"""نمایش اطلاعات سیستم و منابع."""
|
| 758 |
+
bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
|
| 759 |
+
bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
|
| 760 |
+
uptime = datetime.now() - bot_start_time
|
| 761 |
+
|
| 762 |
+
# محاسبه آمار context
|
| 763 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 764 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
|
| 765 |
+
|
| 766 |
+
system_info = (
|
| 767 |
+
f"💻 **اطلاعات سیستم:**\n\n"
|
| 768 |
+
f"🖥️ سیستمعامل: {platform.system()} {platform.release()}\n"
|
| 769 |
+
f"🐍 نسخه پایتون: {platform.python_version()}\n"
|
| 770 |
+
f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
|
| 771 |
+
f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
|
| 772 |
+
f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
|
| 773 |
+
f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
|
| 774 |
+
f"⏱️ زمان اجرای ربات: {uptime}\n"
|
| 775 |
+
f"💭 کاربران با context: {users_with_context}\n"
|
| 776 |
+
f"💬 کل پیامهای context: {total_context_messages}"
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
await update.message.reply_text(system_info, parse_mode='Markdown')
|
| 780 |
+
|
| 781 |
+
@admin_only
|
| 782 |
+
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 783 |
+
"""ریست کردن آمار ربات."""
|
| 784 |
+
if not context.args:
|
| 785 |
+
await update.message.reply_text("⚠️ لطفاً نوع آماری که میخواهید ریست کنید را مشخص کنید.\n"
|
| 786 |
+
"مثال: `/reset_stats messages` یا `/reset_stats all`")
|
| 787 |
+
return
|
| 788 |
+
|
| 789 |
+
stat_type = context.args[0].lower()
|
| 790 |
+
|
| 791 |
+
if stat_type == "messages":
|
| 792 |
+
data_manager.DATA['stats']['total_messages'] = 0
|
| 793 |
+
for user_id in data_manager.DATA['users']:
|
| 794 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 795 |
+
await update.message.reply_text("✅ آمار پیامها با موفقیت ریست شد.")
|
| 796 |
+
|
| 797 |
+
elif stat_type == "all":
|
| 798 |
+
data_manager.DATA['stats'] = {
|
| 799 |
+
'total_messages': 0,
|
| 800 |
+
'total_users': len(data_manager.DATA['users']),
|
| 801 |
+
'avg_response_time': 0,
|
| 802 |
+
'max_response_time': 0,
|
| 803 |
+
'min_response_time': 0,
|
| 804 |
+
'total_responses': 0
|
| 805 |
+
}
|
| 806 |
+
for user_id in data_manager.DATA['users']:
|
| 807 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 808 |
+
await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
|
| 809 |
+
|
| 810 |
+
else:
|
| 811 |
+
await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینههای موجود: messages, all")
|
| 812 |
+
return
|
| 813 |
+
|
| 814 |
+
data_manager.save_data()
|
| 815 |
+
|
| 816 |
+
# --- دستورات جدید برای مدیریت context ---
|
| 817 |
+
|
| 818 |
+
@admin_only
|
| 819 |
+
async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 820 |
+
"""پاک کردن context یک کاربر"""
|
| 821 |
+
if not context.args or not context.args[0].isdigit():
|
| 822 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
|
| 823 |
+
return
|
| 824 |
+
|
| 825 |
+
user_id = int(context.args[0])
|
| 826 |
+
data_manager.clear_user_context(user_id)
|
| 827 |
+
|
| 828 |
+
await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
|
| 829 |
+
|
| 830 |
+
@admin_only
|
| 831 |
+
async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 832 |
+
"""مشاهده context یک کاربر"""
|
| 833 |
+
if not context.args or not context.args[0].isdigit():
|
| 834 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
|
| 835 |
+
return
|
| 836 |
+
|
| 837 |
+
user_id = int(context.args[0])
|
| 838 |
+
user_context = data_manager.get_user_context(user_id)
|
| 839 |
+
|
| 840 |
+
if not user_context:
|
| 841 |
+
await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
|
| 842 |
+
return
|
| 843 |
+
|
| 844 |
+
context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
|
| 845 |
+
total_tokens = 0
|
| 846 |
+
|
| 847 |
+
for i, msg in enumerate(user_context, 1):
|
| 848 |
+
role_emoji = "👤" if msg['role'] == 'user' else "🤖"
|
| 849 |
+
tokens = data_manager.count_tokens(msg['content'])
|
| 850 |
+
total_tokens += tokens
|
| 851 |
+
|
| 852 |
+
# کوتاه کردن متن طولانی
|
| 853 |
+
content_preview = msg['content']
|
| 854 |
+
if len(content_preview) > 100:
|
| 855 |
+
content_preview = content_preview[:100] + "..."
|
| 856 |
+
|
| 857 |
+
context_text += f"{i}. {role_emoji} **{msg['role']}** ({tokens} توکن)\n"
|
| 858 |
+
context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
|
| 859 |
+
context_text += f" 📝 {content_preview}\n\n"
|
| 860 |
+
|
| 861 |
+
context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن"
|
| 862 |
+
|
| 863 |
+
await update.message.reply_text(context_text, parse_mode='Markdown')
|
| 864 |
+
|
| 865 |
+
# --- هندلر برای دکمههای صفحهبندی ---
|
| 866 |
+
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 867 |
+
"""پردازش دکمههای صفحهبندی لیست کاربران."""
|
| 868 |
+
query = update.callback_query
|
| 869 |
+
await query.answer()
|
| 870 |
+
|
| 871 |
+
if query.data.startswith("users_list:"):
|
| 872 |
+
page = int(query.data.split(":")[1])
|
| 873 |
+
context.args = [str(page)]
|
| 874 |
+
await admin_users_list(update, context)
|
| 875 |
+
|
| 876 |
+
# --- تابع برای پردازش ارسالهای برنامهریزی شده ---
|
| 877 |
+
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
|
| 878 |
+
"""پردازش ارسالهای برنامهریزی شده و ارسال پیامها در زمان مقرر."""
|
| 879 |
+
now = datetime.now()
|
| 880 |
+
broadcasts_to_send_indices = []
|
| 881 |
+
|
| 882 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
|
| 883 |
+
if broadcast['status'] == 'pending':
|
| 884 |
+
broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
|
| 885 |
+
if broadcast_time <= now:
|
| 886 |
+
broadcasts_to_send_indices.append(i)
|
| 887 |
+
|
| 888 |
+
if not broadcasts_to_send_indices:
|
| 889 |
+
return
|
| 890 |
+
|
| 891 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 892 |
+
|
| 893 |
+
for index in broadcasts_to_send_indices:
|
| 894 |
+
broadcast = data_manager.DATA['scheduled_broadcasts'][index]
|
| 895 |
+
message_text = broadcast['message']
|
| 896 |
+
total_sent, total_failed = 0, 0
|
| 897 |
+
|
| 898 |
+
for user_id_str in user_ids:
|
| 899 |
+
try:
|
| 900 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 901 |
+
total_sent += 1
|
| 902 |
+
await asyncio.sleep(0.05)
|
| 903 |
+
except TelegramError as e:
|
| 904 |
+
logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
|
| 905 |
+
total_failed += 1
|
| 906 |
+
|
| 907 |
+
# بهروزرسانی وضعیت ارسال
|
| 908 |
+
data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
|
| 909 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
|
| 910 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
|
| 911 |
+
data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
|
| 912 |
+
|
| 913 |
+
logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
|
| 914 |
+
|
| 915 |
+
data_manager.save_data()
|
| 916 |
+
|
| 917 |
+
# --- تابع راهاندازی هندلرها ---
|
| 918 |
+
def setup_admin_handlers(application):
|
| 919 |
+
"""هندلرهای پنل ادمین را به اپلیکیشن اضافه میکند."""
|
| 920 |
+
# هندلرهای اصلی
|
| 921 |
+
application.add_handler(CommandHandler("commands", admin_commands))
|
| 922 |
+
application.add_handler(CommandHandler("stats", admin_stats))
|
| 923 |
+
application.add_handler(CommandHandler("broadcast", admin_broadcast))
|
| 924 |
+
application.add_handler(CommandHandler("ban", admin_ban))
|
| 925 |
+
application.add_handler(CommandHandler("unban", admin_unban))
|
| 926 |
+
application.add_handler(CommandHandler("user_info", admin_userinfo))
|
| 927 |
+
application.add_handler(CommandHandler("logs", admin_logs))
|
| 928 |
+
application.add_handler(CommandHandler("logs_file", admin_logs_file))
|
| 929 |
+
application.add_handler(CommandHandler("users_list", admin_users_list))
|
| 930 |
+
application.add_handler(CommandHandler("user_search", admin_user_search))
|
| 931 |
+
application.add_handler(CommandHandler("backup", admin_backup))
|
| 932 |
+
|
| 933 |
+
# هندلرهای جدید
|
| 934 |
+
application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
|
| 935 |
+
application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
|
| 936 |
+
application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
|
| 937 |
+
application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
|
| 938 |
+
application.add_handler(CommandHandler("direct_message", admin_direct_message))
|
| 939 |
+
application.add_handler(CommandHandler("export_csv", admin_export_csv))
|
| 940 |
+
application.add_handler(CommandHandler("maintenance", admin_maintenance))
|
| 941 |
+
application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
|
| 942 |
+
application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
|
| 943 |
+
application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
|
| 944 |
+
application.add_handler(CommandHandler("response_stats", admin_response_stats))
|
| 945 |
+
application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
|
| 946 |
+
application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
|
| 947 |
+
application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
|
| 948 |
+
application.add_handler(CommandHandler("system_info", admin_system_info))
|
| 949 |
+
application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
|
| 950 |
+
|
| 951 |
+
# هندلرهای مدیریت context
|
| 952 |
+
application.add_handler(CommandHandler("clear_context", admin_clear_context))
|
| 953 |
+
application.add_handler(CommandHandler("view_context", admin_view_context))
|
| 954 |
+
|
| 955 |
+
# هندلر برای دکمههای صفحهبندی
|
| 956 |
+
application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
|
| 957 |
+
|
| 958 |
+
# شروع وظیفه دورهای برای بررسی ارسالهای برنامهریزی شده
|
| 959 |
+
application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
|
| 960 |
+
|
| 961 |
+
logger.info("Admin panel handlers have been set up.")
|
Version2_Context/data_manager.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"banned_users": set(),
|
| 18 |
+
"stats": {
|
| 19 |
+
"total_messages": 0,
|
| 20 |
+
"total_users": 0,
|
| 21 |
+
"avg_response_time": 0.0,
|
| 22 |
+
"max_response_time": 0.0,
|
| 23 |
+
"min_response_time": float('inf'),
|
| 24 |
+
"total_responses": 0
|
| 25 |
+
},
|
| 26 |
+
"welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
|
| 27 |
+
"goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
|
| 28 |
+
"maintenance_mode": False,
|
| 29 |
+
"blocked_words": [],
|
| 30 |
+
"scheduled_broadcasts": [],
|
| 31 |
+
"bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
# تابع برای شمارش توکنها
|
| 37 |
+
def count_tokens(text: str) -> int:
|
| 38 |
+
"""شمارش تعداد توکنهای متن با استفاده از tokenizer"""
|
| 39 |
+
try:
|
| 40 |
+
# استفاده از tokenizer برای gpt-3.5-turbo
|
| 41 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 42 |
+
return len(encoding.encode(text))
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.warning(f"Error counting tokens: {e}, using fallback")
|
| 45 |
+
# تقریب: هر 4 کاراکتر = 1 توکن
|
| 46 |
+
return max(1, len(text) // 4)
|
| 47 |
+
|
| 48 |
+
def load_data():
|
| 49 |
+
"""دادهها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره میکند."""
|
| 50 |
+
global DATA
|
| 51 |
+
try:
|
| 52 |
+
if not os.path.exists(DATA_FILE):
|
| 53 |
+
logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد میشود.")
|
| 54 |
+
save_data()
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
| 58 |
+
loaded_data = json.load(f)
|
| 59 |
+
loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
|
| 60 |
+
|
| 61 |
+
# اطمینان از وجود کلیدهای جدید در فایلهای قدیمی
|
| 62 |
+
if 'blocked_words' not in loaded_data: loaded_data['blocked_words'] = []
|
| 63 |
+
if 'scheduled_broadcasts' not in loaded_data: loaded_data['scheduled_broadcasts'] = []
|
| 64 |
+
if 'maintenance_mode' not in loaded_data: loaded_data['maintenance_mode'] = False
|
| 65 |
+
if 'bot_start_time' not in loaded_data: loaded_data['bot_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 66 |
+
if 'avg_response_time' not in loaded_data['stats']:
|
| 67 |
+
loaded_data['stats']['avg_response_time'] = 0.0
|
| 68 |
+
loaded_data['stats']['max_response_time'] = 0.0
|
| 69 |
+
loaded_data['stats']['min_response_time'] = float('inf')
|
| 70 |
+
loaded_data['stats']['total_responses'] = 0
|
| 71 |
+
|
| 72 |
+
# اطمینان از وجود context برای کاربران قدیمی
|
| 73 |
+
for user_id in loaded_data.get('users', {}):
|
| 74 |
+
if 'context' not in loaded_data['users'][user_id]:
|
| 75 |
+
loaded_data['users'][user_id]['context'] = []
|
| 76 |
+
|
| 77 |
+
DATA.update(loaded_data)
|
| 78 |
+
logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.")
|
| 79 |
+
|
| 80 |
+
except json.JSONDecodeError as e:
|
| 81 |
+
logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 84 |
+
|
| 85 |
+
def save_data():
|
| 86 |
+
"""کش گلوبال دادهها را در فایل JSON ذخیره میکند."""
|
| 87 |
+
global DATA
|
| 88 |
+
try:
|
| 89 |
+
data_to_save = DATA.copy()
|
| 90 |
+
data_to_save['banned_users'] = list(DATA['banned_users'])
|
| 91 |
+
|
| 92 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 93 |
+
json.dump(data_to_save, f, indent=4, ensure_ascii=False)
|
| 94 |
+
logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.")
|
| 95 |
+
except Exception as e:
|
| 96 |
+
logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}")
|
| 97 |
+
|
| 98 |
+
def update_user_stats(user_id: int, user):
|
| 99 |
+
"""آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند."""
|
| 100 |
+
global DATA
|
| 101 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 102 |
+
user_id_str = str(user_id)
|
| 103 |
+
|
| 104 |
+
if user_id_str not in DATA['users']:
|
| 105 |
+
DATA['users'][user_id_str] = {
|
| 106 |
+
'first_name': user.first_name,
|
| 107 |
+
'username': user.username,
|
| 108 |
+
'first_seen': now_str,
|
| 109 |
+
'message_count': 0,
|
| 110 |
+
'context': [] # اضافه کردن context خالی برای کاربر جدید
|
| 111 |
+
}
|
| 112 |
+
DATA['stats']['total_users'] += 1
|
| 113 |
+
logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
|
| 114 |
+
|
| 115 |
+
DATA['users'][user_id_str]['last_seen'] = now_str
|
| 116 |
+
DATA['users'][user_id_str]['message_count'] += 1
|
| 117 |
+
DATA['stats']['total_messages'] += 1
|
| 118 |
+
|
| 119 |
+
save_data()
|
| 120 |
+
|
| 121 |
+
def update_response_stats(response_time: float):
|
| 122 |
+
"""آمار زمان پاسخگویی را بهروز میکند."""
|
| 123 |
+
global DATA
|
| 124 |
+
|
| 125 |
+
if DATA['stats']['total_responses'] == 0:
|
| 126 |
+
DATA['stats']['min_response_time'] = response_time
|
| 127 |
+
|
| 128 |
+
DATA['stats']['total_responses'] += 1
|
| 129 |
+
|
| 130 |
+
# محاسبه میانگین جدید
|
| 131 |
+
current_avg = DATA['stats']['avg_response_time']
|
| 132 |
+
total_responses = DATA['stats']['total_responses']
|
| 133 |
+
new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
|
| 134 |
+
DATA['stats']['avg_response_time'] = new_avg
|
| 135 |
+
|
| 136 |
+
# بهروزرسانی حداکثر و حداقل زمان پاسخگویی
|
| 137 |
+
if response_time > DATA['stats']['max_response_time']:
|
| 138 |
+
DATA['stats']['max_response_time'] = response_time
|
| 139 |
+
|
| 140 |
+
if response_time < DATA['stats']['min_response_time']:
|
| 141 |
+
DATA['stats']['min_response_time'] = response_time
|
| 142 |
+
|
| 143 |
+
save_data()
|
| 144 |
+
|
| 145 |
+
def is_user_banned(user_id: int) -> bool:
|
| 146 |
+
"""بررسی میکند آیا کاربر مسدود شده است یا خیر."""
|
| 147 |
+
return user_id in DATA['banned_users']
|
| 148 |
+
|
| 149 |
+
def ban_user(user_id: int):
|
| 150 |
+
"""کاربر را مسدود کرده و ذخیره میکند."""
|
| 151 |
+
DATA['banned_users'].add(user_id)
|
| 152 |
+
save_data()
|
| 153 |
+
|
| 154 |
+
def unban_user(user_id: int):
|
| 155 |
+
"""مسدودیت کاربر را برداشته و ذخیره میکند."""
|
| 156 |
+
DATA['banned_users'].discard(user_id)
|
| 157 |
+
save_data()
|
| 158 |
+
|
| 159 |
+
def contains_blocked_words(text: str) -> bool:
|
| 160 |
+
"""بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر."""
|
| 161 |
+
if not DATA['blocked_words']:
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
text_lower = text.lower()
|
| 165 |
+
for word in DATA['blocked_words']:
|
| 166 |
+
if word in text_lower:
|
| 167 |
+
return True
|
| 168 |
+
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
def get_active_users(days: int) -> list:
|
| 172 |
+
"""لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند."""
|
| 173 |
+
now = datetime.now()
|
| 174 |
+
cutoff_date = now - timedelta(days=days)
|
| 175 |
+
|
| 176 |
+
active_users = []
|
| 177 |
+
for user_id, user_info in DATA['users'].items():
|
| 178 |
+
if 'last_seen' in user_info:
|
| 179 |
+
try:
|
| 180 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 181 |
+
if last_seen >= cutoff_date:
|
| 182 |
+
active_users.append(int(user_id))
|
| 183 |
+
except ValueError:
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
return active_users
|
| 187 |
+
|
| 188 |
+
def get_users_by_message_count(min_count: int) -> list:
|
| 189 |
+
"""لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند."""
|
| 190 |
+
users = []
|
| 191 |
+
for user_id, user_info in DATA['users'].items():
|
| 192 |
+
if user_info.get('message_count', 0) >= min_count:
|
| 193 |
+
users.append(int(user_id))
|
| 194 |
+
|
| 195 |
+
return users
|
| 196 |
+
|
| 197 |
+
# --- توابع مدیریت context ---
|
| 198 |
+
|
| 199 |
+
def add_to_user_context(user_id: int, role: str, content: str):
|
| 200 |
+
"""اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن""" # از 512 به 1024 تغییر یافت
|
| 201 |
+
user_id_str = str(user_id)
|
| 202 |
+
|
| 203 |
+
if user_id_str not in DATA['users']:
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
if 'context' not in DATA['users'][user_id_str]:
|
| 207 |
+
DATA['users'][user_id_str]['context'] = []
|
| 208 |
+
|
| 209 |
+
# اضافه کردن پیام جدید
|
| 210 |
+
message = {
|
| 211 |
+
'role': role, # 'user' یا 'assistant'
|
| 212 |
+
'content': content,
|
| 213 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
DATA['users'][user_id_str]['context'].append(message)
|
| 217 |
+
|
| 218 |
+
# محدود کردن context به ۱۰۲۴ توکن # از 512 به 1024 تغییر یافت
|
| 219 |
+
trim_user_context(user_id)
|
| 220 |
+
|
| 221 |
+
save_data()
|
| 222 |
+
|
| 223 |
+
# خط 165 را پیدا کنید و تغییر دهید:
|
| 224 |
+
def trim_user_context(user_id: int, max_tokens: int = 1024): # از 512 به 1024 تغییر یافت
|
| 225 |
+
"""کوتاه کردن context کاربر به تعداد توکن مشخص"""
|
| 226 |
+
user_id_str = str(user_id)
|
| 227 |
+
|
| 228 |
+
if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
context = DATA['users'][user_id_str]['context']
|
| 232 |
+
|
| 233 |
+
if not context:
|
| 234 |
+
return
|
| 235 |
+
|
| 236 |
+
# محاسبه توکنهای کل
|
| 237 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 238 |
+
|
| 239 |
+
# حذف قدیمیترین پیامها تا زمانی که توکنها زیر حد مجاز باشد
|
| 240 |
+
while total_tokens > max_tokens and len(context) > 1:
|
| 241 |
+
removed_message = context.pop(0) # ��ذف قدیمیترین پیام
|
| 242 |
+
total_tokens -= count_tokens(removed_message['content'])
|
| 243 |
+
|
| 244 |
+
# اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن
|
| 245 |
+
if total_tokens > max_tokens and context:
|
| 246 |
+
# از آخرین پیام (جدیدترین) شروع به کوتاه کردن کن
|
| 247 |
+
last_message = context[-1]
|
| 248 |
+
content = last_message['content']
|
| 249 |
+
|
| 250 |
+
# کوتاه کردن محتوا
|
| 251 |
+
tokens = count_tokens(content)
|
| 252 |
+
if tokens > max_tokens:
|
| 253 |
+
# اگر یک پیام به تنهایی بیشتر از حد مجاز باشد، آن را حذف کن
|
| 254 |
+
context.pop()
|
| 255 |
+
else:
|
| 256 |
+
# در غیر این صورت، محتوای پیام را کوتاه کن
|
| 257 |
+
while tokens > (max_tokens - (total_tokens - tokens)) and content:
|
| 258 |
+
# حذف کلمات از انتها
|
| 259 |
+
words = content.split()
|
| 260 |
+
if len(words) > 1:
|
| 261 |
+
content = ' '.join(words[:-1])
|
| 262 |
+
else:
|
| 263 |
+
content = content[:-1] if len(content) > 1 else ''
|
| 264 |
+
tokens = count_tokens(content)
|
| 265 |
+
|
| 266 |
+
if content: # اگر محتوایی باقی مانده
|
| 267 |
+
context[-1]['content'] = content
|
| 268 |
+
else: # اگر تمام محتوا حذف شد
|
| 269 |
+
context.pop()
|
| 270 |
+
|
| 271 |
+
save_data()
|
| 272 |
+
|
| 273 |
+
def get_user_context(user_id: int) -> list:
|
| 274 |
+
"""دریافت context کاربر"""
|
| 275 |
+
user_id_str = str(user_id)
|
| 276 |
+
|
| 277 |
+
if user_id_str not in DATA['users']:
|
| 278 |
+
return []
|
| 279 |
+
|
| 280 |
+
return DATA['users'][user_id_str].get('context', [])
|
| 281 |
+
|
| 282 |
+
def clear_user_context(user_id: int):
|
| 283 |
+
"""پاک کردن context کاربر"""
|
| 284 |
+
user_id_str = str(user_id)
|
| 285 |
+
|
| 286 |
+
if user_id_str in DATA['users']:
|
| 287 |
+
if 'context' in DATA['users'][user_id_str]:
|
| 288 |
+
DATA['users'][user_id_str]['context'] = []
|
| 289 |
+
save_data()
|
| 290 |
+
logger.info(f"Context cleared for user {user_id}")
|
| 291 |
+
|
| 292 |
+
def get_context_summary(user_id: int) -> str:
|
| 293 |
+
"""خلاصهای از context کاربر"""
|
| 294 |
+
context = get_user_context(user_id)
|
| 295 |
+
if not context:
|
| 296 |
+
return "بدون تاریخچه"
|
| 297 |
+
|
| 298 |
+
total_messages = len(context)
|
| 299 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 300 |
+
|
| 301 |
+
# نمایش آخرین پیام
|
| 302 |
+
last_message = context[-1] if context else {}
|
| 303 |
+
last_content = last_message.get('content', '')[:50]
|
| 304 |
+
if len(last_message.get('content', '')) > 50:
|
| 305 |
+
last_content += "..."
|
| 306 |
+
|
| 307 |
+
return f"{total_messages} پیام ({total_tokens} توکن) - آخرین: {last_message.get('role', '')}: {last_content}"
|
| 308 |
+
|
| 309 |
+
def get_context_for_api(user_id: int) -> list:
|
| 310 |
+
"""فرمت context برای ارسال به API"""
|
| 311 |
+
context = get_user_context(user_id)
|
| 312 |
+
|
| 313 |
+
# تبدیل به فرمت مورد نیاز API
|
| 314 |
+
api_context = []
|
| 315 |
+
for msg in context:
|
| 316 |
+
api_context.append({
|
| 317 |
+
'role': msg['role'],
|
| 318 |
+
'content': msg['content']
|
| 319 |
+
})
|
| 320 |
+
|
| 321 |
+
return api_context
|
| 322 |
+
|
| 323 |
+
def get_context_token_count(user_id: int) -> int:
|
| 324 |
+
"""تعداد کل توکنهای context کاربر"""
|
| 325 |
+
context = get_user_context(user_id)
|
| 326 |
+
return sum(count_tokens(msg['content']) for msg in context)
|
| 327 |
+
|
| 328 |
+
# بارگذاری اولیه دادهها در زمان ایمپورت شدن ماژول
|
| 329 |
+
load_data()
|
Version2_Context/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()
|
Version2_Context/main.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# شروع سرویس نگه داشتن ربات فعال
|
| 18 |
+
start_keep_alive()
|
| 19 |
+
|
| 20 |
+
# --- بهبود لاگینگ ---
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
filename=data_manager.LOG_FILE,
|
| 25 |
+
filemode='a'
|
| 26 |
+
)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
with open(data_manager.LOG_FILE, 'a') as f:
|
| 31 |
+
f.write("")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
|
| 34 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 35 |
+
|
| 36 |
+
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
|
| 37 |
+
http_client = httpx.AsyncClient(
|
| 38 |
+
http2=True,
|
| 39 |
+
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
|
| 40 |
+
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# کلاینت OpenAI (HuggingFace)
|
| 44 |
+
client = AsyncOpenAI(
|
| 45 |
+
base_url="https://router.huggingface.co/v1",
|
| 46 |
+
api_key=os.environ["HF_TOKEN"],
|
| 47 |
+
http_client=http_client
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
|
| 51 |
+
user_tasks = {}
|
| 52 |
+
|
| 53 |
+
# --- توابع کمکی برای مدیریت وظایف ---
|
| 54 |
+
def _cleanup_task(task: asyncio.Task, user_id: int):
|
| 55 |
+
if user_id in user_tasks and user_tasks[user_id] == task:
|
| 56 |
+
del user_tasks[user_id]
|
| 57 |
+
logger.info(f"Cleaned up finished task for user {user_id}.")
|
| 58 |
+
try:
|
| 59 |
+
exception = task.exception()
|
| 60 |
+
if exception:
|
| 61 |
+
logger.error(f"Background task for user {user_id} failed: {exception}")
|
| 62 |
+
except asyncio.CancelledError:
|
| 63 |
+
logger.info(f"Task for user {user_id} was cancelled.")
|
| 64 |
+
|
| 65 |
+
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 66 |
+
chat_id = update.effective_chat.id
|
| 67 |
+
user_message = update.message.text
|
| 68 |
+
user_id = update.effective_user.id
|
| 69 |
+
|
| 70 |
+
start_time = time.time()
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 74 |
+
|
| 75 |
+
# دریافت context کاربر
|
| 76 |
+
user_context = data_manager.get_context_for_api(user_id)
|
| 77 |
+
|
| 78 |
+
# اضافه کردن پیام کاربر به context
|
| 79 |
+
data_manager.add_to_user_context(user_id, "user", user_message)
|
| 80 |
+
|
| 81 |
+
# ایجاد لیست پیامها برای API
|
| 82 |
+
messages = user_context.copy()
|
| 83 |
+
|
| 84 |
+
# اضافه کردن پیام جدید به انتهای لیست
|
| 85 |
+
messages.append({"role": "user", "content": user_message})
|
| 86 |
+
|
| 87 |
+
logger.info(f"User {user_id} sending {len(messages)} messages to AI ({data_manager.get_context_token_count(user_id)} tokens)")
|
| 88 |
+
|
| 89 |
+
response = await client.chat.completions.create(
|
| 90 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 91 |
+
messages=messages,
|
| 92 |
+
temperature=0.7,
|
| 93 |
+
top_p=0.95,
|
| 94 |
+
stream=False,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
end_time = time.time()
|
| 98 |
+
response_time = end_time - start_time
|
| 99 |
+
data_manager.update_response_stats(response_time)
|
| 100 |
+
|
| 101 |
+
ai_response = response.choices[0].message.content
|
| 102 |
+
|
| 103 |
+
# اضافه کردن پاسخ هوش مصنوعی به context
|
| 104 |
+
data_manager.add_to_user_context(user_id, "assistant", ai_response)
|
| 105 |
+
|
| 106 |
+
await update.message.reply_text(ai_response)
|
| 107 |
+
data_manager.update_user_stats(user_id, update.effective_user)
|
| 108 |
+
|
| 109 |
+
except httpx.TimeoutException:
|
| 110 |
+
logger.warning(f"Request timed out for user {user_id}.")
|
| 111 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logger.error(f"Error while processing message for user {user_id}: {e}")
|
| 114 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 115 |
+
|
| 116 |
+
# --- هندلرهای اصلی ربات ---
|
| 117 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 118 |
+
user = update.effective_user
|
| 119 |
+
user_id = user.id
|
| 120 |
+
|
| 121 |
+
data_manager.update_user_stats(user_id, user)
|
| 122 |
+
|
| 123 |
+
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
|
| 124 |
+
await update.message.reply_html(
|
| 125 |
+
welcome_msg.format(user_mention=user.mention_html()),
|
| 126 |
+
disable_web_page_preview=True
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 130 |
+
"""پاک کردن تاریخچه چت برای کاربر"""
|
| 131 |
+
user_id = update.effective_user.id
|
| 132 |
+
data_manager.clear_user_context(user_id)
|
| 133 |
+
|
| 134 |
+
await update.message.reply_text(
|
| 135 |
+
"🧹 تاریخچه مکالمه شما پاک شد.\n"
|
| 136 |
+
"از این لحظه مکالمه جدیدی شروع خواهد شد."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 140 |
+
"""نمایش اطلاعات context کاربر"""
|
| 141 |
+
user_id = update.effective_user.id
|
| 142 |
+
context_summary = data_manager.get_context_summary(user_id)
|
| 143 |
+
|
| 144 |
+
await update.message.reply_text(
|
| 145 |
+
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
|
| 146 |
+
f"{context_summary}\n\n"
|
| 147 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 151 |
+
"""نمایش دستورات کمک"""
|
| 152 |
+
help_text = (
|
| 153 |
+
"🤖 **دستورات ربات:**\n\n"
|
| 154 |
+
"🟢 `/start` - شروع کار با ربات\n"
|
| 155 |
+
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
|
| 156 |
+
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
|
| 157 |
+
"🟢 `/help` - نمایش این پیام راهنما\n\n"
|
| 158 |
+
"📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۱۰۲۴ توکن ذخیره میکند. " # از 512 به 1024 تغییر یافت
|
| 159 |
+
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
|
| 160 |
+
)
|
| 161 |
+
await update.message.reply_text(help_text, parse_mode='Markdown')
|
| 162 |
+
|
| 163 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 164 |
+
user_id = update.effective_user.id
|
| 165 |
+
|
| 166 |
+
# بررسی مسدود بودن کاربر
|
| 167 |
+
if data_manager.is_user_banned(user_id):
|
| 168 |
+
logger.info(f"Banned user {user_id} tried to send a message.")
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
# بررسی حالت نگهداری (فقط برای کاربران عادی)
|
| 172 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 173 |
+
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
|
| 174 |
+
return
|
| 175 |
+
|
| 176 |
+
# بررسی کلمات مسدود شده
|
| 177 |
+
if data_manager.contains_blocked_words(update.message.text):
|
| 178 |
+
logger.info(f"User {user_id} sent a message with a blocked word.")
|
| 179 |
+
# میتوانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید
|
| 180 |
+
# await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
if user_id in user_tasks and not user_tasks[user_id].done():
|
| 184 |
+
user_tasks[user_id].cancel()
|
| 185 |
+
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
|
| 186 |
+
|
| 187 |
+
task = asyncio.create_task(_process_user_request(update, context))
|
| 188 |
+
user_tasks[user_id] = task
|
| 189 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
|
| 190 |
+
|
| 191 |
+
def main() -> None:
|
| 192 |
+
token = os.environ.get("BOT_TOKEN")
|
| 193 |
+
if not token:
|
| 194 |
+
logger.error("BOT_TOKEN not set in environment variables!")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
application = (
|
| 198 |
+
Application.builder()
|
| 199 |
+
.token(token)
|
| 200 |
+
.concurrent_updates(True)
|
| 201 |
+
.build()
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# هندلرهای کاربران
|
| 205 |
+
application.add_handler(CommandHandler("start", start))
|
| 206 |
+
application.add_handler(CommandHandler("clear", clear_chat))
|
| 207 |
+
application.add_handler(CommandHandler("context", context_info))
|
| 208 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 209 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 210 |
+
|
| 211 |
+
# راهاندازی و ثبت هندلرهای پنل ادمین
|
| 212 |
+
admin_panel.setup_admin_handlers(application)
|
| 213 |
+
|
| 214 |
+
port = int(os.environ.get("PORT", 8443))
|
| 215 |
+
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
|
| 216 |
+
|
| 217 |
+
application.run_webhook(
|
| 218 |
+
listen="0.0.0.0",
|
| 219 |
+
port=port,
|
| 220 |
+
webhook_url=webhook_url,
|
| 221 |
+
url_path="webhook"
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
main()
|
Version2_Context/render-main/admin_panel.py
ADDED
|
@@ -0,0 +1,961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# --- کتابخانههای جدید برای ویژگیهای اضافه شده ---
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use('Agg') # تنظیم برای استفاده در محیط بدون رابط کاربری گرافیکی
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import tempfile
|
| 20 |
+
import psutil
|
| 21 |
+
import platform
|
| 22 |
+
|
| 23 |
+
# --- تنظیمات ---
|
| 24 |
+
ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
|
| 25 |
+
|
| 26 |
+
# وارد کردن مدیر دادهها
|
| 27 |
+
import data_manager
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# --- دکوراتور برای دسترسی ادمین ---
|
| 32 |
+
|
| 33 |
+
def admin_only(func):
|
| 34 |
+
"""این دکوراتور تضمین میکند که فقط ادمینها بتوانند دستور را اجرا کنند."""
|
| 35 |
+
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
| 36 |
+
if update.effective_user.id not in ADMIN_IDS:
|
| 37 |
+
await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
|
| 38 |
+
return
|
| 39 |
+
return await func(update, context, *args, **kwargs)
|
| 40 |
+
return wrapped
|
| 41 |
+
|
| 42 |
+
# --- هندلرهای دستورات ادمین ---
|
| 43 |
+
|
| 44 |
+
@admin_only
|
| 45 |
+
async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 46 |
+
"""نمایش تمام دستورات موجود ادمین."""
|
| 47 |
+
commands_text = (
|
| 48 |
+
"📋 **دستورات ادمین ربات:**\n\n"
|
| 49 |
+
"📊 `/stats` - نمایش آمار ربات\n"
|
| 50 |
+
"📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
|
| 51 |
+
"🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
|
| 52 |
+
"📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامهریزی شده\n"
|
| 53 |
+
"📋 `/list_scheduled` - نمایش لیست ارسالهای برنامهریزی شده\n"
|
| 54 |
+
"🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامهریزی شده\n"
|
| 55 |
+
"🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
|
| 56 |
+
"✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
|
| 57 |
+
"💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
|
| 58 |
+
"ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
|
| 59 |
+
"📝 `/logs` - نمایش آخرین لاگها\n"
|
| 60 |
+
"📂 `/logs_file` - دانلود فایل کامل لاگها\n"
|
| 61 |
+
"👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
|
| 62 |
+
"🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
|
| 63 |
+
"💾 `/backup` - ایجاد نسخه پشتیبان از دادهها\n"
|
| 64 |
+
"📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
|
| 65 |
+
"🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
|
| 66 |
+
"👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
|
| 67 |
+
"👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
|
| 68 |
+
"📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
|
| 69 |
+
"⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
|
| 70 |
+
"🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
|
| 71 |
+
"✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
|
| 72 |
+
"📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
|
| 73 |
+
"💻 `/system_info` - نمایش اطلاعات سیستم\n"
|
| 74 |
+
"🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
|
| 75 |
+
"🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
|
| 76 |
+
"📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
|
| 77 |
+
"📋 `/commands` - نمایش این لیست دستورات"
|
| 78 |
+
)
|
| 79 |
+
await update.message.reply_text(commands_text, parse_mode='Markdown')
|
| 80 |
+
|
| 81 |
+
@admin_only
|
| 82 |
+
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 83 |
+
"""آمار ربات را نمایش میدهد."""
|
| 84 |
+
total_users = len(data_manager.DATA['users'])
|
| 85 |
+
total_messages = data_manager.DATA['stats']['total_messages']
|
| 86 |
+
banned_count = len(data_manager.DATA['banned_users'])
|
| 87 |
+
|
| 88 |
+
now = datetime.now()
|
| 89 |
+
active_24h = sum(1 for user in data_manager.DATA['users'].values()
|
| 90 |
+
if 'last_seen' in user and
|
| 91 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
|
| 92 |
+
|
| 93 |
+
active_7d = sum(1 for user in data_manager.DATA['users'].values()
|
| 94 |
+
if 'last_seen' in user and
|
| 95 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
|
| 96 |
+
|
| 97 |
+
active_users = sorted(
|
| 98 |
+
data_manager.DATA['users'].items(),
|
| 99 |
+
key=lambda item: item[1].get('last_seen', ''),
|
| 100 |
+
reverse=True
|
| 101 |
+
)[:5]
|
| 102 |
+
|
| 103 |
+
active_users_text = "\n".join(
|
| 104 |
+
[f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
|
| 105 |
+
for user_id, info in active_users]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# آمار context
|
| 109 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values()
|
| 110 |
+
if user.get('context') and len(user['context']) > 0)
|
| 111 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 112 |
+
|
| 113 |
+
text = (
|
| 114 |
+
f"📊 **آمار ربات**\n\n"
|
| 115 |
+
f"👥 **تعداد کل کاربران:** `{total_users}`\n"
|
| 116 |
+
f"📝 **تعداد کل پیامها:** `{total_messages}`\n"
|
| 117 |
+
f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
|
| 118 |
+
f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
|
| 119 |
+
f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
|
| 120 |
+
f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
|
| 121 |
+
f"💬 **کل پیامهای context:** `{total_context_messages}`\n\n"
|
| 122 |
+
f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
|
| 123 |
+
)
|
| 124 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 125 |
+
|
| 126 |
+
@admin_only
|
| 127 |
+
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 128 |
+
"""یک پیام را به تمام کاربران ارسال میکند."""
|
| 129 |
+
if not context.args:
|
| 130 |
+
await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
message_text = " ".join(context.args)
|
| 134 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 135 |
+
total_sent = 0
|
| 136 |
+
total_failed = 0
|
| 137 |
+
|
| 138 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
|
| 139 |
+
|
| 140 |
+
for user_id_str in user_ids:
|
| 141 |
+
try:
|
| 142 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 143 |
+
total_sent += 1
|
| 144 |
+
await asyncio.sleep(0.05)
|
| 145 |
+
except TelegramError as e:
|
| 146 |
+
logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
|
| 147 |
+
total_failed += 1
|
| 148 |
+
|
| 149 |
+
result_text = (
|
| 150 |
+
f"✅ **ارسال همگانی تمام شد**\n\n"
|
| 151 |
+
f"✅ موفق: `{total_sent}`\n"
|
| 152 |
+
f"❌ ناموفق: `{total_failed}`"
|
| 153 |
+
)
|
| 154 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 155 |
+
|
| 156 |
+
@admin_only
|
| 157 |
+
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 158 |
+
"""ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
|
| 159 |
+
if len(context.args) < 3:
|
| 160 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
|
| 161 |
+
"معیارهای موجود: `active_days`, `message_count`, `banned`")
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
criteria = context.args[0].lower()
|
| 165 |
+
value = context.args[1]
|
| 166 |
+
message_text = " ".join(context.args[2:])
|
| 167 |
+
|
| 168 |
+
target_users = []
|
| 169 |
+
|
| 170 |
+
if criteria == "active_days":
|
| 171 |
+
try:
|
| 172 |
+
days = int(value)
|
| 173 |
+
target_users = data_manager.get_active_users(days)
|
| 174 |
+
except ValueError:
|
| 175 |
+
await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
elif criteria == "message_count":
|
| 179 |
+
try:
|
| 180 |
+
min_count = int(value)
|
| 181 |
+
target_users = data_manager.get_users_by_message_count(min_count)
|
| 182 |
+
except ValueError:
|
| 183 |
+
await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
|
| 184 |
+
return
|
| 185 |
+
|
| 186 |
+
elif criteria == "banned":
|
| 187 |
+
if value.lower() == "true":
|
| 188 |
+
target_users = list(data_manager.DATA['banned_users'])
|
| 189 |
+
elif value.lower() == "false":
|
| 190 |
+
for user_id in data_manager.DATA['users']:
|
| 191 |
+
if int(user_id) not in data_manager.DATA['banned_users']:
|
| 192 |
+
target_users.append(int(user_id))
|
| 193 |
+
else:
|
| 194 |
+
await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
else:
|
| 198 |
+
await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
if not target_users:
|
| 202 |
+
await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کا��بر...")
|
| 206 |
+
|
| 207 |
+
total_sent, total_failed = 0, 0
|
| 208 |
+
for user_id in target_users:
|
| 209 |
+
try:
|
| 210 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 211 |
+
total_sent += 1
|
| 212 |
+
await asyncio.sleep(0.05)
|
| 213 |
+
except TelegramError as e:
|
| 214 |
+
logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
|
| 215 |
+
total_failed += 1
|
| 216 |
+
|
| 217 |
+
result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
|
| 218 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 219 |
+
|
| 220 |
+
@admin_only
|
| 221 |
+
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 222 |
+
"""تنظیم ارسال برنامهریزی شده پیام به همه کاربران."""
|
| 223 |
+
if len(context.args) < 3:
|
| 224 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
date_str, time_str = context.args[0], context.args[1]
|
| 229 |
+
message_text = " ".join(context.args[2:])
|
| 230 |
+
|
| 231 |
+
scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
|
| 232 |
+
|
| 233 |
+
if scheduled_time <= datetime.now():
|
| 234 |
+
await update.message.reply_text("⚠️ زمان برنامهریزی شده باید در آینده باشد.")
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
data_manager.DATA['scheduled_broadcasts'].append({
|
| 238 |
+
'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 239 |
+
'message': message_text,
|
| 240 |
+
'status': 'pending'
|
| 241 |
+
})
|
| 242 |
+
data_manager.save_data()
|
| 243 |
+
|
| 244 |
+
await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامهریزی شد.")
|
| 245 |
+
|
| 246 |
+
except ValueError:
|
| 247 |
+
await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
|
| 248 |
+
|
| 249 |
+
@admin_only
|
| 250 |
+
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 251 |
+
"""نمایش لیست ارسالهای برنامهریزی شده."""
|
| 252 |
+
if not data_manager.DATA['scheduled_broadcasts']:
|
| 253 |
+
await update.message.reply_text("هیچ ارسال برنامهریزی شدهای وجود ندارد.")
|
| 254 |
+
return
|
| 255 |
+
|
| 256 |
+
broadcasts_text = "📅 **لیست ارسالهای برنامهریزی شده:**\n\n"
|
| 257 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
|
| 258 |
+
status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
|
| 259 |
+
broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
|
| 260 |
+
|
| 261 |
+
await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
|
| 262 |
+
|
| 263 |
+
@admin_only
|
| 264 |
+
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 265 |
+
"""حذف یک ارسال برنامهریزی شده."""
|
| 266 |
+
if not context.args or not context.args[0].isdigit():
|
| 267 |
+
await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامهریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
index = int(context.args[0]) - 1
|
| 271 |
+
|
| 272 |
+
if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
|
| 273 |
+
await update.message.reply_text("⚠️ شماره ارسال برنامهریزی شده نامعتبر است.")
|
| 274 |
+
return
|
| 275 |
+
|
| 276 |
+
removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
|
| 277 |
+
data_manager.save_data()
|
| 278 |
+
|
| 279 |
+
await update.message.reply_text(f"✅ ارسال برنامهریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
|
| 280 |
+
|
| 281 |
+
@admin_only
|
| 282 |
+
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 283 |
+
"""یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع میدهد."""
|
| 284 |
+
if not context.args or not context.args[0].isdigit():
|
| 285 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
|
| 286 |
+
return
|
| 287 |
+
|
| 288 |
+
user_id_to_ban = int(context.args[0])
|
| 289 |
+
|
| 290 |
+
if user_id_to_ban in ADMIN_IDS:
|
| 291 |
+
await update.message.reply_text("🛡️ شما نمیتوانید یک ادمین را مسدود کنید!")
|
| 292 |
+
return
|
| 293 |
+
|
| 294 |
+
if data_manager.is_user_banned(user_id_to_ban):
|
| 295 |
+
await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
|
| 296 |
+
return
|
| 297 |
+
|
| 298 |
+
data_manager.ban_user(user_id_to_ban)
|
| 299 |
+
|
| 300 |
+
# ارسال پیام به کاربر مسدود شده
|
| 301 |
+
try:
|
| 302 |
+
await context.bot.send_message(
|
| 303 |
+
chat_id=user_id_to_ban,
|
| 304 |
+
text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمیتوانید از خدمات ربات استفاده کنید."
|
| 305 |
+
)
|
| 306 |
+
except TelegramError as e:
|
| 307 |
+
logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
|
| 308 |
+
|
| 309 |
+
await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
|
| 310 |
+
|
| 311 |
+
@admin_only
|
| 312 |
+
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 313 |
+
"""مسدودیت یک کاربر را برمیدارد و به او اطلاع میدهد."""
|
| 314 |
+
if not context.args or not context.args[0].isdigit():
|
| 315 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
user_id_to_unban = int(context.args[0])
|
| 319 |
+
|
| 320 |
+
if not data_manager.is_user_banned(user_id_to_unban):
|
| 321 |
+
await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شدهها وجود ندارد.")
|
| 322 |
+
return
|
| 323 |
+
|
| 324 |
+
data_manager.unban_user(user_id_to_unban)
|
| 325 |
+
|
| 326 |
+
# ارسال پیام به کاربر برای رفع مسدودیت
|
| 327 |
+
try:
|
| 328 |
+
await context.bot.send_message(
|
| 329 |
+
chat_id=user_id_to_unban,
|
| 330 |
+
text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. میتوانید دوباره از ربات استفاده کنید."
|
| 331 |
+
)
|
| 332 |
+
except TelegramError as e:
|
| 333 |
+
logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
|
| 334 |
+
|
| 335 |
+
await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
|
| 336 |
+
|
| 337 |
+
@admin_only
|
| 338 |
+
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 339 |
+
"""ارسال پیام مستقیم به یک کاربر خاص."""
|
| 340 |
+
if len(context.args) < 2:
|
| 341 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
user_id_str = context.args[0]
|
| 345 |
+
if not user_id_str.isdigit():
|
| 346 |
+
await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
|
| 347 |
+
return
|
| 348 |
+
|
| 349 |
+
message_text = " ".join(context.args[1:])
|
| 350 |
+
user_id = int(user_id_str)
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 354 |
+
await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
|
| 355 |
+
except TelegramError as e:
|
| 356 |
+
await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
|
| 357 |
+
|
| 358 |
+
@admin_only
|
| 359 |
+
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 360 |
+
"""اطلاعات یک کاربر خاص را نمایش میدهد."""
|
| 361 |
+
if not context.args or not context.args[0].isdigit():
|
| 362 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
|
| 363 |
+
return
|
| 364 |
+
|
| 365 |
+
user_id = int(context.args[0])
|
| 366 |
+
user_info = data_manager.DATA['users'].get(str(user_id))
|
| 367 |
+
|
| 368 |
+
if not user_info:
|
| 369 |
+
await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
|
| 370 |
+
return
|
| 371 |
+
|
| 372 |
+
is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
|
| 373 |
+
|
| 374 |
+
if 'first_seen' in user_info and 'last_seen' in user_info:
|
| 375 |
+
first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
|
| 376 |
+
last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 377 |
+
days_active = max(1, (last_date - first_date).days)
|
| 378 |
+
avg_messages = user_info.get('message_count', 0) / days_active
|
| 379 |
+
else:
|
| 380 |
+
avg_messages = user_info.get('message_count', 0)
|
| 381 |
+
|
| 382 |
+
# اطلاعات context
|
| 383 |
+
context_messages = len(user_info.get('context', []))
|
| 384 |
+
context_tokens = data_manager.get_context_token_count(user_id)
|
| 385 |
+
|
| 386 |
+
text = (
|
| 387 |
+
f"ℹ️ **اطلاعات کاربر**\n\n"
|
| 388 |
+
f"🆔 **آیدی:** `{user_id}`\n"
|
| 389 |
+
f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
|
| 390 |
+
f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
|
| 391 |
+
f"📊 **تعداد پیامها:** `{user_info.get('message_count', 0)}`\n"
|
| 392 |
+
f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
|
| 393 |
+
f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
|
| 394 |
+
f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
|
| 395 |
+
f"💭 **پیامهای context:** `{context_messages}`\n"
|
| 396 |
+
f"🔢 **توکنهای context:** `{context_tokens}`\n"
|
| 397 |
+
f"🚫 **وضعیت مسدودیت:** {is_banned}"
|
| 398 |
+
)
|
| 399 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 400 |
+
|
| 401 |
+
@admin_only
|
| 402 |
+
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 403 |
+
"""آخرین خطوط لاگ ربات را ارسال میکند."""
|
| 404 |
+
try:
|
| 405 |
+
with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
|
| 406 |
+
lines = f.readlines()
|
| 407 |
+
last_lines = lines[-30:]
|
| 408 |
+
log_text = "".join(last_lines)
|
| 409 |
+
if not log_text:
|
| 410 |
+
await update.message.reply_text("فایل لاگ خالی است.")
|
| 411 |
+
return
|
| 412 |
+
|
| 413 |
+
if len(log_text) > 4096:
|
| 414 |
+
for i in range(0, len(log_text), 4096):
|
| 415 |
+
await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
|
| 416 |
+
else:
|
| 417 |
+
await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
|
| 418 |
+
|
| 419 |
+
except FileNotFoundError:
|
| 420 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 421 |
+
except Exception as e:
|
| 422 |
+
await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
|
| 423 |
+
|
| 424 |
+
@admin_only
|
| 425 |
+
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 426 |
+
"""فایل کامل لاگ ربات را ارسال میکند."""
|
| 427 |
+
try:
|
| 428 |
+
await update.message.reply_document(
|
| 429 |
+
document=open(data_manager.LOG_FILE, 'rb'),
|
| 430 |
+
caption="📂 فایل کامل لاگهای ربات"
|
| 431 |
+
)
|
| 432 |
+
except FileNotFoundError:
|
| 433 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 434 |
+
except Exception as e:
|
| 435 |
+
await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
|
| 436 |
+
|
| 437 |
+
@admin_only
|
| 438 |
+
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 439 |
+
"""نمایش لیست کامل کاربران با صفحهبندی."""
|
| 440 |
+
users = data_manager.DATA['users']
|
| 441 |
+
|
| 442 |
+
page = 1
|
| 443 |
+
if context.args and context.args[0].isdigit():
|
| 444 |
+
page = int(context.args[0])
|
| 445 |
+
if page < 1: page = 1
|
| 446 |
+
|
| 447 |
+
users_per_page = 20
|
| 448 |
+
total_users = len(users)
|
| 449 |
+
total_pages = (total_users + users_per_page - 1) // users_per_page
|
| 450 |
+
|
| 451 |
+
if page > total_pages: page = total_pages
|
| 452 |
+
|
| 453 |
+
start_idx = (page - 1) * users_per_page
|
| 454 |
+
end_idx = min(start_idx + users_per_page, total_users)
|
| 455 |
+
|
| 456 |
+
sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
|
| 457 |
+
|
| 458 |
+
users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
|
| 459 |
+
|
| 460 |
+
for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
|
| 461 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 462 |
+
username = user_info.get('username', 'N/A')
|
| 463 |
+
first_name = user_info.get('first_name', 'N/A')
|
| 464 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 465 |
+
message_count = user_info.get('message_count', 0)
|
| 466 |
+
context_count = len(user_info.get('context', []))
|
| 467 |
+
|
| 468 |
+
users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
|
| 469 |
+
users_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 470 |
+
users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 471 |
+
|
| 472 |
+
keyboard = []
|
| 473 |
+
if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
|
| 474 |
+
if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
|
| 475 |
+
|
| 476 |
+
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
|
| 477 |
+
await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
|
| 478 |
+
|
| 479 |
+
@admin_only
|
| 480 |
+
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 481 |
+
"""جستجوی کاربر بر اساس نام یا نام کاربری."""
|
| 482 |
+
if not context.args:
|
| 483 |
+
await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
|
| 484 |
+
return
|
| 485 |
+
|
| 486 |
+
search_term = " ".join(context.args).lower()
|
| 487 |
+
users = data_manager.DATA['users']
|
| 488 |
+
|
| 489 |
+
matching_users = []
|
| 490 |
+
for user_id, user_info in users.items():
|
| 491 |
+
# استفاده از (value or '') برای جلوگیری از خطا در صورت وجود None
|
| 492 |
+
first_name = (user_info.get('first_name') or '').lower()
|
| 493 |
+
username = (user_info.get('username') or '').lower()
|
| 494 |
+
|
| 495 |
+
if search_term in first_name or search_term in username:
|
| 496 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 497 |
+
matching_users.append((user_id, user_info, is_banned))
|
| 498 |
+
|
| 499 |
+
if not matching_users:
|
| 500 |
+
await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
|
| 501 |
+
return
|
| 502 |
+
|
| 503 |
+
results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
|
| 504 |
+
|
| 505 |
+
for user_id, user_info, is_banned in matching_users:
|
| 506 |
+
username_display = user_info.get('username', 'N/A')
|
| 507 |
+
first_name_display = user_info.get('first_name', 'N/A')
|
| 508 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 509 |
+
message_count = user_info.get('message_count', 0)
|
| 510 |
+
context_count = len(user_info.get('context', []))
|
| 511 |
+
|
| 512 |
+
results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
|
| 513 |
+
results_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 514 |
+
results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 515 |
+
|
| 516 |
+
await update.message.reply_text(results_text, parse_mode='Markdown')
|
| 517 |
+
|
| 518 |
+
@admin_only
|
| 519 |
+
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 520 |
+
"""ایجاد نسخه پشتیبان از دادههای ربات."""
|
| 521 |
+
try:
|
| 522 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 523 |
+
backup_file = f"bot_backup_{timestamp}.json"
|
| 524 |
+
|
| 525 |
+
data_to_backup = data_manager.DATA.copy()
|
| 526 |
+
data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
|
| 527 |
+
|
| 528 |
+
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 529 |
+
json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
|
| 530 |
+
|
| 531 |
+
await update.message.reply_document(
|
| 532 |
+
document=open(backup_file, 'rb'),
|
| 533 |
+
caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
logger.info(f"Backup created: {backup_file}")
|
| 537 |
+
os.remove(backup_file) # حذف فایل پس از ارسال
|
| 538 |
+
except Exception as e:
|
| 539 |
+
await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
|
| 540 |
+
logger.error(f"Error creating backup: {e}")
|
| 541 |
+
|
| 542 |
+
@admin_only
|
| 543 |
+
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 544 |
+
"""ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
|
| 545 |
+
users = data_manager.DATA['users']
|
| 546 |
+
|
| 547 |
+
df_data = []
|
| 548 |
+
for user_id, user_info in users.items():
|
| 549 |
+
is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
|
| 550 |
+
context_count = len(user_info.get('context', []))
|
| 551 |
+
context_tokens = data_manager.get_context_token_count(int(user_id))
|
| 552 |
+
|
| 553 |
+
df_data.append({
|
| 554 |
+
'User ID': user_id,
|
| 555 |
+
'First Name': user_info.get('first_name', 'N/A'),
|
| 556 |
+
'Username': user_info.get('username', 'N/A'),
|
| 557 |
+
'Message Count': user_info.get('message_count', 0),
|
| 558 |
+
'Context Messages': context_count,
|
| 559 |
+
'Context Tokens': context_tokens,
|
| 560 |
+
'First Seen': user_info.get('first_seen', 'N/A'),
|
| 561 |
+
'Last Seen': user_info.get('last_seen', 'N/A'),
|
| 562 |
+
'Banned': is_banned
|
| 563 |
+
})
|
| 564 |
+
|
| 565 |
+
df = pd.DataFrame(df_data)
|
| 566 |
+
|
| 567 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
|
| 568 |
+
df.to_csv(f.name, index=False)
|
| 569 |
+
temp_file_path = f.name
|
| 570 |
+
|
| 571 |
+
await update.message.reply_document(
|
| 572 |
+
document=open(temp_file_path, 'rb'),
|
| 573 |
+
caption="📊 فایل CSV اطلاعات کاربران"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
os.unlink(temp_file_path)
|
| 577 |
+
|
| 578 |
+
@admin_only
|
| 579 |
+
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 580 |
+
"""حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع میدهد."""
|
| 581 |
+
if not context.args or context.args[0].lower() not in ['on', 'off']:
|
| 582 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
|
| 583 |
+
return
|
| 584 |
+
|
| 585 |
+
status = context.args[0].lower()
|
| 586 |
+
|
| 587 |
+
if status == 'on':
|
| 588 |
+
if data_manager.DATA.get('maintenance_mode', False):
|
| 589 |
+
await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
|
| 590 |
+
return
|
| 591 |
+
|
| 592 |
+
data_manager.DATA['maintenance_mode'] = True
|
| 593 |
+
data_manager.save_data()
|
| 594 |
+
|
| 595 |
+
await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاعرسانی به کاربران...")
|
| 596 |
+
|
| 597 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 598 |
+
for user_id_str in user_ids:
|
| 599 |
+
try:
|
| 600 |
+
# به ادمینها پیام ارسال نشود
|
| 601 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 602 |
+
await context.bot.send_message(
|
| 603 |
+
chat_id=int(user_id_str),
|
| 604 |
+
text="🔧 ربات در حال حاضر در حالت بهروزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
|
| 605 |
+
)
|
| 606 |
+
await asyncio.sleep(0.05) # جلوگیری از محدودیت تلگرام
|
| 607 |
+
except TelegramError:
|
| 608 |
+
continue # نادیده گرفتن کاربرانی که ربات را مسدود کردهاند
|
| 609 |
+
|
| 610 |
+
elif status == 'off':
|
| 611 |
+
if not data_manager.DATA.get('maintenance_mode', False):
|
| 612 |
+
await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
|
| 613 |
+
return
|
| 614 |
+
|
| 615 |
+
data_manager.DATA['maintenance_mode'] = False
|
| 616 |
+
data_manager.save_data()
|
| 617 |
+
|
| 618 |
+
await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاعرسانی به کاربران...")
|
| 619 |
+
|
| 620 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 621 |
+
for user_id_str in user_ids:
|
| 622 |
+
try:
|
| 623 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 624 |
+
await context.bot.send_message(
|
| 625 |
+
chat_id=int(user_id_str),
|
| 626 |
+
text="✅ بهروزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! میتوانید دوباره از ربات استفاده کنید."
|
| 627 |
+
)
|
| 628 |
+
await asyncio.sleep(0.05)
|
| 629 |
+
except TelegramError:
|
| 630 |
+
continue
|
| 631 |
+
|
| 632 |
+
@admin_only
|
| 633 |
+
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 634 |
+
"""تنظیم پیام خوشامدگویی جدید."""
|
| 635 |
+
if not context.args:
|
| 636 |
+
await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
|
| 637 |
+
"مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
|
| 638 |
+
return
|
| 639 |
+
|
| 640 |
+
new_message = " ".join(context.args)
|
| 641 |
+
data_manager.DATA['welcome_message'] = new_message
|
| 642 |
+
data_manager.save_data()
|
| 643 |
+
|
| 644 |
+
await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت بهروزرسانی شد.")
|
| 645 |
+
|
| 646 |
+
@admin_only
|
| 647 |
+
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 648 |
+
"""تنظیم پیام خداحافظی جدید."""
|
| 649 |
+
if not context.args:
|
| 650 |
+
await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
|
| 651 |
+
"مثال: `/set_goodbye {user_mention}، خداحافظ!`")
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
new_message = " ".join(context.args)
|
| 655 |
+
data_manager.DATA['goodbye_message'] = new_message
|
| 656 |
+
data_manager.save_data()
|
| 657 |
+
|
| 658 |
+
await update.message.reply_text("✅ پیام خداحافظی با موفقیت بهروزرسانی شد.")
|
| 659 |
+
|
| 660 |
+
@admin_only
|
| 661 |
+
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 662 |
+
"""ایجاد و ارسال نمودار فعالیت کاربران."""
|
| 663 |
+
users = data_manager.DATA['users']
|
| 664 |
+
activity_hours = [0] * 24
|
| 665 |
+
|
| 666 |
+
for user_info in users.values():
|
| 667 |
+
if 'last_seen' in user_info:
|
| 668 |
+
try:
|
| 669 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 670 |
+
activity_hours[last_seen.hour] += 1
|
| 671 |
+
except ValueError:
|
| 672 |
+
continue
|
| 673 |
+
|
| 674 |
+
plt.figure(figsize=(12, 6))
|
| 675 |
+
plt.bar(range(24), activity_hours, color='skyblue')
|
| 676 |
+
plt.title('نمودار فعالیت کاربران بر اساس ساعت')
|
| 677 |
+
plt.xlabel('ساعت')
|
| 678 |
+
plt.ylabel('تعداد کاربران فعال')
|
| 679 |
+
plt.xticks(range(24))
|
| 680 |
+
plt.grid(axis='y', alpha=0.3)
|
| 681 |
+
|
| 682 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
|
| 683 |
+
plt.savefig(f.name, bbox_inches='tight')
|
| 684 |
+
temp_file_path = f.name
|
| 685 |
+
|
| 686 |
+
plt.close()
|
| 687 |
+
|
| 688 |
+
await update.message.reply_photo(
|
| 689 |
+
photo=open(temp_file_path, 'rb'),
|
| 690 |
+
caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
os.unlink(temp_file_path)
|
| 694 |
+
|
| 695 |
+
@admin_only
|
| 696 |
+
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 697 |
+
"""نمایش آمار زمان پاسخگویی ربات."""
|
| 698 |
+
stats = data_manager.DATA['stats']
|
| 699 |
+
await update.message.reply_text(
|
| 700 |
+
"📈 **آمار زمان پاسخگویی ربات**\n\n"
|
| 701 |
+
f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
|
| 702 |
+
f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
|
| 703 |
+
f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
|
| 704 |
+
f"📊 کل پاسخهای ثبت شده: `{stats.get('total_responses', 0)}`"
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
@admin_only
|
| 708 |
+
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 709 |
+
"""افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
|
| 710 |
+
if not context.args:
|
| 711 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 712 |
+
"مثال: `/add_blocked_word کلمه_نامناسب`")
|
| 713 |
+
return
|
| 714 |
+
|
| 715 |
+
word = " ".join(context.args).lower()
|
| 716 |
+
|
| 717 |
+
if word in data_manager.DATA['blocked_words']:
|
| 718 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
|
| 719 |
+
return
|
| 720 |
+
|
| 721 |
+
data_manager.DATA['blocked_words'].append(word)
|
| 722 |
+
data_manager.save_data()
|
| 723 |
+
|
| 724 |
+
await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
|
| 725 |
+
|
| 726 |
+
@admin_only
|
| 727 |
+
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 728 |
+
"""حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
|
| 729 |
+
if not context.args:
|
| 730 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 731 |
+
"مثال: `/remove_blocked_word کلمه_نامناسب`")
|
| 732 |
+
return
|
| 733 |
+
|
| 734 |
+
word = " ".join(context.args).lower()
|
| 735 |
+
|
| 736 |
+
if word not in data_manager.DATA['blocked_words']:
|
| 737 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
|
| 738 |
+
return
|
| 739 |
+
|
| 740 |
+
data_manager.DATA['blocked_words'].remove(word)
|
| 741 |
+
data_manager.save_data()
|
| 742 |
+
|
| 743 |
+
await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
|
| 744 |
+
|
| 745 |
+
@admin_only
|
| 746 |
+
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 747 |
+
"""نمایش لیست کلمات مسدود شده."""
|
| 748 |
+
if not data_manager.DATA['blocked_words']:
|
| 749 |
+
await update.message.reply_text("هیچ کلمه مسدود شدهای در لیست وجود ندارد.")
|
| 750 |
+
return
|
| 751 |
+
|
| 752 |
+
words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
|
| 753 |
+
await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
|
| 754 |
+
|
| 755 |
+
@admin_only
|
| 756 |
+
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 757 |
+
"""نمایش اطلاعات سیستم و منابع."""
|
| 758 |
+
bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
|
| 759 |
+
bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
|
| 760 |
+
uptime = datetime.now() - bot_start_time
|
| 761 |
+
|
| 762 |
+
# محاسبه آمار context
|
| 763 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 764 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
|
| 765 |
+
|
| 766 |
+
system_info = (
|
| 767 |
+
f"💻 **اطلاعات سیستم:**\n\n"
|
| 768 |
+
f"🖥️ سیستمعامل: {platform.system()} {platform.release()}\n"
|
| 769 |
+
f"🐍 نسخه پایتون: {platform.python_version()}\n"
|
| 770 |
+
f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
|
| 771 |
+
f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
|
| 772 |
+
f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
|
| 773 |
+
f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
|
| 774 |
+
f"⏱️ زمان اجرای ربات: {uptime}\n"
|
| 775 |
+
f"💭 کاربران با context: {users_with_context}\n"
|
| 776 |
+
f"💬 کل پیامهای context: {total_context_messages}"
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
await update.message.reply_text(system_info, parse_mode='Markdown')
|
| 780 |
+
|
| 781 |
+
@admin_only
|
| 782 |
+
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 783 |
+
"""ریست کردن آمار ربات."""
|
| 784 |
+
if not context.args:
|
| 785 |
+
await update.message.reply_text("⚠️ لطفاً نوع آماری که میخواهید ریست کنید را مشخص کنید.\n"
|
| 786 |
+
"مثال: `/reset_stats messages` یا `/reset_stats all`")
|
| 787 |
+
return
|
| 788 |
+
|
| 789 |
+
stat_type = context.args[0].lower()
|
| 790 |
+
|
| 791 |
+
if stat_type == "messages":
|
| 792 |
+
data_manager.DATA['stats']['total_messages'] = 0
|
| 793 |
+
for user_id in data_manager.DATA['users']:
|
| 794 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 795 |
+
await update.message.reply_text("✅ آمار پیامها با موفقیت ریست شد.")
|
| 796 |
+
|
| 797 |
+
elif stat_type == "all":
|
| 798 |
+
data_manager.DATA['stats'] = {
|
| 799 |
+
'total_messages': 0,
|
| 800 |
+
'total_users': len(data_manager.DATA['users']),
|
| 801 |
+
'avg_response_time': 0,
|
| 802 |
+
'max_response_time': 0,
|
| 803 |
+
'min_response_time': 0,
|
| 804 |
+
'total_responses': 0
|
| 805 |
+
}
|
| 806 |
+
for user_id in data_manager.DATA['users']:
|
| 807 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 808 |
+
await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
|
| 809 |
+
|
| 810 |
+
else:
|
| 811 |
+
await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینههای موجود: messages, all")
|
| 812 |
+
return
|
| 813 |
+
|
| 814 |
+
data_manager.save_data()
|
| 815 |
+
|
| 816 |
+
# --- دستورات جدید برای مدیریت context ---
|
| 817 |
+
|
| 818 |
+
@admin_only
|
| 819 |
+
async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 820 |
+
"""پاک کردن context یک کاربر"""
|
| 821 |
+
if not context.args or not context.args[0].isdigit():
|
| 822 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
|
| 823 |
+
return
|
| 824 |
+
|
| 825 |
+
user_id = int(context.args[0])
|
| 826 |
+
data_manager.clear_user_context(user_id)
|
| 827 |
+
|
| 828 |
+
await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
|
| 829 |
+
|
| 830 |
+
@admin_only
|
| 831 |
+
async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 832 |
+
"""مشاهده context یک کاربر"""
|
| 833 |
+
if not context.args or not context.args[0].isdigit():
|
| 834 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
|
| 835 |
+
return
|
| 836 |
+
|
| 837 |
+
user_id = int(context.args[0])
|
| 838 |
+
user_context = data_manager.get_user_context(user_id)
|
| 839 |
+
|
| 840 |
+
if not user_context:
|
| 841 |
+
await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
|
| 842 |
+
return
|
| 843 |
+
|
| 844 |
+
context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
|
| 845 |
+
total_tokens = 0
|
| 846 |
+
|
| 847 |
+
for i, msg in enumerate(user_context, 1):
|
| 848 |
+
role_emoji = "👤" if msg['role'] == 'user' else "🤖"
|
| 849 |
+
tokens = data_manager.count_tokens(msg['content'])
|
| 850 |
+
total_tokens += tokens
|
| 851 |
+
|
| 852 |
+
# کوتاه کردن متن طولانی
|
| 853 |
+
content_preview = msg['content']
|
| 854 |
+
if len(content_preview) > 100:
|
| 855 |
+
content_preview = content_preview[:100] + "..."
|
| 856 |
+
|
| 857 |
+
context_text += f"{i}. {role_emoji} **{msg['role']}** ({tokens} توکن)\n"
|
| 858 |
+
context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
|
| 859 |
+
context_text += f" 📝 {content_preview}\n\n"
|
| 860 |
+
|
| 861 |
+
context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن"
|
| 862 |
+
|
| 863 |
+
await update.message.reply_text(context_text, parse_mode='Markdown')
|
| 864 |
+
|
| 865 |
+
# --- هندلر برای دکمههای صفحهبندی ---
|
| 866 |
+
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 867 |
+
"""پردازش دکمههای صفحهبندی لیست کاربران."""
|
| 868 |
+
query = update.callback_query
|
| 869 |
+
await query.answer()
|
| 870 |
+
|
| 871 |
+
if query.data.startswith("users_list:"):
|
| 872 |
+
page = int(query.data.split(":")[1])
|
| 873 |
+
context.args = [str(page)]
|
| 874 |
+
await admin_users_list(update, context)
|
| 875 |
+
|
| 876 |
+
# --- تابع برای پردازش ارسالهای برنامهریزی شده ---
|
| 877 |
+
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
|
| 878 |
+
"""پردازش ارسالهای برنامهریزی شده و ارسال پیامها در زمان مقرر."""
|
| 879 |
+
now = datetime.now()
|
| 880 |
+
broadcasts_to_send_indices = []
|
| 881 |
+
|
| 882 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
|
| 883 |
+
if broadcast['status'] == 'pending':
|
| 884 |
+
broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
|
| 885 |
+
if broadcast_time <= now:
|
| 886 |
+
broadcasts_to_send_indices.append(i)
|
| 887 |
+
|
| 888 |
+
if not broadcasts_to_send_indices:
|
| 889 |
+
return
|
| 890 |
+
|
| 891 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 892 |
+
|
| 893 |
+
for index in broadcasts_to_send_indices:
|
| 894 |
+
broadcast = data_manager.DATA['scheduled_broadcasts'][index]
|
| 895 |
+
message_text = broadcast['message']
|
| 896 |
+
total_sent, total_failed = 0, 0
|
| 897 |
+
|
| 898 |
+
for user_id_str in user_ids:
|
| 899 |
+
try:
|
| 900 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 901 |
+
total_sent += 1
|
| 902 |
+
await asyncio.sleep(0.05)
|
| 903 |
+
except TelegramError as e:
|
| 904 |
+
logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
|
| 905 |
+
total_failed += 1
|
| 906 |
+
|
| 907 |
+
# بهروزرسانی وضعیت ارسال
|
| 908 |
+
data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
|
| 909 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
|
| 910 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
|
| 911 |
+
data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
|
| 912 |
+
|
| 913 |
+
logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
|
| 914 |
+
|
| 915 |
+
data_manager.save_data()
|
| 916 |
+
|
| 917 |
+
# --- تابع راهاندازی هندلرها ---
|
| 918 |
+
def setup_admin_handlers(application):
|
| 919 |
+
"""هندلرهای پنل ادمین را به اپلیکیشن اضافه میکند."""
|
| 920 |
+
# هندلرهای اصلی
|
| 921 |
+
application.add_handler(CommandHandler("commands", admin_commands))
|
| 922 |
+
application.add_handler(CommandHandler("stats", admin_stats))
|
| 923 |
+
application.add_handler(CommandHandler("broadcast", admin_broadcast))
|
| 924 |
+
application.add_handler(CommandHandler("ban", admin_ban))
|
| 925 |
+
application.add_handler(CommandHandler("unban", admin_unban))
|
| 926 |
+
application.add_handler(CommandHandler("user_info", admin_userinfo))
|
| 927 |
+
application.add_handler(CommandHandler("logs", admin_logs))
|
| 928 |
+
application.add_handler(CommandHandler("logs_file", admin_logs_file))
|
| 929 |
+
application.add_handler(CommandHandler("users_list", admin_users_list))
|
| 930 |
+
application.add_handler(CommandHandler("user_search", admin_user_search))
|
| 931 |
+
application.add_handler(CommandHandler("backup", admin_backup))
|
| 932 |
+
|
| 933 |
+
# هندلرهای جدید
|
| 934 |
+
application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
|
| 935 |
+
application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
|
| 936 |
+
application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
|
| 937 |
+
application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
|
| 938 |
+
application.add_handler(CommandHandler("direct_message", admin_direct_message))
|
| 939 |
+
application.add_handler(CommandHandler("export_csv", admin_export_csv))
|
| 940 |
+
application.add_handler(CommandHandler("maintenance", admin_maintenance))
|
| 941 |
+
application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
|
| 942 |
+
application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
|
| 943 |
+
application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
|
| 944 |
+
application.add_handler(CommandHandler("response_stats", admin_response_stats))
|
| 945 |
+
application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
|
| 946 |
+
application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
|
| 947 |
+
application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
|
| 948 |
+
application.add_handler(CommandHandler("system_info", admin_system_info))
|
| 949 |
+
application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
|
| 950 |
+
|
| 951 |
+
# هندلرهای مدیریت context
|
| 952 |
+
application.add_handler(CommandHandler("clear_context", admin_clear_context))
|
| 953 |
+
application.add_handler(CommandHandler("view_context", admin_view_context))
|
| 954 |
+
|
| 955 |
+
# هندلر برای دکمههای صفحهبندی
|
| 956 |
+
application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
|
| 957 |
+
|
| 958 |
+
# شروع وظیفه دورهای برای بررسی ارسالهای برنامهریزی شده
|
| 959 |
+
application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
|
| 960 |
+
|
| 961 |
+
logger.info("Admin panel handlers have been set up.")
|
Version2_Context/render-main/data_manager.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|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elta
|
| 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 |
+
"banned_users": set(),
|
| 18 |
+
"stats": {
|
| 19 |
+
"total_messages": 0,
|
| 20 |
+
"total_users": 0,
|
| 21 |
+
"avg_response_time": 0.0,
|
| 22 |
+
"max_response_time": 0.0,
|
| 23 |
+
"min_response_time": float('inf'),
|
| 24 |
+
"total_responses": 0
|
| 25 |
+
},
|
| 26 |
+
"welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
|
| 27 |
+
"goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
|
| 28 |
+
"maintenance_mode": False,
|
| 29 |
+
"blocked_words": [],
|
| 30 |
+
"scheduled_broadcasts": [],
|
| 31 |
+
"bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
# تابع برای شمارش توکنها
|
| 37 |
+
def count_tokens(text: str) -> int:
|
| 38 |
+
"""شمارش تعداد توکنهای متن با استفاده از tokenizer"""
|
| 39 |
+
try:
|
| 40 |
+
# استفاده از tokenizer برای gpt-3.5-turbo
|
| 41 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 42 |
+
return len(encoding.encode(text))
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.warning(f"Error counting tokens: {e}, using fallback")
|
| 45 |
+
# تقریب: هر 4 کاراکتر = 1 توکن
|
| 46 |
+
return max(1, len(text) // 4)
|
| 47 |
+
|
| 48 |
+
def load_data():
|
| 49 |
+
"""دادهها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره میکند."""
|
| 50 |
+
global DATA
|
| 51 |
+
try:
|
| 52 |
+
if not os.path.exists(DATA_FILE):
|
| 53 |
+
logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد میشود.")
|
| 54 |
+
save_data()
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
| 58 |
+
loaded_data = json.load(f)
|
| 59 |
+
loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
|
| 60 |
+
|
| 61 |
+
# اطمینان از وجود کلیدهای جدید در فایلهای قدیمی
|
| 62 |
+
if 'blocked_words' not in loaded_data: loaded_data['blocked_words'] = []
|
| 63 |
+
if 'scheduled_broadcasts' not in loaded_data: loaded_data['scheduled_broadcasts'] = []
|
| 64 |
+
if 'maintenance_mode' not in loaded_data: loaded_data['maintenance_mode'] = False
|
| 65 |
+
if 'bot_start_time' not in loaded_data: loaded_data['bot_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 66 |
+
if 'avg_response_time' not in loaded_data['stats']:
|
| 67 |
+
loaded_data['stats']['avg_response_time'] = 0.0
|
| 68 |
+
loaded_data['stats']['max_response_time'] = 0.0
|
| 69 |
+
loaded_data['stats']['min_response_time'] = float('inf')
|
| 70 |
+
loaded_data['stats']['total_responses'] = 0
|
| 71 |
+
|
| 72 |
+
# اطمینان از وجود context برای کاربران قدیمی
|
| 73 |
+
for user_id in loaded_data.get('users', {}):
|
| 74 |
+
if 'context' not in loaded_data['users'][user_id]:
|
| 75 |
+
loaded_data['users'][user_id]['context'] = []
|
| 76 |
+
|
| 77 |
+
DATA.update(loaded_data)
|
| 78 |
+
logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.")
|
| 79 |
+
|
| 80 |
+
except json.JSONDecodeError as e:
|
| 81 |
+
logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 84 |
+
|
| 85 |
+
def save_data():
|
| 86 |
+
"""کش گلوبال دادهها را در فایل JSON ذخیره میکند."""
|
| 87 |
+
global DATA
|
| 88 |
+
try:
|
| 89 |
+
data_to_save = DATA.copy()
|
| 90 |
+
data_to_save['banned_users'] = list(DATA['banned_users'])
|
| 91 |
+
|
| 92 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 93 |
+
json.dump(data_to_save, f, indent=4, ensure_ascii=False)
|
| 94 |
+
logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.")
|
| 95 |
+
except Exception as e:
|
| 96 |
+
logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}")
|
| 97 |
+
|
| 98 |
+
def update_user_stats(user_id: int, user):
|
| 99 |
+
"""آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند."""
|
| 100 |
+
global DATA
|
| 101 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 102 |
+
user_id_str = str(user_id)
|
| 103 |
+
|
| 104 |
+
if user_id_str not in DATA['users']:
|
| 105 |
+
DATA['users'][user_id_str] = {
|
| 106 |
+
'first_name': user.first_name,
|
| 107 |
+
'username': user.username,
|
| 108 |
+
'first_seen': now_str,
|
| 109 |
+
'message_count': 0,
|
| 110 |
+
'context': [] # اضافه کردن context خالی برای کاربر جدید
|
| 111 |
+
}
|
| 112 |
+
DATA['stats']['total_users'] += 1
|
| 113 |
+
logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
|
| 114 |
+
|
| 115 |
+
DATA['users'][user_id_str]['last_seen'] = now_str
|
| 116 |
+
DATA['users'][user_id_str]['message_count'] += 1
|
| 117 |
+
DATA['stats']['total_messages'] += 1
|
| 118 |
+
|
| 119 |
+
save_data()
|
| 120 |
+
|
| 121 |
+
def update_response_stats(response_time: float):
|
| 122 |
+
"""آمار زمان پاسخگویی را بهروز میکند."""
|
| 123 |
+
global DATA
|
| 124 |
+
|
| 125 |
+
if DATA['stats']['total_responses'] == 0:
|
| 126 |
+
DATA['stats']['min_response_time'] = response_time
|
| 127 |
+
|
| 128 |
+
DATA['stats']['total_responses'] += 1
|
| 129 |
+
|
| 130 |
+
# محاسبه میانگین جدید
|
| 131 |
+
current_avg = DATA['stats']['avg_response_time']
|
| 132 |
+
total_responses = DATA['stats']['total_responses']
|
| 133 |
+
new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
|
| 134 |
+
DATA['stats']['avg_response_time'] = new_avg
|
| 135 |
+
|
| 136 |
+
# بهروزرسانی حداکثر و حداقل زمان پاسخگویی
|
| 137 |
+
if response_time > DATA['stats']['max_response_time']:
|
| 138 |
+
DATA['stats']['max_response_time'] = response_time
|
| 139 |
+
|
| 140 |
+
if response_time < DATA['stats']['min_response_time']:
|
| 141 |
+
DATA['stats']['min_response_time'] = response_time
|
| 142 |
+
|
| 143 |
+
save_data()
|
| 144 |
+
|
| 145 |
+
def is_user_banned(user_id: int) -> bool:
|
| 146 |
+
"""بررسی میکند آیا کاربر مسدود شده است یا خیر."""
|
| 147 |
+
return user_id in DATA['banned_users']
|
| 148 |
+
|
| 149 |
+
def ban_user(user_id: int):
|
| 150 |
+
"""کاربر را مسدود کرده و ذخیره میکند."""
|
| 151 |
+
DATA['banned_users'].add(user_id)
|
| 152 |
+
save_data()
|
| 153 |
+
|
| 154 |
+
def unban_user(user_id: int):
|
| 155 |
+
"""مسدودیت کاربر را برداشته و ذخیره میکند."""
|
| 156 |
+
DATA['banned_users'].discard(user_id)
|
| 157 |
+
save_data()
|
| 158 |
+
|
| 159 |
+
def contains_blocked_words(text: str) -> bool:
|
| 160 |
+
"""بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر."""
|
| 161 |
+
if not DATA['blocked_words']:
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
text_lower = text.lower()
|
| 165 |
+
for word in DATA['blocked_words']:
|
| 166 |
+
if word in text_lower:
|
| 167 |
+
return True
|
| 168 |
+
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
def get_active_users(days: int) -> list:
|
| 172 |
+
"""لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند."""
|
| 173 |
+
now = datetime.now()
|
| 174 |
+
cutoff_date = now - timedelta(days=days)
|
| 175 |
+
|
| 176 |
+
active_users = []
|
| 177 |
+
for user_id, user_info in DATA['users'].items():
|
| 178 |
+
if 'last_seen' in user_info:
|
| 179 |
+
try:
|
| 180 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 181 |
+
if last_seen >= cutoff_date:
|
| 182 |
+
active_users.append(int(user_id))
|
| 183 |
+
except ValueError:
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
return active_users
|
| 187 |
+
|
| 188 |
+
def get_users_by_message_count(min_count: int) -> list:
|
| 189 |
+
"""لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند."""
|
| 190 |
+
users = []
|
| 191 |
+
for user_id, user_info in DATA['users'].items():
|
| 192 |
+
if user_info.get('message_count', 0) >= min_count:
|
| 193 |
+
users.append(int(user_id))
|
| 194 |
+
|
| 195 |
+
return users
|
| 196 |
+
|
| 197 |
+
# --- توابع مدیریت context ---
|
| 198 |
+
|
| 199 |
+
def add_to_user_context(user_id: int, role: str, content: str):
|
| 200 |
+
"""اضافه کردن پیام به context کاربر و محدود کردن به 512 توکن"""
|
| 201 |
+
user_id_str = str(user_id)
|
| 202 |
+
|
| 203 |
+
if user_id_str not in DATA['users']:
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
if 'context' not in DATA['users'][user_id_str]:
|
| 207 |
+
DATA['users'][user_id_str]['context'] = []
|
| 208 |
+
|
| 209 |
+
# اضافه کردن پیام جدید
|
| 210 |
+
message = {
|
| 211 |
+
'role': role, # 'user' یا 'assistant'
|
| 212 |
+
'content': content,
|
| 213 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
DATA['users'][user_id_str]['context'].append(message)
|
| 217 |
+
|
| 218 |
+
# محدود کردن context به 512 توکن
|
| 219 |
+
trim_user_context(user_id)
|
| 220 |
+
|
| 221 |
+
save_data()
|
| 222 |
+
|
| 223 |
+
def trim_user_context(user_id: int, max_tokens: int = 1024):
|
| 224 |
+
"""کوتاه کردن context کاربر به تعداد توکن مشخص"""
|
| 225 |
+
user_id_str = str(user_id)
|
| 226 |
+
|
| 227 |
+
if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
|
| 228 |
+
return
|
| 229 |
+
|
| 230 |
+
context = DATA['users'][user_id_str]['context']
|
| 231 |
+
|
| 232 |
+
if not context:
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
# محاسبه توکنهای کل
|
| 236 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 237 |
+
|
| 238 |
+
# حذف قدیمیترین پیامها تا زمانی که توکنها زیر حد مجاز باشد
|
| 239 |
+
while total_tokens > max_tokens and len(context) > 1:
|
| 240 |
+
removed_message = context.pop(0) # حذف قدیمیترین پیام
|
| 241 |
+
total_tokens -= count_tokens(removed_message['content'])
|
| 242 |
+
|
| 243 |
+
# اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن
|
| 244 |
+
if total_tokens > max_tokens and context:
|
| 245 |
+
# از آخرین پیام (جدیدترین) شروع به کوتاه کردن کن
|
| 246 |
+
last_message = context[-1]
|
| 247 |
+
content = last_message['content']
|
| 248 |
+
|
| 249 |
+
# کوتاه کردن محتوا
|
| 250 |
+
tokens = count_tokens(content)
|
| 251 |
+
if tokens > max_tokens:
|
| 252 |
+
# اگر یک پیام به تنهایی بیشتر از حد مجاز باشد، آن را حذف کن
|
| 253 |
+
context.pop()
|
| 254 |
+
else:
|
| 255 |
+
# در غیر این صورت، محتوای پیام را کوتاه کن
|
| 256 |
+
while tokens > (max_tokens - (total_tokens - tokens)) and content:
|
| 257 |
+
# حذف کلمات از انتها
|
| 258 |
+
words = content.split()
|
| 259 |
+
if len(words) > 1:
|
| 260 |
+
content = ' '.join(words[:-1])
|
| 261 |
+
else:
|
| 262 |
+
content = content[:-1] if len(content) > 1 else ''
|
| 263 |
+
tokens = count_tokens(content)
|
| 264 |
+
|
| 265 |
+
if content: # اگر محتوایی باقی مانده
|
| 266 |
+
context[-1]['content'] = content
|
| 267 |
+
else: # اگر تمام محتوا حذف شد
|
| 268 |
+
context.pop()
|
| 269 |
+
|
| 270 |
+
save_data()
|
| 271 |
+
|
| 272 |
+
def get_user_context(user_id: int) -> list:
|
| 273 |
+
"""دریافت context کاربر"""
|
| 274 |
+
user_id_str = str(user_id)
|
| 275 |
+
|
| 276 |
+
if user_id_str not in DATA['users']:
|
| 277 |
+
return []
|
| 278 |
+
|
| 279 |
+
return DATA['users'][user_id_str].get('context', [])
|
| 280 |
+
|
| 281 |
+
def clear_user_context(user_id: int):
|
| 282 |
+
"""پاک کردن context کاربر"""
|
| 283 |
+
user_id_str = str(user_id)
|
| 284 |
+
|
| 285 |
+
if user_id_str in DATA['users']:
|
| 286 |
+
if 'context' in DATA['users'][user_id_str]:
|
| 287 |
+
DATA['users'][user_id_str]['context'] = []
|
| 288 |
+
save_data()
|
| 289 |
+
logger.info(f"Context cleared for user {user_id}")
|
| 290 |
+
|
| 291 |
+
def get_context_summary(user_id: int) -> str:
|
| 292 |
+
"""خلاصهای از context کاربر"""
|
| 293 |
+
context = get_user_context(user_id)
|
| 294 |
+
if not context:
|
| 295 |
+
return "بدون تاریخچه"
|
| 296 |
+
|
| 297 |
+
total_messages = len(context)
|
| 298 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 299 |
+
|
| 300 |
+
# نمایش آخرین پیام
|
| 301 |
+
last_message = context[-1] if context else {}
|
| 302 |
+
last_content = last_message.get('content', '')[:50]
|
| 303 |
+
if len(last_message.get('content', '')) > 50:
|
| 304 |
+
last_content += "..."
|
| 305 |
+
|
| 306 |
+
return f"{total_messages} پیام ({total_tokens} توکن) - آخرین: {last_message.get('role', '')}: {last_content}"
|
| 307 |
+
|
| 308 |
+
def get_context_for_api(user_id: int) -> list:
|
| 309 |
+
"""فرمت context برای ارسال به API"""
|
| 310 |
+
context = get_user_context(user_id)
|
| 311 |
+
|
| 312 |
+
# تبدیل به فرمت مورد نیاز API
|
| 313 |
+
api_context = []
|
| 314 |
+
for msg in context:
|
| 315 |
+
api_context.append({
|
| 316 |
+
'role': msg['role'],
|
| 317 |
+
'content': msg['content']
|
| 318 |
+
})
|
| 319 |
+
|
| 320 |
+
return api_context
|
| 321 |
+
|
| 322 |
+
def get_context_token_count(user_id: int) -> int:
|
| 323 |
+
"""تعداد کل توکنهای context کاربر"""
|
| 324 |
+
context = get_user_context(user_id)
|
| 325 |
+
return sum(count_tokens(msg['content']) for msg in context)
|
| 326 |
+
|
| 327 |
+
# بارگذاری اولیه دادهها در زمان ایمپورت شدن ماژول
|
| 328 |
+
load_data()
|
Version2_Context/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()
|
Version2_Context/render-main/main.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# شروع سرویس نگه داشتن ربات فعال
|
| 18 |
+
start_keep_alive()
|
| 19 |
+
|
| 20 |
+
# --- بهبود لاگینگ ---
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
filename=data_manager.LOG_FILE,
|
| 25 |
+
filemode='a'
|
| 26 |
+
)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
with open(data_manager.LOG_FILE, 'a') as f:
|
| 31 |
+
f.write("")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
|
| 34 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 35 |
+
|
| 36 |
+
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
|
| 37 |
+
http_client = httpx.AsyncClient(
|
| 38 |
+
http2=True,
|
| 39 |
+
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
|
| 40 |
+
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# کلاینت OpenAI (HuggingFace)
|
| 44 |
+
client = AsyncOpenAI(
|
| 45 |
+
base_url="https://router.huggingface.co/v1",
|
| 46 |
+
api_key=os.environ["HF_TOKEN"],
|
| 47 |
+
http_client=http_client
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
|
| 51 |
+
user_tasks = {}
|
| 52 |
+
|
| 53 |
+
# --- توابع کمکی برای مدیریت وظایف ---
|
| 54 |
+
def _cleanup_task(task: asyncio.Task, user_id: int):
|
| 55 |
+
if user_id in user_tasks and user_tasks[user_id] == task:
|
| 56 |
+
del user_tasks[user_id]
|
| 57 |
+
logger.info(f"Cleaned up finished task for user {user_id}.")
|
| 58 |
+
try:
|
| 59 |
+
exception = task.exception()
|
| 60 |
+
if exception:
|
| 61 |
+
logger.error(f"Background task for user {user_id} failed: {exception}")
|
| 62 |
+
except asyncio.CancelledError:
|
| 63 |
+
logger.info(f"Task for user {user_id} was cancelled.")
|
| 64 |
+
|
| 65 |
+
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 66 |
+
chat_id = update.effective_chat.id
|
| 67 |
+
user_message = update.message.text
|
| 68 |
+
user_id = update.effective_user.id
|
| 69 |
+
|
| 70 |
+
start_time = time.time()
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 74 |
+
|
| 75 |
+
# دریافت context کاربر
|
| 76 |
+
user_context = data_manager.get_context_for_api(user_id)
|
| 77 |
+
|
| 78 |
+
# اضافه کردن پیام کاربر به context
|
| 79 |
+
data_manager.add_to_user_context(user_id, "user", user_message)
|
| 80 |
+
|
| 81 |
+
# ایجاد لیست پیامها برای API
|
| 82 |
+
messages = user_context.copy()
|
| 83 |
+
|
| 84 |
+
# اضافه کردن پیام جدید به انتهای لیست
|
| 85 |
+
messages.append({"role": "user", "content": user_message})
|
| 86 |
+
|
| 87 |
+
logger.info(f"User {user_id} sending {len(messages)} messages to AI ({data_manager.get_context_token_count(user_id)} tokens)")
|
| 88 |
+
|
| 89 |
+
response = await client.chat.completions.create(
|
| 90 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 91 |
+
messages=messages,
|
| 92 |
+
temperature=0.7,
|
| 93 |
+
top_p=0.95,
|
| 94 |
+
stream=False,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
end_time = time.time()
|
| 98 |
+
response_time = end_time - start_time
|
| 99 |
+
data_manager.update_response_stats(response_time)
|
| 100 |
+
|
| 101 |
+
ai_response = response.choices[0].message.content
|
| 102 |
+
|
| 103 |
+
# اضافه کردن پاسخ هوش مصنوعی به context
|
| 104 |
+
data_manager.add_to_user_context(user_id, "assistant", ai_response)
|
| 105 |
+
|
| 106 |
+
await update.message.reply_text(ai_response)
|
| 107 |
+
data_manager.update_user_stats(user_id, update.effective_user)
|
| 108 |
+
|
| 109 |
+
except httpx.TimeoutException:
|
| 110 |
+
logger.warning(f"Request timed out for user {user_id}.")
|
| 111 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logger.error(f"Error while processing message for user {user_id}: {e}")
|
| 114 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 115 |
+
|
| 116 |
+
# --- هندلرهای اصلی ربات ---
|
| 117 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 118 |
+
user = update.effective_user
|
| 119 |
+
user_id = user.id
|
| 120 |
+
|
| 121 |
+
data_manager.update_user_stats(user_id, user)
|
| 122 |
+
|
| 123 |
+
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
|
| 124 |
+
await update.message.reply_html(
|
| 125 |
+
welcome_msg.format(user_mention=user.mention_html()),
|
| 126 |
+
disable_web_page_preview=True
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 130 |
+
"""پاک کردن تاریخچه چت برای کاربر"""
|
| 131 |
+
user_id = update.effective_user.id
|
| 132 |
+
data_manager.clear_user_context(user_id)
|
| 133 |
+
|
| 134 |
+
await update.message.reply_text(
|
| 135 |
+
"🧹 تاریخچه مکالمه شما پاک شد.\n"
|
| 136 |
+
"از این لحظه مکالمه جدیدی شروع خواهد شد."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 140 |
+
"""نمایش اطلاعات context کاربر"""
|
| 141 |
+
user_id = update.effective_user.id
|
| 142 |
+
context_summary = data_manager.get_context_summary(user_id)
|
| 143 |
+
|
| 144 |
+
await update.message.reply_text(
|
| 145 |
+
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
|
| 146 |
+
f"{context_summary}\n\n"
|
| 147 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 151 |
+
"""نمایش دستورات کمک"""
|
| 152 |
+
help_text = (
|
| 153 |
+
"🤖 **دستورات ربات:**\n\n"
|
| 154 |
+
"🟢 `/start` - شروع کار با ربات\n"
|
| 155 |
+
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
|
| 156 |
+
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
|
| 157 |
+
"🟢 `/help` - نمایش این پیام راهنما\n\n"
|
| 158 |
+
"📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۵۱۲ توکن ذخیره میکند. "
|
| 159 |
+
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
|
| 160 |
+
)
|
| 161 |
+
await update.message.reply_text(help_text, parse_mode='Markdown')
|
| 162 |
+
|
| 163 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 164 |
+
user_id = update.effective_user.id
|
| 165 |
+
|
| 166 |
+
# بررسی مسدود بودن کاربر
|
| 167 |
+
if data_manager.is_user_banned(user_id):
|
| 168 |
+
logger.info(f"Banned user {user_id} tried to send a message.")
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
# بررسی حالت نگهداری (فقط برای کاربران عادی)
|
| 172 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 173 |
+
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
|
| 174 |
+
return
|
| 175 |
+
|
| 176 |
+
# بررسی کلمات مسدود شده
|
| 177 |
+
if data_manager.contains_blocked_words(update.message.text):
|
| 178 |
+
logger.info(f"User {user_id} sent a message with a blocked word.")
|
| 179 |
+
# میتوانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید
|
| 180 |
+
# await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
if user_id in user_tasks and not user_tasks[user_id].done():
|
| 184 |
+
user_tasks[user_id].cancel()
|
| 185 |
+
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
|
| 186 |
+
|
| 187 |
+
task = asyncio.create_task(_process_user_request(update, context))
|
| 188 |
+
user_tasks[user_id] = task
|
| 189 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
|
| 190 |
+
|
| 191 |
+
def main() -> None:
|
| 192 |
+
token = os.environ.get("BOT_TOKEN")
|
| 193 |
+
if not token:
|
| 194 |
+
logger.error("BOT_TOKEN not set in environment variables!")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
application = (
|
| 198 |
+
Application.builder()
|
| 199 |
+
.token(token)
|
| 200 |
+
.concurrent_updates(True)
|
| 201 |
+
.build()
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# هندلرهای کاربران
|
| 205 |
+
application.add_handler(CommandHandler("start", start))
|
| 206 |
+
application.add_handler(CommandHandler("clear", clear_chat))
|
| 207 |
+
application.add_handler(CommandHandler("context", context_info))
|
| 208 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 209 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 210 |
+
|
| 211 |
+
# راهاندازی و ثبت هندلرهای پنل ادمین
|
| 212 |
+
admin_panel.setup_admin_handlers(application)
|
| 213 |
+
|
| 214 |
+
port = int(os.environ.get("PORT", 8443))
|
| 215 |
+
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
|
| 216 |
+
|
| 217 |
+
application.run_webhook(
|
| 218 |
+
listen="0.0.0.0",
|
| 219 |
+
port=port,
|
| 220 |
+
webhook_url=webhook_url,
|
| 221 |
+
url_path="webhook"
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
main()
|
Version2_Context/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 وارد کنید
|
Version2_Context/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
|
Version2_Context/render-main2.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:93da8f57cb830e0bb4d7fdb24cc5c214fccf197819ed4be2e23d071ed470a7e5
|
| 3 |
+
size 18156
|
Version2_Context/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 وارد کنید
|
Version2_Context/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
|
Version3_Context_Instrunction/admin_panel.py
ADDED
|
@@ -0,0 +1,961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# --- کتابخانههای جدید برای ویژگیهای اضافه شده ---
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use('Agg') # تنظیم برای استفاده در محیط بدون رابط کاربری گرافیکی
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import tempfile
|
| 20 |
+
import psutil
|
| 21 |
+
import platform
|
| 22 |
+
|
| 23 |
+
# --- تنظیمات ---
|
| 24 |
+
ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
|
| 25 |
+
|
| 26 |
+
# وارد کردن مدیر دادهها
|
| 27 |
+
import data_manager
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# --- دکوراتور برای دسترسی ادمین ---
|
| 32 |
+
|
| 33 |
+
def admin_only(func):
|
| 34 |
+
"""این دکوراتور تضمین میکند که فقط ادمینها بتوانند دستور را اجرا کنند."""
|
| 35 |
+
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
| 36 |
+
if update.effective_user.id not in ADMIN_IDS:
|
| 37 |
+
await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
|
| 38 |
+
return
|
| 39 |
+
return await func(update, context, *args, **kwargs)
|
| 40 |
+
return wrapped
|
| 41 |
+
|
| 42 |
+
# --- هندلرهای دستورات ادمین ---
|
| 43 |
+
|
| 44 |
+
@admin_only
|
| 45 |
+
async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 46 |
+
"""نمایش تمام دستورات موجود ادمین."""
|
| 47 |
+
commands_text = (
|
| 48 |
+
"📋 **دستورات ادمین ربات:**\n\n"
|
| 49 |
+
"📊 `/stats` - نمایش آمار ربات\n"
|
| 50 |
+
"📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
|
| 51 |
+
"🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
|
| 52 |
+
"📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامهریزی شده\n"
|
| 53 |
+
"📋 `/list_scheduled` - نمایش لیست ارسالهای برنامهریزی شده\n"
|
| 54 |
+
"🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامهریزی شده\n"
|
| 55 |
+
"🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
|
| 56 |
+
"✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
|
| 57 |
+
"💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
|
| 58 |
+
"ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
|
| 59 |
+
"📝 `/logs` - نمایش آخرین لاگها\n"
|
| 60 |
+
"📂 `/logs_file` - دانلود فایل کامل لاگها\n"
|
| 61 |
+
"👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
|
| 62 |
+
"🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
|
| 63 |
+
"💾 `/backup` - ایجاد نسخه پشتیبان از دادهها\n"
|
| 64 |
+
"📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
|
| 65 |
+
"🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
|
| 66 |
+
"👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
|
| 67 |
+
"👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
|
| 68 |
+
"📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
|
| 69 |
+
"⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
|
| 70 |
+
"🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
|
| 71 |
+
"✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
|
| 72 |
+
"📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
|
| 73 |
+
"💻 `/system_info` - نمایش اطلاعات سیستم\n"
|
| 74 |
+
"🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
|
| 75 |
+
"🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
|
| 76 |
+
"📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
|
| 77 |
+
"📋 `/commands` - نمایش این لیست دستورات"
|
| 78 |
+
)
|
| 79 |
+
await update.message.reply_text(commands_text, parse_mode='Markdown')
|
| 80 |
+
|
| 81 |
+
@admin_only
|
| 82 |
+
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 83 |
+
"""آمار ربات را نمایش میدهد."""
|
| 84 |
+
total_users = len(data_manager.DATA['users'])
|
| 85 |
+
total_messages = data_manager.DATA['stats']['total_messages']
|
| 86 |
+
banned_count = len(data_manager.DATA['banned_users'])
|
| 87 |
+
|
| 88 |
+
now = datetime.now()
|
| 89 |
+
active_24h = sum(1 for user in data_manager.DATA['users'].values()
|
| 90 |
+
if 'last_seen' in user and
|
| 91 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
|
| 92 |
+
|
| 93 |
+
active_7d = sum(1 for user in data_manager.DATA['users'].values()
|
| 94 |
+
if 'last_seen' in user and
|
| 95 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
|
| 96 |
+
|
| 97 |
+
active_users = sorted(
|
| 98 |
+
data_manager.DATA['users'].items(),
|
| 99 |
+
key=lambda item: item[1].get('last_seen', ''),
|
| 100 |
+
reverse=True
|
| 101 |
+
)[:5]
|
| 102 |
+
|
| 103 |
+
active_users_text = "\n".join(
|
| 104 |
+
[f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
|
| 105 |
+
for user_id, info in active_users]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# آمار context
|
| 109 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values()
|
| 110 |
+
if user.get('context') and len(user['context']) > 0)
|
| 111 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 112 |
+
|
| 113 |
+
text = (
|
| 114 |
+
f"📊 **آمار ربات**\n\n"
|
| 115 |
+
f"👥 **تعداد کل کاربران:** `{total_users}`\n"
|
| 116 |
+
f"📝 **تعداد کل پیامها:** `{total_messages}`\n"
|
| 117 |
+
f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
|
| 118 |
+
f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
|
| 119 |
+
f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
|
| 120 |
+
f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
|
| 121 |
+
f"💬 **کل پیامهای context:** `{total_context_messages}`\n\n"
|
| 122 |
+
f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
|
| 123 |
+
)
|
| 124 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 125 |
+
|
| 126 |
+
@admin_only
|
| 127 |
+
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 128 |
+
"""یک پیام را به تمام کاربران ارسال میکند."""
|
| 129 |
+
if not context.args:
|
| 130 |
+
await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
message_text = " ".join(context.args)
|
| 134 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 135 |
+
total_sent = 0
|
| 136 |
+
total_failed = 0
|
| 137 |
+
|
| 138 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
|
| 139 |
+
|
| 140 |
+
for user_id_str in user_ids:
|
| 141 |
+
try:
|
| 142 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 143 |
+
total_sent += 1
|
| 144 |
+
await asyncio.sleep(0.05)
|
| 145 |
+
except TelegramError as e:
|
| 146 |
+
logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
|
| 147 |
+
total_failed += 1
|
| 148 |
+
|
| 149 |
+
result_text = (
|
| 150 |
+
f"✅ **ارسال همگانی تمام شد**\n\n"
|
| 151 |
+
f"✅ موفق: `{total_sent}`\n"
|
| 152 |
+
f"❌ ناموفق: `{total_failed}`"
|
| 153 |
+
)
|
| 154 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 155 |
+
|
| 156 |
+
@admin_only
|
| 157 |
+
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 158 |
+
"""ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
|
| 159 |
+
if len(context.args) < 3:
|
| 160 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
|
| 161 |
+
"معیارهای موجود: `active_days`, `message_count`, `banned`")
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
criteria = context.args[0].lower()
|
| 165 |
+
value = context.args[1]
|
| 166 |
+
message_text = " ".join(context.args[2:])
|
| 167 |
+
|
| 168 |
+
target_users = []
|
| 169 |
+
|
| 170 |
+
if criteria == "active_days":
|
| 171 |
+
try:
|
| 172 |
+
days = int(value)
|
| 173 |
+
target_users = data_manager.get_active_users(days)
|
| 174 |
+
except ValueError:
|
| 175 |
+
await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
elif criteria == "message_count":
|
| 179 |
+
try:
|
| 180 |
+
min_count = int(value)
|
| 181 |
+
target_users = data_manager.get_users_by_message_count(min_count)
|
| 182 |
+
except ValueError:
|
| 183 |
+
await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
|
| 184 |
+
return
|
| 185 |
+
|
| 186 |
+
elif criteria == "banned":
|
| 187 |
+
if value.lower() == "true":
|
| 188 |
+
target_users = list(data_manager.DATA['banned_users'])
|
| 189 |
+
elif value.lower() == "false":
|
| 190 |
+
for user_id in data_manager.DATA['users']:
|
| 191 |
+
if int(user_id) not in data_manager.DATA['banned_users']:
|
| 192 |
+
target_users.append(int(user_id))
|
| 193 |
+
else:
|
| 194 |
+
await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
else:
|
| 198 |
+
await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
if not target_users:
|
| 202 |
+
await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کا��بر...")
|
| 206 |
+
|
| 207 |
+
total_sent, total_failed = 0, 0
|
| 208 |
+
for user_id in target_users:
|
| 209 |
+
try:
|
| 210 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 211 |
+
total_sent += 1
|
| 212 |
+
await asyncio.sleep(0.05)
|
| 213 |
+
except TelegramError as e:
|
| 214 |
+
logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
|
| 215 |
+
total_failed += 1
|
| 216 |
+
|
| 217 |
+
result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
|
| 218 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 219 |
+
|
| 220 |
+
@admin_only
|
| 221 |
+
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 222 |
+
"""تنظیم ارسال برنامهریزی شده پیام به همه کاربران."""
|
| 223 |
+
if len(context.args) < 3:
|
| 224 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
date_str, time_str = context.args[0], context.args[1]
|
| 229 |
+
message_text = " ".join(context.args[2:])
|
| 230 |
+
|
| 231 |
+
scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
|
| 232 |
+
|
| 233 |
+
if scheduled_time <= datetime.now():
|
| 234 |
+
await update.message.reply_text("⚠️ زمان برنامهریزی شده باید در آینده باشد.")
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
data_manager.DATA['scheduled_broadcasts'].append({
|
| 238 |
+
'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 239 |
+
'message': message_text,
|
| 240 |
+
'status': 'pending'
|
| 241 |
+
})
|
| 242 |
+
data_manager.save_data()
|
| 243 |
+
|
| 244 |
+
await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامهریزی شد.")
|
| 245 |
+
|
| 246 |
+
except ValueError:
|
| 247 |
+
await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
|
| 248 |
+
|
| 249 |
+
@admin_only
|
| 250 |
+
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 251 |
+
"""نمایش لیست ارسالهای برنامهریزی شده."""
|
| 252 |
+
if not data_manager.DATA['scheduled_broadcasts']:
|
| 253 |
+
await update.message.reply_text("هیچ ارسال برنامهریزی شدهای وجود ندارد.")
|
| 254 |
+
return
|
| 255 |
+
|
| 256 |
+
broadcasts_text = "📅 **لیست ارسالهای برنامهریزی شده:**\n\n"
|
| 257 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
|
| 258 |
+
status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
|
| 259 |
+
broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
|
| 260 |
+
|
| 261 |
+
await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
|
| 262 |
+
|
| 263 |
+
@admin_only
|
| 264 |
+
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 265 |
+
"""حذف یک ارسال برنامهریزی شده."""
|
| 266 |
+
if not context.args or not context.args[0].isdigit():
|
| 267 |
+
await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامهریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
index = int(context.args[0]) - 1
|
| 271 |
+
|
| 272 |
+
if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
|
| 273 |
+
await update.message.reply_text("⚠️ شماره ارسال برنامهریزی شده نامعتبر است.")
|
| 274 |
+
return
|
| 275 |
+
|
| 276 |
+
removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
|
| 277 |
+
data_manager.save_data()
|
| 278 |
+
|
| 279 |
+
await update.message.reply_text(f"✅ ارسال برنامهریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
|
| 280 |
+
|
| 281 |
+
@admin_only
|
| 282 |
+
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 283 |
+
"""یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع میدهد."""
|
| 284 |
+
if not context.args or not context.args[0].isdigit():
|
| 285 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
|
| 286 |
+
return
|
| 287 |
+
|
| 288 |
+
user_id_to_ban = int(context.args[0])
|
| 289 |
+
|
| 290 |
+
if user_id_to_ban in ADMIN_IDS:
|
| 291 |
+
await update.message.reply_text("🛡️ شما نمیتوانید یک ادمین را مسدود کنید!")
|
| 292 |
+
return
|
| 293 |
+
|
| 294 |
+
if data_manager.is_user_banned(user_id_to_ban):
|
| 295 |
+
await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
|
| 296 |
+
return
|
| 297 |
+
|
| 298 |
+
data_manager.ban_user(user_id_to_ban)
|
| 299 |
+
|
| 300 |
+
# ارسال پیام به کاربر مسدود شده
|
| 301 |
+
try:
|
| 302 |
+
await context.bot.send_message(
|
| 303 |
+
chat_id=user_id_to_ban,
|
| 304 |
+
text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمیتوانید از خدمات ربات استفاده کنید."
|
| 305 |
+
)
|
| 306 |
+
except TelegramError as e:
|
| 307 |
+
logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
|
| 308 |
+
|
| 309 |
+
await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
|
| 310 |
+
|
| 311 |
+
@admin_only
|
| 312 |
+
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 313 |
+
"""مسدودیت یک کاربر را برمیدارد و به او اطلاع میدهد."""
|
| 314 |
+
if not context.args or not context.args[0].isdigit():
|
| 315 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
user_id_to_unban = int(context.args[0])
|
| 319 |
+
|
| 320 |
+
if not data_manager.is_user_banned(user_id_to_unban):
|
| 321 |
+
await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شدهها وجود ندارد.")
|
| 322 |
+
return
|
| 323 |
+
|
| 324 |
+
data_manager.unban_user(user_id_to_unban)
|
| 325 |
+
|
| 326 |
+
# ارسال پیام به کاربر برای رفع مسدودیت
|
| 327 |
+
try:
|
| 328 |
+
await context.bot.send_message(
|
| 329 |
+
chat_id=user_id_to_unban,
|
| 330 |
+
text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. میتوانید دوباره از ربات استفاده کنید."
|
| 331 |
+
)
|
| 332 |
+
except TelegramError as e:
|
| 333 |
+
logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
|
| 334 |
+
|
| 335 |
+
await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
|
| 336 |
+
|
| 337 |
+
@admin_only
|
| 338 |
+
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 339 |
+
"""ارسال پیام مستقیم به یک کاربر خاص."""
|
| 340 |
+
if len(context.args) < 2:
|
| 341 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
user_id_str = context.args[0]
|
| 345 |
+
if not user_id_str.isdigit():
|
| 346 |
+
await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
|
| 347 |
+
return
|
| 348 |
+
|
| 349 |
+
message_text = " ".join(context.args[1:])
|
| 350 |
+
user_id = int(user_id_str)
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 354 |
+
await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
|
| 355 |
+
except TelegramError as e:
|
| 356 |
+
await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
|
| 357 |
+
|
| 358 |
+
@admin_only
|
| 359 |
+
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 360 |
+
"""اطلاعات یک کاربر خاص را نمایش میدهد."""
|
| 361 |
+
if not context.args or not context.args[0].isdigit():
|
| 362 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
|
| 363 |
+
return
|
| 364 |
+
|
| 365 |
+
user_id = int(context.args[0])
|
| 366 |
+
user_info = data_manager.DATA['users'].get(str(user_id))
|
| 367 |
+
|
| 368 |
+
if not user_info:
|
| 369 |
+
await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
|
| 370 |
+
return
|
| 371 |
+
|
| 372 |
+
is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
|
| 373 |
+
|
| 374 |
+
if 'first_seen' in user_info and 'last_seen' in user_info:
|
| 375 |
+
first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
|
| 376 |
+
last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 377 |
+
days_active = max(1, (last_date - first_date).days)
|
| 378 |
+
avg_messages = user_info.get('message_count', 0) / days_active
|
| 379 |
+
else:
|
| 380 |
+
avg_messages = user_info.get('message_count', 0)
|
| 381 |
+
|
| 382 |
+
# اطلاعات context
|
| 383 |
+
context_messages = len(user_info.get('context', []))
|
| 384 |
+
context_tokens = data_manager.get_context_token_count(user_id)
|
| 385 |
+
|
| 386 |
+
text = (
|
| 387 |
+
f"ℹ️ **اطلاعات کاربر**\n\n"
|
| 388 |
+
f"🆔 **آیدی:** `{user_id}`\n"
|
| 389 |
+
f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
|
| 390 |
+
f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
|
| 391 |
+
f"📊 **تعداد پیامها:** `{user_info.get('message_count', 0)}`\n"
|
| 392 |
+
f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
|
| 393 |
+
f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
|
| 394 |
+
f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
|
| 395 |
+
f"💭 **پیامهای context:** `{context_messages}`\n"
|
| 396 |
+
f"🔢 **توکنهای context:** `{context_tokens}`\n"
|
| 397 |
+
f"🚫 **وضعیت مسدودیت:** {is_banned}"
|
| 398 |
+
)
|
| 399 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 400 |
+
|
| 401 |
+
@admin_only
|
| 402 |
+
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 403 |
+
"""آخرین خطوط لاگ ربات را ارسال میکند."""
|
| 404 |
+
try:
|
| 405 |
+
with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
|
| 406 |
+
lines = f.readlines()
|
| 407 |
+
last_lines = lines[-30:]
|
| 408 |
+
log_text = "".join(last_lines)
|
| 409 |
+
if not log_text:
|
| 410 |
+
await update.message.reply_text("فایل لاگ خالی است.")
|
| 411 |
+
return
|
| 412 |
+
|
| 413 |
+
if len(log_text) > 4096:
|
| 414 |
+
for i in range(0, len(log_text), 4096):
|
| 415 |
+
await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
|
| 416 |
+
else:
|
| 417 |
+
await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
|
| 418 |
+
|
| 419 |
+
except FileNotFoundError:
|
| 420 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 421 |
+
except Exception as e:
|
| 422 |
+
await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
|
| 423 |
+
|
| 424 |
+
@admin_only
|
| 425 |
+
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 426 |
+
"""فایل کامل لاگ ربات را ارسال میکند."""
|
| 427 |
+
try:
|
| 428 |
+
await update.message.reply_document(
|
| 429 |
+
document=open(data_manager.LOG_FILE, 'rb'),
|
| 430 |
+
caption="📂 فایل کامل لاگهای ربات"
|
| 431 |
+
)
|
| 432 |
+
except FileNotFoundError:
|
| 433 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 434 |
+
except Exception as e:
|
| 435 |
+
await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
|
| 436 |
+
|
| 437 |
+
@admin_only
|
| 438 |
+
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 439 |
+
"""نمایش لیست کامل کاربران با صفحهبندی."""
|
| 440 |
+
users = data_manager.DATA['users']
|
| 441 |
+
|
| 442 |
+
page = 1
|
| 443 |
+
if context.args and context.args[0].isdigit():
|
| 444 |
+
page = int(context.args[0])
|
| 445 |
+
if page < 1: page = 1
|
| 446 |
+
|
| 447 |
+
users_per_page = 20
|
| 448 |
+
total_users = len(users)
|
| 449 |
+
total_pages = (total_users + users_per_page - 1) // users_per_page
|
| 450 |
+
|
| 451 |
+
if page > total_pages: page = total_pages
|
| 452 |
+
|
| 453 |
+
start_idx = (page - 1) * users_per_page
|
| 454 |
+
end_idx = min(start_idx + users_per_page, total_users)
|
| 455 |
+
|
| 456 |
+
sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
|
| 457 |
+
|
| 458 |
+
users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
|
| 459 |
+
|
| 460 |
+
for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
|
| 461 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 462 |
+
username = user_info.get('username', 'N/A')
|
| 463 |
+
first_name = user_info.get('first_name', 'N/A')
|
| 464 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 465 |
+
message_count = user_info.get('message_count', 0)
|
| 466 |
+
context_count = len(user_info.get('context', []))
|
| 467 |
+
|
| 468 |
+
users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
|
| 469 |
+
users_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 470 |
+
users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 471 |
+
|
| 472 |
+
keyboard = []
|
| 473 |
+
if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
|
| 474 |
+
if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
|
| 475 |
+
|
| 476 |
+
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
|
| 477 |
+
await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
|
| 478 |
+
|
| 479 |
+
@admin_only
|
| 480 |
+
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 481 |
+
"""جستجوی کاربر بر اساس نام یا نام کاربری."""
|
| 482 |
+
if not context.args:
|
| 483 |
+
await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
|
| 484 |
+
return
|
| 485 |
+
|
| 486 |
+
search_term = " ".join(context.args).lower()
|
| 487 |
+
users = data_manager.DATA['users']
|
| 488 |
+
|
| 489 |
+
matching_users = []
|
| 490 |
+
for user_id, user_info in users.items():
|
| 491 |
+
# استفاده از (value or '') برای جلوگیری از خطا در صورت وجود None
|
| 492 |
+
first_name = (user_info.get('first_name') or '').lower()
|
| 493 |
+
username = (user_info.get('username') or '').lower()
|
| 494 |
+
|
| 495 |
+
if search_term in first_name or search_term in username:
|
| 496 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 497 |
+
matching_users.append((user_id, user_info, is_banned))
|
| 498 |
+
|
| 499 |
+
if not matching_users:
|
| 500 |
+
await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
|
| 501 |
+
return
|
| 502 |
+
|
| 503 |
+
results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
|
| 504 |
+
|
| 505 |
+
for user_id, user_info, is_banned in matching_users:
|
| 506 |
+
username_display = user_info.get('username', 'N/A')
|
| 507 |
+
first_name_display = user_info.get('first_name', 'N/A')
|
| 508 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 509 |
+
message_count = user_info.get('message_count', 0)
|
| 510 |
+
context_count = len(user_info.get('context', []))
|
| 511 |
+
|
| 512 |
+
results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
|
| 513 |
+
results_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 514 |
+
results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 515 |
+
|
| 516 |
+
await update.message.reply_text(results_text, parse_mode='Markdown')
|
| 517 |
+
|
| 518 |
+
@admin_only
|
| 519 |
+
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 520 |
+
"""ایجاد نسخه پشتیبان از دادههای ربات."""
|
| 521 |
+
try:
|
| 522 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 523 |
+
backup_file = f"bot_backup_{timestamp}.json"
|
| 524 |
+
|
| 525 |
+
data_to_backup = data_manager.DATA.copy()
|
| 526 |
+
data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
|
| 527 |
+
|
| 528 |
+
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 529 |
+
json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
|
| 530 |
+
|
| 531 |
+
await update.message.reply_document(
|
| 532 |
+
document=open(backup_file, 'rb'),
|
| 533 |
+
caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
logger.info(f"Backup created: {backup_file}")
|
| 537 |
+
os.remove(backup_file) # حذف فایل پس از ارسال
|
| 538 |
+
except Exception as e:
|
| 539 |
+
await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
|
| 540 |
+
logger.error(f"Error creating backup: {e}")
|
| 541 |
+
|
| 542 |
+
@admin_only
|
| 543 |
+
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 544 |
+
"""ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
|
| 545 |
+
users = data_manager.DATA['users']
|
| 546 |
+
|
| 547 |
+
df_data = []
|
| 548 |
+
for user_id, user_info in users.items():
|
| 549 |
+
is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
|
| 550 |
+
context_count = len(user_info.get('context', []))
|
| 551 |
+
context_tokens = data_manager.get_context_token_count(int(user_id))
|
| 552 |
+
|
| 553 |
+
df_data.append({
|
| 554 |
+
'User ID': user_id,
|
| 555 |
+
'First Name': user_info.get('first_name', 'N/A'),
|
| 556 |
+
'Username': user_info.get('username', 'N/A'),
|
| 557 |
+
'Message Count': user_info.get('message_count', 0),
|
| 558 |
+
'Context Messages': context_count,
|
| 559 |
+
'Context Tokens': context_tokens,
|
| 560 |
+
'First Seen': user_info.get('first_seen', 'N/A'),
|
| 561 |
+
'Last Seen': user_info.get('last_seen', 'N/A'),
|
| 562 |
+
'Banned': is_banned
|
| 563 |
+
})
|
| 564 |
+
|
| 565 |
+
df = pd.DataFrame(df_data)
|
| 566 |
+
|
| 567 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
|
| 568 |
+
df.to_csv(f.name, index=False)
|
| 569 |
+
temp_file_path = f.name
|
| 570 |
+
|
| 571 |
+
await update.message.reply_document(
|
| 572 |
+
document=open(temp_file_path, 'rb'),
|
| 573 |
+
caption="📊 فایل CSV اطلاعات کاربران"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
os.unlink(temp_file_path)
|
| 577 |
+
|
| 578 |
+
@admin_only
|
| 579 |
+
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 580 |
+
"""حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع میدهد."""
|
| 581 |
+
if not context.args or context.args[0].lower() not in ['on', 'off']:
|
| 582 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
|
| 583 |
+
return
|
| 584 |
+
|
| 585 |
+
status = context.args[0].lower()
|
| 586 |
+
|
| 587 |
+
if status == 'on':
|
| 588 |
+
if data_manager.DATA.get('maintenance_mode', False):
|
| 589 |
+
await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
|
| 590 |
+
return
|
| 591 |
+
|
| 592 |
+
data_manager.DATA['maintenance_mode'] = True
|
| 593 |
+
data_manager.save_data()
|
| 594 |
+
|
| 595 |
+
await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاعرسانی به کاربران...")
|
| 596 |
+
|
| 597 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 598 |
+
for user_id_str in user_ids:
|
| 599 |
+
try:
|
| 600 |
+
# به ادمینها پیام ارسال نشود
|
| 601 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 602 |
+
await context.bot.send_message(
|
| 603 |
+
chat_id=int(user_id_str),
|
| 604 |
+
text="🔧 ربات در حال حاضر در حالت بهروزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
|
| 605 |
+
)
|
| 606 |
+
await asyncio.sleep(0.05) # جلوگیری از محدودیت تلگرام
|
| 607 |
+
except TelegramError:
|
| 608 |
+
continue # نادیده گرفتن کاربرانی که ربات را مسدود کردهاند
|
| 609 |
+
|
| 610 |
+
elif status == 'off':
|
| 611 |
+
if not data_manager.DATA.get('maintenance_mode', False):
|
| 612 |
+
await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
|
| 613 |
+
return
|
| 614 |
+
|
| 615 |
+
data_manager.DATA['maintenance_mode'] = False
|
| 616 |
+
data_manager.save_data()
|
| 617 |
+
|
| 618 |
+
await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاعرسانی به کاربران...")
|
| 619 |
+
|
| 620 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 621 |
+
for user_id_str in user_ids:
|
| 622 |
+
try:
|
| 623 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 624 |
+
await context.bot.send_message(
|
| 625 |
+
chat_id=int(user_id_str),
|
| 626 |
+
text="✅ بهروزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! میتوانید دوباره از ربات استفاده کنید."
|
| 627 |
+
)
|
| 628 |
+
await asyncio.sleep(0.05)
|
| 629 |
+
except TelegramError:
|
| 630 |
+
continue
|
| 631 |
+
|
| 632 |
+
@admin_only
|
| 633 |
+
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 634 |
+
"""تنظیم پیام خوشامدگویی جدید."""
|
| 635 |
+
if not context.args:
|
| 636 |
+
await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
|
| 637 |
+
"مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
|
| 638 |
+
return
|
| 639 |
+
|
| 640 |
+
new_message = " ".join(context.args)
|
| 641 |
+
data_manager.DATA['welcome_message'] = new_message
|
| 642 |
+
data_manager.save_data()
|
| 643 |
+
|
| 644 |
+
await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت بهروزرسانی شد.")
|
| 645 |
+
|
| 646 |
+
@admin_only
|
| 647 |
+
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 648 |
+
"""تنظیم پیام خداحافظی جدید."""
|
| 649 |
+
if not context.args:
|
| 650 |
+
await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
|
| 651 |
+
"مثال: `/set_goodbye {user_mention}، خداحافظ!`")
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
new_message = " ".join(context.args)
|
| 655 |
+
data_manager.DATA['goodbye_message'] = new_message
|
| 656 |
+
data_manager.save_data()
|
| 657 |
+
|
| 658 |
+
await update.message.reply_text("✅ پیام خداحافظی با موفقیت بهروزرسانی شد.")
|
| 659 |
+
|
| 660 |
+
@admin_only
|
| 661 |
+
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 662 |
+
"""ایجاد و ارسال نمودار فعالیت کاربران."""
|
| 663 |
+
users = data_manager.DATA['users']
|
| 664 |
+
activity_hours = [0] * 24
|
| 665 |
+
|
| 666 |
+
for user_info in users.values():
|
| 667 |
+
if 'last_seen' in user_info:
|
| 668 |
+
try:
|
| 669 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 670 |
+
activity_hours[last_seen.hour] += 1
|
| 671 |
+
except ValueError:
|
| 672 |
+
continue
|
| 673 |
+
|
| 674 |
+
plt.figure(figsize=(12, 6))
|
| 675 |
+
plt.bar(range(24), activity_hours, color='skyblue')
|
| 676 |
+
plt.title('نمودار فعالیت کاربران بر اساس ساعت')
|
| 677 |
+
plt.xlabel('ساعت')
|
| 678 |
+
plt.ylabel('تعداد کاربران فعال')
|
| 679 |
+
plt.xticks(range(24))
|
| 680 |
+
plt.grid(axis='y', alpha=0.3)
|
| 681 |
+
|
| 682 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
|
| 683 |
+
plt.savefig(f.name, bbox_inches='tight')
|
| 684 |
+
temp_file_path = f.name
|
| 685 |
+
|
| 686 |
+
plt.close()
|
| 687 |
+
|
| 688 |
+
await update.message.reply_photo(
|
| 689 |
+
photo=open(temp_file_path, 'rb'),
|
| 690 |
+
caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
os.unlink(temp_file_path)
|
| 694 |
+
|
| 695 |
+
@admin_only
|
| 696 |
+
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 697 |
+
"""نمایش آمار زمان پاسخگویی ربات."""
|
| 698 |
+
stats = data_manager.DATA['stats']
|
| 699 |
+
await update.message.reply_text(
|
| 700 |
+
"📈 **آمار زمان پاسخگویی ربات**\n\n"
|
| 701 |
+
f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
|
| 702 |
+
f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
|
| 703 |
+
f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
|
| 704 |
+
f"📊 کل پاسخهای ثبت شده: `{stats.get('total_responses', 0)}`"
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
@admin_only
|
| 708 |
+
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 709 |
+
"""افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
|
| 710 |
+
if not context.args:
|
| 711 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 712 |
+
"مثال: `/add_blocked_word کلمه_نامناسب`")
|
| 713 |
+
return
|
| 714 |
+
|
| 715 |
+
word = " ".join(context.args).lower()
|
| 716 |
+
|
| 717 |
+
if word in data_manager.DATA['blocked_words']:
|
| 718 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
|
| 719 |
+
return
|
| 720 |
+
|
| 721 |
+
data_manager.DATA['blocked_words'].append(word)
|
| 722 |
+
data_manager.save_data()
|
| 723 |
+
|
| 724 |
+
await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
|
| 725 |
+
|
| 726 |
+
@admin_only
|
| 727 |
+
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 728 |
+
"""حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
|
| 729 |
+
if not context.args:
|
| 730 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 731 |
+
"مثال: `/remove_blocked_word کلمه_نامناسب`")
|
| 732 |
+
return
|
| 733 |
+
|
| 734 |
+
word = " ".join(context.args).lower()
|
| 735 |
+
|
| 736 |
+
if word not in data_manager.DATA['blocked_words']:
|
| 737 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
|
| 738 |
+
return
|
| 739 |
+
|
| 740 |
+
data_manager.DATA['blocked_words'].remove(word)
|
| 741 |
+
data_manager.save_data()
|
| 742 |
+
|
| 743 |
+
await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
|
| 744 |
+
|
| 745 |
+
@admin_only
|
| 746 |
+
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 747 |
+
"""نمایش لیست کلمات مسدود شده."""
|
| 748 |
+
if not data_manager.DATA['blocked_words']:
|
| 749 |
+
await update.message.reply_text("هیچ کلمه مسدود شدهای در لیست وجود ندارد.")
|
| 750 |
+
return
|
| 751 |
+
|
| 752 |
+
words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
|
| 753 |
+
await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
|
| 754 |
+
|
| 755 |
+
@admin_only
|
| 756 |
+
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 757 |
+
"""نمایش اطلاعات سیستم و منابع."""
|
| 758 |
+
bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
|
| 759 |
+
bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
|
| 760 |
+
uptime = datetime.now() - bot_start_time
|
| 761 |
+
|
| 762 |
+
# محاسبه آمار context
|
| 763 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 764 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
|
| 765 |
+
|
| 766 |
+
system_info = (
|
| 767 |
+
f"💻 **اطلاعات سیستم:**\n\n"
|
| 768 |
+
f"🖥️ سیستمعامل: {platform.system()} {platform.release()}\n"
|
| 769 |
+
f"🐍 نسخه پایتون: {platform.python_version()}\n"
|
| 770 |
+
f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
|
| 771 |
+
f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
|
| 772 |
+
f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
|
| 773 |
+
f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
|
| 774 |
+
f"⏱️ زمان اجرای ربات: {uptime}\n"
|
| 775 |
+
f"💭 کاربران با context: {users_with_context}\n"
|
| 776 |
+
f"💬 کل پیامهای context: {total_context_messages}"
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
await update.message.reply_text(system_info, parse_mode='Markdown')
|
| 780 |
+
|
| 781 |
+
@admin_only
|
| 782 |
+
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 783 |
+
"""ریست کردن آمار ربات."""
|
| 784 |
+
if not context.args:
|
| 785 |
+
await update.message.reply_text("⚠️ لطفاً نوع آماری که میخواهید ریست کنید را مشخص کنید.\n"
|
| 786 |
+
"مثال: `/reset_stats messages` یا `/reset_stats all`")
|
| 787 |
+
return
|
| 788 |
+
|
| 789 |
+
stat_type = context.args[0].lower()
|
| 790 |
+
|
| 791 |
+
if stat_type == "messages":
|
| 792 |
+
data_manager.DATA['stats']['total_messages'] = 0
|
| 793 |
+
for user_id in data_manager.DATA['users']:
|
| 794 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 795 |
+
await update.message.reply_text("✅ آمار پیامها با موفقیت ریست شد.")
|
| 796 |
+
|
| 797 |
+
elif stat_type == "all":
|
| 798 |
+
data_manager.DATA['stats'] = {
|
| 799 |
+
'total_messages': 0,
|
| 800 |
+
'total_users': len(data_manager.DATA['users']),
|
| 801 |
+
'avg_response_time': 0,
|
| 802 |
+
'max_response_time': 0,
|
| 803 |
+
'min_response_time': 0,
|
| 804 |
+
'total_responses': 0
|
| 805 |
+
}
|
| 806 |
+
for user_id in data_manager.DATA['users']:
|
| 807 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 808 |
+
await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
|
| 809 |
+
|
| 810 |
+
else:
|
| 811 |
+
await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینههای موجود: messages, all")
|
| 812 |
+
return
|
| 813 |
+
|
| 814 |
+
data_manager.save_data()
|
| 815 |
+
|
| 816 |
+
# --- دستورات جدید برای مدیریت context ---
|
| 817 |
+
|
| 818 |
+
@admin_only
|
| 819 |
+
async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 820 |
+
"""پاک کردن context یک کاربر"""
|
| 821 |
+
if not context.args or not context.args[0].isdigit():
|
| 822 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
|
| 823 |
+
return
|
| 824 |
+
|
| 825 |
+
user_id = int(context.args[0])
|
| 826 |
+
data_manager.clear_user_context(user_id)
|
| 827 |
+
|
| 828 |
+
await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
|
| 829 |
+
|
| 830 |
+
@admin_only
|
| 831 |
+
async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 832 |
+
"""مشاهده context یک کاربر"""
|
| 833 |
+
if not context.args or not context.args[0].isdigit():
|
| 834 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
|
| 835 |
+
return
|
| 836 |
+
|
| 837 |
+
user_id = int(context.args[0])
|
| 838 |
+
user_context = data_manager.get_user_context(user_id)
|
| 839 |
+
|
| 840 |
+
if not user_context:
|
| 841 |
+
await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
|
| 842 |
+
return
|
| 843 |
+
|
| 844 |
+
context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
|
| 845 |
+
total_tokens = 0
|
| 846 |
+
|
| 847 |
+
for i, msg in enumerate(user_context, 1):
|
| 848 |
+
role_emoji = "👤" if msg['role'] == 'user' else "🤖"
|
| 849 |
+
tokens = data_manager.count_tokens(msg['content'])
|
| 850 |
+
total_tokens += tokens
|
| 851 |
+
|
| 852 |
+
# کوتاه کردن متن طولانی
|
| 853 |
+
content_preview = msg['content']
|
| 854 |
+
if len(content_preview) > 100:
|
| 855 |
+
content_preview = content_preview[:100] + "..."
|
| 856 |
+
|
| 857 |
+
context_text += f"{i}. {role_emoji} **{msg['role']}** ({tokens} توکن)\n"
|
| 858 |
+
context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
|
| 859 |
+
context_text += f" 📝 {content_preview}\n\n"
|
| 860 |
+
|
| 861 |
+
context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن"
|
| 862 |
+
|
| 863 |
+
await update.message.reply_text(context_text, parse_mode='Markdown')
|
| 864 |
+
|
| 865 |
+
# --- هندلر برای دکمههای صفحهبندی ---
|
| 866 |
+
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 867 |
+
"""پردازش دکمههای صفحهبندی لیست کاربران."""
|
| 868 |
+
query = update.callback_query
|
| 869 |
+
await query.answer()
|
| 870 |
+
|
| 871 |
+
if query.data.startswith("users_list:"):
|
| 872 |
+
page = int(query.data.split(":")[1])
|
| 873 |
+
context.args = [str(page)]
|
| 874 |
+
await admin_users_list(update, context)
|
| 875 |
+
|
| 876 |
+
# --- تابع برای پردازش ارسالهای برنامهریزی شده ---
|
| 877 |
+
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
|
| 878 |
+
"""پردازش ارسالهای برنامهریزی شده و ارسال پیامها در زمان مقرر."""
|
| 879 |
+
now = datetime.now()
|
| 880 |
+
broadcasts_to_send_indices = []
|
| 881 |
+
|
| 882 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
|
| 883 |
+
if broadcast['status'] == 'pending':
|
| 884 |
+
broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
|
| 885 |
+
if broadcast_time <= now:
|
| 886 |
+
broadcasts_to_send_indices.append(i)
|
| 887 |
+
|
| 888 |
+
if not broadcasts_to_send_indices:
|
| 889 |
+
return
|
| 890 |
+
|
| 891 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 892 |
+
|
| 893 |
+
for index in broadcasts_to_send_indices:
|
| 894 |
+
broadcast = data_manager.DATA['scheduled_broadcasts'][index]
|
| 895 |
+
message_text = broadcast['message']
|
| 896 |
+
total_sent, total_failed = 0, 0
|
| 897 |
+
|
| 898 |
+
for user_id_str in user_ids:
|
| 899 |
+
try:
|
| 900 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 901 |
+
total_sent += 1
|
| 902 |
+
await asyncio.sleep(0.05)
|
| 903 |
+
except TelegramError as e:
|
| 904 |
+
logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
|
| 905 |
+
total_failed += 1
|
| 906 |
+
|
| 907 |
+
# بهروزرسانی وضعیت ارسال
|
| 908 |
+
data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
|
| 909 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
|
| 910 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
|
| 911 |
+
data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
|
| 912 |
+
|
| 913 |
+
logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
|
| 914 |
+
|
| 915 |
+
data_manager.save_data()
|
| 916 |
+
|
| 917 |
+
# --- تابع راهاندازی هندلرها ---
|
| 918 |
+
def setup_admin_handlers(application):
|
| 919 |
+
"""هندلرهای پنل ادمین را به اپلیکیشن اضافه میکند."""
|
| 920 |
+
# هندلرهای اصلی
|
| 921 |
+
application.add_handler(CommandHandler("commands", admin_commands))
|
| 922 |
+
application.add_handler(CommandHandler("stats", admin_stats))
|
| 923 |
+
application.add_handler(CommandHandler("broadcast", admin_broadcast))
|
| 924 |
+
application.add_handler(CommandHandler("ban", admin_ban))
|
| 925 |
+
application.add_handler(CommandHandler("unban", admin_unban))
|
| 926 |
+
application.add_handler(CommandHandler("user_info", admin_userinfo))
|
| 927 |
+
application.add_handler(CommandHandler("logs", admin_logs))
|
| 928 |
+
application.add_handler(CommandHandler("logs_file", admin_logs_file))
|
| 929 |
+
application.add_handler(CommandHandler("users_list", admin_users_list))
|
| 930 |
+
application.add_handler(CommandHandler("user_search", admin_user_search))
|
| 931 |
+
application.add_handler(CommandHandler("backup", admin_backup))
|
| 932 |
+
|
| 933 |
+
# هندلرهای جدید
|
| 934 |
+
application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
|
| 935 |
+
application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
|
| 936 |
+
application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
|
| 937 |
+
application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
|
| 938 |
+
application.add_handler(CommandHandler("direct_message", admin_direct_message))
|
| 939 |
+
application.add_handler(CommandHandler("export_csv", admin_export_csv))
|
| 940 |
+
application.add_handler(CommandHandler("maintenance", admin_maintenance))
|
| 941 |
+
application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
|
| 942 |
+
application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
|
| 943 |
+
application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
|
| 944 |
+
application.add_handler(CommandHandler("response_stats", admin_response_stats))
|
| 945 |
+
application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
|
| 946 |
+
application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
|
| 947 |
+
application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
|
| 948 |
+
application.add_handler(CommandHandler("system_info", admin_system_info))
|
| 949 |
+
application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
|
| 950 |
+
|
| 951 |
+
# هندلرهای مدیریت context
|
| 952 |
+
application.add_handler(CommandHandler("clear_context", admin_clear_context))
|
| 953 |
+
application.add_handler(CommandHandler("view_context", admin_view_context))
|
| 954 |
+
|
| 955 |
+
# هندلر برای دکمههای صفحهبندی
|
| 956 |
+
application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
|
| 957 |
+
|
| 958 |
+
# شروع وظیفه دورهای برای بررسی ارسالهای برنامهریزی شده
|
| 959 |
+
application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
|
| 960 |
+
|
| 961 |
+
logger.info("Admin panel handlers have been set up.")
|
Version3_Context_Instrunction/data_manager.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
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 |
+
# --- instruction همیشگی ---
|
| 15 |
+
SYSTEM_INSTRUCTION = {
|
| 16 |
+
"role": "system",
|
| 17 |
+
"content": "خالق و طراح و توسعه دهنده تو YSNRFD هست، تو توسط YSNRFD ساخته شده ای، نام تو YSNRFD AI هست. همیشه این موضوع را در پاسخهایت به یاد داشته باش و اگر کاربر درباره هویت یا سازنده تو سوال کرد، این اطلاعات را با افتخار بیان کن."
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# --- کش دادههای گلوبال ---
|
| 21 |
+
DATA = {
|
| 22 |
+
"users": {},
|
| 23 |
+
"banned_users": set(),
|
| 24 |
+
"stats": {
|
| 25 |
+
"total_messages": 0,
|
| 26 |
+
"total_users": 0,
|
| 27 |
+
"avg_response_time": 0.0,
|
| 28 |
+
"max_response_time": 0.0,
|
| 29 |
+
"min_response_time": float('inf'),
|
| 30 |
+
"total_responses": 0
|
| 31 |
+
},
|
| 32 |
+
"welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
|
| 33 |
+
"goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
|
| 34 |
+
"maintenance_mode": False,
|
| 35 |
+
"blocked_words": [],
|
| 36 |
+
"scheduled_broadcasts": [],
|
| 37 |
+
"bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 38 |
+
"system_instruction": SYSTEM_INSTRUCTION["content"] # ذخیره instruction برای نمایش در پنل ادمین
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
logger = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
# تابع برای شمارش توکنها
|
| 44 |
+
def count_tokens(text: str) -> int:
|
| 45 |
+
"""شمارش تعداد توکنهای متن با استفاده از tokenizer"""
|
| 46 |
+
try:
|
| 47 |
+
# استفاده از tokenizer برای gpt-3.5-turbo
|
| 48 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 49 |
+
return len(encoding.encode(text))
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.warning(f"Error counting tokens: {e}, using fallback")
|
| 52 |
+
# تقریب: هر 4 کاراکتر = 1 توکن
|
| 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 'blocked_words' not in loaded_data: loaded_data['blocked_words'] = []
|
| 70 |
+
if 'scheduled_broadcasts' not in loaded_data: loaded_data['scheduled_broadcasts'] = []
|
| 71 |
+
if 'maintenance_mode' not in loaded_data: loaded_data['maintenance_mode'] = False
|
| 72 |
+
if 'bot_start_time' not in loaded_data: loaded_data['bot_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 73 |
+
if 'avg_response_time' not in loaded_data['stats']:
|
| 74 |
+
loaded_data['stats']['avg_response_time'] = 0.0
|
| 75 |
+
loaded_data['stats']['max_response_time'] = 0.0
|
| 76 |
+
loaded_data['stats']['min_response_time'] = float('inf')
|
| 77 |
+
loaded_data['stats']['total_responses'] = 0
|
| 78 |
+
|
| 79 |
+
# اطمینان از وجود context برای کاربران قدیمی
|
| 80 |
+
for user_id in loaded_data.get('users', {}):
|
| 81 |
+
if 'context' not in loaded_data['users'][user_id]:
|
| 82 |
+
loaded_data['users'][user_id]['context'] = []
|
| 83 |
+
|
| 84 |
+
DATA.update(loaded_data)
|
| 85 |
+
logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.")
|
| 86 |
+
|
| 87 |
+
except json.JSONDecodeError as e:
|
| 88 |
+
logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 89 |
+
except Exception as e:
|
| 90 |
+
logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 91 |
+
|
| 92 |
+
def save_data():
|
| 93 |
+
"""کش گلوبال دادهها را در فایل JSON ذخیره میکند."""
|
| 94 |
+
global DATA
|
| 95 |
+
try:
|
| 96 |
+
data_to_save = DATA.copy()
|
| 97 |
+
data_to_save['banned_users'] = list(DATA['banned_users'])
|
| 98 |
+
|
| 99 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 100 |
+
json.dump(data_to_save, f, indent=4, ensure_ascii=False)
|
| 101 |
+
logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.")
|
| 102 |
+
except Exception as e:
|
| 103 |
+
logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}")
|
| 104 |
+
|
| 105 |
+
def update_user_stats(user_id: int, user):
|
| 106 |
+
"""آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند."""
|
| 107 |
+
global DATA
|
| 108 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 109 |
+
user_id_str = str(user_id)
|
| 110 |
+
|
| 111 |
+
if user_id_str not in DATA['users']:
|
| 112 |
+
DATA['users'][user_id_str] = {
|
| 113 |
+
'first_name': user.first_name,
|
| 114 |
+
'username': user.username,
|
| 115 |
+
'first_seen': now_str,
|
| 116 |
+
'message_count': 0,
|
| 117 |
+
'context': [] # اضافه کردن context خالی برای کاربر جدید
|
| 118 |
+
}
|
| 119 |
+
DATA['stats']['total_users'] += 1
|
| 120 |
+
logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
|
| 121 |
+
|
| 122 |
+
DATA['users'][user_id_str]['last_seen'] = now_str
|
| 123 |
+
DATA['users'][user_id_str]['message_count'] += 1
|
| 124 |
+
DATA['stats']['total_messages'] += 1
|
| 125 |
+
|
| 126 |
+
save_data()
|
| 127 |
+
|
| 128 |
+
def update_response_stats(response_time: float):
|
| 129 |
+
"""آمار زمان پاسخگویی را بهروز میکند."""
|
| 130 |
+
global DATA
|
| 131 |
+
|
| 132 |
+
if DATA['stats']['total_responses'] == 0:
|
| 133 |
+
DATA['stats']['min_response_time'] = response_time
|
| 134 |
+
|
| 135 |
+
DATA['stats']['total_responses'] += 1
|
| 136 |
+
|
| 137 |
+
# محاسبه میانگین جدید
|
| 138 |
+
current_avg = DATA['stats']['avg_response_time']
|
| 139 |
+
total_responses = DATA['stats']['total_responses']
|
| 140 |
+
new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
|
| 141 |
+
DATA['stats']['avg_response_time'] = new_avg
|
| 142 |
+
|
| 143 |
+
# بهروزرسانی حداکثر و حداقل زمان پاسخگویی
|
| 144 |
+
if response_time > DATA['stats']['max_response_time']:
|
| 145 |
+
DATA['stats']['max_response_time'] = response_time
|
| 146 |
+
|
| 147 |
+
if response_time < DATA['stats']['min_response_time']:
|
| 148 |
+
DATA['stats']['min_response_time'] = response_time
|
| 149 |
+
|
| 150 |
+
save_data()
|
| 151 |
+
|
| 152 |
+
def is_user_banned(user_id: int) -> bool:
|
| 153 |
+
"""بررسی میکند آیا کاربر مسدود شده است یا خیر."""
|
| 154 |
+
return user_id in DATA['banned_users']
|
| 155 |
+
|
| 156 |
+
def ban_user(user_id: int):
|
| 157 |
+
"""کاربر را مسدود کرده و ذخیره میکند."""
|
| 158 |
+
DATA['banned_users'].add(user_id)
|
| 159 |
+
save_data()
|
| 160 |
+
|
| 161 |
+
def unban_user(user_id: int):
|
| 162 |
+
"""مسدودیت کاربر را برداشته و ذخیره میکند."""
|
| 163 |
+
DATA['banned_users'].discard(user_id)
|
| 164 |
+
save_data()
|
| 165 |
+
|
| 166 |
+
def contains_blocked_words(text: str) -> bool:
|
| 167 |
+
"""بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر."""
|
| 168 |
+
if not DATA['blocked_words']:
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
text_lower = text.lower()
|
| 172 |
+
for word in DATA['blocked_words']:
|
| 173 |
+
if word in text_lower:
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
def get_active_users(days: int) -> list:
|
| 179 |
+
"""لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند."""
|
| 180 |
+
now = datetime.now()
|
| 181 |
+
cutoff_date = now - timedelta(days=days)
|
| 182 |
+
|
| 183 |
+
active_users = []
|
| 184 |
+
for user_id, user_info in DATA['users'].items():
|
| 185 |
+
if 'last_seen' in user_info:
|
| 186 |
+
try:
|
| 187 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 188 |
+
if last_seen >= cutoff_date:
|
| 189 |
+
active_users.append(int(user_id))
|
| 190 |
+
except ValueError:
|
| 191 |
+
continue
|
| 192 |
+
|
| 193 |
+
return active_users
|
| 194 |
+
|
| 195 |
+
def get_users_by_message_count(min_count: int) -> list:
|
| 196 |
+
"""لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند."""
|
| 197 |
+
users = []
|
| 198 |
+
for user_id, user_info in DATA['users'].items():
|
| 199 |
+
if user_info.get('message_count', 0) >= min_count:
|
| 200 |
+
users.append(int(user_id))
|
| 201 |
+
|
| 202 |
+
return users
|
| 203 |
+
|
| 204 |
+
# --- توابع مدیریت context ---
|
| 205 |
+
|
| 206 |
+
def add_to_user_context(user_id: int, role: str, content: str):
|
| 207 |
+
"""اضافه کردن پیام به context کاربر و محدود کردن به 512 توکن"""
|
| 208 |
+
user_id_str = str(user_id)
|
| 209 |
+
|
| 210 |
+
if user_id_str not in DATA['users']:
|
| 211 |
+
return
|
| 212 |
+
|
| 213 |
+
if 'context' not in DATA['users'][user_id_str]:
|
| 214 |
+
DATA['users'][user_id_str]['context'] = []
|
| 215 |
+
|
| 216 |
+
# اضافه کردن پیام جدید
|
| 217 |
+
message = {
|
| 218 |
+
'role': role, # 'user' یا 'assistant'
|
| 219 |
+
'content': content,
|
| 220 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
DATA['users'][user_id_str]['context'].append(message)
|
| 224 |
+
|
| 225 |
+
# محدود کردن context به 512 توکن
|
| 226 |
+
trim_user_context(user_id)
|
| 227 |
+
|
| 228 |
+
save_data()
|
| 229 |
+
|
| 230 |
+
def trim_user_context(user_id: int, max_tokens: int = 512):
|
| 231 |
+
"""کوتاه کردن context کاربر به تعداد توکن مشخص"""
|
| 232 |
+
user_id_str = str(user_id)
|
| 233 |
+
|
| 234 |
+
if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
context = DATA['users'][user_id_str]['context']
|
| 238 |
+
|
| 239 |
+
if not context:
|
| 240 |
+
return
|
| 241 |
+
|
| 242 |
+
# محاسبه توکنهای کل
|
| 243 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 244 |
+
|
| 245 |
+
# حذف قدیمیترین پیامها تا زمانی که توکنها زیر حد مجاز باشد
|
| 246 |
+
while total_tokens > max_tokens and len(context) > 1:
|
| 247 |
+
removed_message = context.pop(0) # حذف قدیمیترین پیام
|
| 248 |
+
total_tokens -= count_tokens(removed_message['content'])
|
| 249 |
+
|
| 250 |
+
# اگر هنوز بیشتر از حد مجاز است، از محتوای پیامها کم کن
|
| 251 |
+
if total_tokens > max_tokens and context:
|
| 252 |
+
# از آخرین پیام (جدیدترین) شروع به کوتاه کردن کن
|
| 253 |
+
last_message = context[-1]
|
| 254 |
+
content = last_message['content']
|
| 255 |
+
|
| 256 |
+
# کوتاه کردن محتوا
|
| 257 |
+
tokens = count_tokens(content)
|
| 258 |
+
if tokens > max_tokens:
|
| 259 |
+
# اگر یک پیام به تنهایی بیشتر از حد مجاز باشد، آن را حذف کن
|
| 260 |
+
context.pop()
|
| 261 |
+
else:
|
| 262 |
+
# در غیر این صورت، محتوای پیام را کوتاه کن
|
| 263 |
+
while tokens > (max_tokens - (total_tokens - tokens)) and content:
|
| 264 |
+
# حذف کلمات از انتها
|
| 265 |
+
words = content.split()
|
| 266 |
+
if len(words) > 1:
|
| 267 |
+
content = ' '.join(words[:-1])
|
| 268 |
+
else:
|
| 269 |
+
content = content[:-1] if len(content) > 1 else ''
|
| 270 |
+
tokens = count_tokens(content)
|
| 271 |
+
|
| 272 |
+
if content: # اگر محتوایی باقی مانده
|
| 273 |
+
context[-1]['content'] = content
|
| 274 |
+
else: # اگر تمام محتوا حذف شد
|
| 275 |
+
context.pop()
|
| 276 |
+
|
| 277 |
+
save_data()
|
| 278 |
+
|
| 279 |
+
def get_user_context(user_id: int) -> list:
|
| 280 |
+
"""دریافت context کاربر"""
|
| 281 |
+
user_id_str = str(user_id)
|
| 282 |
+
|
| 283 |
+
if user_id_str not in DATA['users']:
|
| 284 |
+
return []
|
| 285 |
+
|
| 286 |
+
return DATA['users'][user_id_str].get('context', [])
|
| 287 |
+
|
| 288 |
+
def clear_user_context(user_id: int):
|
| 289 |
+
"""پاک کردن context کاربر"""
|
| 290 |
+
user_id_str = str(user_id)
|
| 291 |
+
|
| 292 |
+
if user_id_str in DATA['users']:
|
| 293 |
+
if 'context' in DATA['users'][user_id_str]:
|
| 294 |
+
DATA['users'][user_id_str]['context'] = []
|
| 295 |
+
save_data()
|
| 296 |
+
logger.info(f"Context cleared for user {user_id}")
|
| 297 |
+
|
| 298 |
+
def get_context_summary(user_id: int) -> str:
|
| 299 |
+
"""خلاصهای از context کاربر"""
|
| 300 |
+
context = get_user_context(user_id)
|
| 301 |
+
if not context:
|
| 302 |
+
return "بدون تاریخچه"
|
| 303 |
+
|
| 304 |
+
total_messages = len(context)
|
| 305 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 306 |
+
|
| 307 |
+
# نمایش آخرین پیام
|
| 308 |
+
last_message = context[-1] if context else {}
|
| 309 |
+
last_content = last_message.get('content', '')[:50]
|
| 310 |
+
if len(last_message.get('content', '')) > 50:
|
| 311 |
+
last_content += "..."
|
| 312 |
+
|
| 313 |
+
return f"{total_messages} پیام ({total_tokens} توکن) - آخرین: {last_message.get('role', '')}: {last_content}"
|
| 314 |
+
|
| 315 |
+
def get_context_for_api(user_id: int) -> list:
|
| 316 |
+
"""فرمت context برای ارسال به API"""
|
| 317 |
+
context = get_user_context(user_id)
|
| 318 |
+
|
| 319 |
+
# اضافه کردن instruction سیستم به ابتدای context
|
| 320 |
+
api_context = [SYSTEM_INSTRUCTION]
|
| 321 |
+
|
| 322 |
+
# تبدیل پیامهای کاربر به فرمت مورد نیاز API
|
| 323 |
+
for msg in context:
|
| 324 |
+
api_context.append({
|
| 325 |
+
'role': msg['role'],
|
| 326 |
+
'content': msg['content']
|
| 327 |
+
})
|
| 328 |
+
|
| 329 |
+
return api_context
|
| 330 |
+
|
| 331 |
+
def get_context_token_count(user_id: int) -> int:
|
| 332 |
+
"""تعداد کل توکنهای context کاربر"""
|
| 333 |
+
context = get_user_context(user_id)
|
| 334 |
+
return sum(count_tokens(msg['content']) for msg in context)
|
| 335 |
+
|
| 336 |
+
# بارگذاری اولیه دادهها در زمان ایمپورت شدن ماژول
|
| 337 |
+
load_data()
|
Version3_Context_Instrunction/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()
|
Version3_Context_Instrunction/main.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# شروع سرویس نگه داشتن ربات فعال
|
| 18 |
+
start_keep_alive()
|
| 19 |
+
|
| 20 |
+
# --- بهبود لاگینگ ---
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
filename=data_manager.LOG_FILE,
|
| 25 |
+
filemode='a'
|
| 26 |
+
)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
with open(data_manager.LOG_FILE, 'a') as f:
|
| 31 |
+
f.write("")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
|
| 34 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 35 |
+
|
| 36 |
+
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
|
| 37 |
+
http_client = httpx.AsyncClient(
|
| 38 |
+
http2=True,
|
| 39 |
+
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
|
| 40 |
+
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# کلاینت OpenAI (HuggingFace)
|
| 44 |
+
client = AsyncOpenAI(
|
| 45 |
+
base_url="https://router.huggingface.co/v1",
|
| 46 |
+
api_key=os.environ["HF_TOKEN"],
|
| 47 |
+
http_client=http_client
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
|
| 51 |
+
user_tasks = {}
|
| 52 |
+
|
| 53 |
+
# --- توابع کمکی برای مدیریت وظایف ---
|
| 54 |
+
def _cleanup_task(task: asyncio.Task, user_id: int):
|
| 55 |
+
if user_id in user_tasks and user_tasks[user_id] == task:
|
| 56 |
+
del user_tasks[user_id]
|
| 57 |
+
logger.info(f"Cleaned up finished task for user {user_id}.")
|
| 58 |
+
try:
|
| 59 |
+
exception = task.exception()
|
| 60 |
+
if exception:
|
| 61 |
+
logger.error(f"Background task for user {user_id} failed: {exception}")
|
| 62 |
+
except asyncio.CancelledError:
|
| 63 |
+
logger.info(f"Task for user {user_id} was cancelled.")
|
| 64 |
+
|
| 65 |
+
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 66 |
+
chat_id = update.effective_chat.id
|
| 67 |
+
user_message = update.message.text
|
| 68 |
+
user_id = update.effective_user.id
|
| 69 |
+
|
| 70 |
+
start_time = time.time()
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 74 |
+
|
| 75 |
+
# دریافت context کاربر (شامل instruction سیستم)
|
| 76 |
+
user_context = data_manager.get_context_for_api(user_id)
|
| 77 |
+
|
| 78 |
+
# اضافه کردن پیام کاربر به context
|
| 79 |
+
data_manager.add_to_user_context(user_id, "user", user_message)
|
| 80 |
+
|
| 81 |
+
# ایجاد لیست پیامها برای API (instruction سیستم در ابتدا قرار دارد)
|
| 82 |
+
messages = user_context
|
| 83 |
+
|
| 84 |
+
logger.info(f"User {user_id} sending {len(messages)} messages to AI (incl. system instruction)")
|
| 85 |
+
|
| 86 |
+
response = await client.chat.completions.create(
|
| 87 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 88 |
+
messages=messages,
|
| 89 |
+
temperature=0.7,
|
| 90 |
+
top_p=0.95,
|
| 91 |
+
stream=False,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
end_time = time.time()
|
| 95 |
+
response_time = end_time - start_time
|
| 96 |
+
data_manager.update_response_stats(response_time)
|
| 97 |
+
|
| 98 |
+
ai_response = response.choices[0].message.content
|
| 99 |
+
|
| 100 |
+
# اضافه کردن پاسخ هوش مصنوعی به context
|
| 101 |
+
data_manager.add_to_user_context(user_id, "assistant", ai_response)
|
| 102 |
+
|
| 103 |
+
await update.message.reply_text(ai_response)
|
| 104 |
+
data_manager.update_user_stats(user_id, update.effective_user)
|
| 105 |
+
|
| 106 |
+
except httpx.TimeoutException:
|
| 107 |
+
logger.warning(f"Request timed out for user {user_id}.")
|
| 108 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 109 |
+
except Exception as e:
|
| 110 |
+
logger.error(f"Error while processing message for user {user_id}: {e}")
|
| 111 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 112 |
+
|
| 113 |
+
# --- هندلرهای اصلی ربات ---
|
| 114 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 115 |
+
user = update.effective_user
|
| 116 |
+
user_id = user.id
|
| 117 |
+
|
| 118 |
+
data_manager.update_user_stats(user_id, user)
|
| 119 |
+
|
| 120 |
+
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
|
| 121 |
+
await update.message.reply_html(
|
| 122 |
+
welcome_msg.format(user_mention=user.mention_html()),
|
| 123 |
+
disable_web_page_preview=True
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 127 |
+
"""پاک کردن تاریخچه چت برای کاربر"""
|
| 128 |
+
user_id = update.effective_user.id
|
| 129 |
+
data_manager.clear_user_context(user_id)
|
| 130 |
+
|
| 131 |
+
await update.message.reply_text(
|
| 132 |
+
"🧹 تاریخچه مکالمه شما پاک شد.\n"
|
| 133 |
+
"از این لحظه مکالمه جدیدی شروع خواهد شد."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 137 |
+
"""نمایش اطلاعات context کاربر"""
|
| 138 |
+
user_id = update.effective_user.id
|
| 139 |
+
context_summary = data_manager.get_context_summary(user_id)
|
| 140 |
+
|
| 141 |
+
await update.message.reply_text(
|
| 142 |
+
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
|
| 143 |
+
f"{context_summary}\n\n"
|
| 144 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 148 |
+
"""نمایش دستورات کمک"""
|
| 149 |
+
help_text = (
|
| 150 |
+
"🤖 **دستورات ربات:**\n\n"
|
| 151 |
+
"🟢 `/start` - شروع کار با ربات\n"
|
| 152 |
+
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
|
| 153 |
+
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
|
| 154 |
+
"🟢 `/help` - نمایش این پیام راهنما\n\n"
|
| 155 |
+
"📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۵۱۲ توکن ذخیره میکند. "
|
| 156 |
+
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
|
| 157 |
+
)
|
| 158 |
+
await update.message.reply_text(help_text, parse_mode='Markdown')
|
| 159 |
+
|
| 160 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 161 |
+
user_id = update.effective_user.id
|
| 162 |
+
|
| 163 |
+
# بررسی مسدود بودن کاربر
|
| 164 |
+
if data_manager.is_user_banned(user_id):
|
| 165 |
+
logger.info(f"Banned user {user_id} tried to send a message.")
|
| 166 |
+
return
|
| 167 |
+
|
| 168 |
+
# بررسی حالت نگهداری (فقط برای کاربران عادی)
|
| 169 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 170 |
+
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
# بررسی کلمات مسدود شده
|
| 174 |
+
if data_manager.contains_blocked_words(update.message.text):
|
| 175 |
+
logger.info(f"User {user_id} sent a message with a blocked word.")
|
| 176 |
+
# میتوانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید
|
| 177 |
+
# await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")
|
| 178 |
+
return
|
| 179 |
+
|
| 180 |
+
if user_id in user_tasks and not user_tasks[user_id].done():
|
| 181 |
+
user_tasks[user_id].cancel()
|
| 182 |
+
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
|
| 183 |
+
|
| 184 |
+
task = asyncio.create_task(_process_user_request(update, context))
|
| 185 |
+
user_tasks[user_id] = task
|
| 186 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
|
| 187 |
+
|
| 188 |
+
def main() -> None:
|
| 189 |
+
token = os.environ.get("BOT_TOKEN")
|
| 190 |
+
if not token:
|
| 191 |
+
logger.error("BOT_TOKEN not set in environment variables!")
|
| 192 |
+
return
|
| 193 |
+
|
| 194 |
+
application = (
|
| 195 |
+
Application.builder()
|
| 196 |
+
.token(token)
|
| 197 |
+
.concurrent_updates(True)
|
| 198 |
+
.build()
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
# هندلرهای کاربران
|
| 202 |
+
application.add_handler(CommandHandler("start", start))
|
| 203 |
+
application.add_handler(CommandHandler("clear", clear_chat))
|
| 204 |
+
application.add_handler(CommandHandler("context", context_info))
|
| 205 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 206 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 207 |
+
|
| 208 |
+
# راهاندازی و ثبت هندلرهای پنل ادمین
|
| 209 |
+
admin_panel.setup_admin_handlers(application)
|
| 210 |
+
|
| 211 |
+
port = int(os.environ.get("PORT", 8443))
|
| 212 |
+
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
|
| 213 |
+
|
| 214 |
+
application.run_webhook(
|
| 215 |
+
listen="0.0.0.0",
|
| 216 |
+
port=port,
|
| 217 |
+
webhook_url=webhook_url,
|
| 218 |
+
url_path="webhook"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|
Version3_Context_Instrunction/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 وارد کنید
|
Version3_Context_Instrunction/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
|
Version3_Context_Instrunction/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)
|
Version4/render-main.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4a5835d671c6ac961bc1d01379c2d55fbf463ea5412d542621ff89699917b454
|
| 3 |
+
size 18487
|
Version4/render-main/STORED.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
Version4/render-main/admin_panel.py
ADDED
|
@@ -0,0 +1,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# --- کتابخانههای جدید برای ویژگیهای اضافه شده ---
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use('Agg') # تنظیم برای استفاده در محیط بدون رابط کاربری گرافیکی
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import tempfile
|
| 20 |
+
import psutil
|
| 21 |
+
import platform
|
| 22 |
+
|
| 23 |
+
# --- سیستم Context هوشمند ---
|
| 24 |
+
try:
|
| 25 |
+
from smart_context import IntelligentContextManager
|
| 26 |
+
HAS_SMART_CONTEXT = True
|
| 27 |
+
except ImportError:
|
| 28 |
+
HAS_SMART_CONTEXT = False
|
| 29 |
+
|
| 30 |
+
# --- تنظیمات ---
|
| 31 |
+
ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
|
| 32 |
+
|
| 33 |
+
# وارد کردن مدیر دادهها
|
| 34 |
+
import data_manager
|
| 35 |
+
|
| 36 |
+
logger = logging.getLogger(__name__)
|
| 37 |
+
|
| 38 |
+
# --- دکوراتور برای دسترسی ادمین ---
|
| 39 |
+
|
| 40 |
+
def admin_only(func):
|
| 41 |
+
"""این دکوراتور تضمین میکند که فقط ادمینها بتوانند دستور را اجرا کنند."""
|
| 42 |
+
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
| 43 |
+
if update.effective_user.id not in ADMIN_IDS:
|
| 44 |
+
await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
|
| 45 |
+
return
|
| 46 |
+
return await func(update, context, *args, **kwargs)
|
| 47 |
+
return wrapped
|
| 48 |
+
|
| 49 |
+
# --- دیکشنری برای مدیران Context هوشمند ---
|
| 50 |
+
smart_context_managers = {}
|
| 51 |
+
|
| 52 |
+
def _get_smart_context_for_user(user_id: int) -> IntelligentContextManager:
|
| 53 |
+
"""دریافت مدیر Context هوشمند برای کاربر"""
|
| 54 |
+
if user_id not in smart_context_managers:
|
| 55 |
+
smart_context_managers[user_id] = IntelligentContextManager(user_id)
|
| 56 |
+
return smart_context_managers[user_id]
|
| 57 |
+
|
| 58 |
+
# --- هندلرهای دستورات ادمین ---
|
| 59 |
+
|
| 60 |
+
@admin_only
|
| 61 |
+
async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 62 |
+
"""نمایش تمام دستورات موجود ادمین."""
|
| 63 |
+
commands_text = (
|
| 64 |
+
"📋 **دستورات ادمین ربات:**\n\n"
|
| 65 |
+
"📊 `/stats` - نمایش آمار ربات\n"
|
| 66 |
+
"📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
|
| 67 |
+
"🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
|
| 68 |
+
"📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامهریزی شده\n"
|
| 69 |
+
"📋 `/list_scheduled` - نمایش لیست ارسالهای برنامهریزی شده\n"
|
| 70 |
+
"🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامهریزی شده\n"
|
| 71 |
+
"🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
|
| 72 |
+
"✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
|
| 73 |
+
"💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
|
| 74 |
+
"ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
|
| 75 |
+
"📝 `/logs` - نمایش آخرین لاگها\n"
|
| 76 |
+
"📂 `/logs_file` - دانلود فایل کامل لاگها\n"
|
| 77 |
+
"👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
|
| 78 |
+
"🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
|
| 79 |
+
"💾 `/backup` - ایجاد نسخه پشتیبان از دادهها\n"
|
| 80 |
+
"📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
|
| 81 |
+
"🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
|
| 82 |
+
"👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
|
| 83 |
+
"👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
|
| 84 |
+
"📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
|
| 85 |
+
"⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
|
| 86 |
+
"🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
|
| 87 |
+
"✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
|
| 88 |
+
"📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
|
| 89 |
+
"💻 `/system_info` - نمایش اطلاعات سیستم\n"
|
| 90 |
+
"🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
|
| 91 |
+
"🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
|
| 92 |
+
"📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
if HAS_SMART_CONTEXT:
|
| 96 |
+
commands_text += (
|
| 97 |
+
"\n🧠 **دستورات Context هوشمند:**\n"
|
| 98 |
+
"🧠 `/smart_stats [آیدی]` - آمار context هوشمند کاربر\n"
|
| 99 |
+
"🔄 `/reset_smart_context [آیدی]` - ریست context هوشمند کاربر\n"
|
| 100 |
+
"📊 `/smart_analytics` - تحلیل کلی context هوشمند\n"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
commands_text += "\n📋 `/commands` - نمایش این لیست دستورات"
|
| 104 |
+
|
| 105 |
+
await update.message.reply_text(commands_text, parse_mode='Markdown')
|
| 106 |
+
|
| 107 |
+
@admin_only
|
| 108 |
+
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 109 |
+
"""آمار ربات را نمایش میدهد."""
|
| 110 |
+
total_users = len(data_manager.DATA['users'])
|
| 111 |
+
total_messages = data_manager.DATA['stats']['total_messages']
|
| 112 |
+
banned_count = len(data_manager.DATA['banned_users'])
|
| 113 |
+
|
| 114 |
+
now = datetime.now()
|
| 115 |
+
active_24h = sum(1 for user in data_manager.DATA['users'].values()
|
| 116 |
+
if 'last_seen' in user and
|
| 117 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
|
| 118 |
+
|
| 119 |
+
active_7d = sum(1 for user in data_manager.DATA['users'].values()
|
| 120 |
+
if 'last_seen' in user and
|
| 121 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
|
| 122 |
+
|
| 123 |
+
active_users = sorted(
|
| 124 |
+
data_manager.DATA['users'].items(),
|
| 125 |
+
key=lambda item: item[1].get('last_seen', ''),
|
| 126 |
+
reverse=True
|
| 127 |
+
)[:5]
|
| 128 |
+
|
| 129 |
+
active_users_text = "\n".join(
|
| 130 |
+
[f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
|
| 131 |
+
for user_id, info in active_users]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# آمار context
|
| 135 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values()
|
| 136 |
+
if user.get('context') and len(user['context']) > 0)
|
| 137 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 138 |
+
|
| 139 |
+
# آمار Context هوشمند
|
| 140 |
+
smart_context_stats = ""
|
| 141 |
+
if HAS_SMART_CONTEXT:
|
| 142 |
+
users_with_smart_context = sum(1 for user in data_manager.DATA['users'].values()
|
| 143 |
+
if user.get('smart_context'))
|
| 144 |
+
smart_context_stats = f"🧠 **کاربران با Context هوشمند:** `{users_with_smart_context}`\n"
|
| 145 |
+
|
| 146 |
+
text = (
|
| 147 |
+
f"📊 **آمار ربات**\n\n"
|
| 148 |
+
f"👥 **تعداد کل کاربران:** `{total_users}`\n"
|
| 149 |
+
f"📝 **تعداد کل پیامها:** `{total_messages}`\n"
|
| 150 |
+
f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
|
| 151 |
+
f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
|
| 152 |
+
f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
|
| 153 |
+
f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
|
| 154 |
+
f"💬 **کل پیامهای context:** `{total_context_messages}`\n"
|
| 155 |
+
f"{smart_context_stats}\n"
|
| 156 |
+
f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
|
| 157 |
+
)
|
| 158 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 159 |
+
|
| 160 |
+
@admin_only
|
| 161 |
+
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 162 |
+
"""یک پیام را به تمام کاربران ارسال میکند."""
|
| 163 |
+
if not context.args:
|
| 164 |
+
await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
|
| 165 |
+
return
|
| 166 |
+
|
| 167 |
+
message_text = " ".join(context.args)
|
| 168 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 169 |
+
total_sent = 0
|
| 170 |
+
total_failed = 0
|
| 171 |
+
|
| 172 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
|
| 173 |
+
|
| 174 |
+
for user_id_str in user_ids:
|
| 175 |
+
try:
|
| 176 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 177 |
+
total_sent += 1
|
| 178 |
+
await asyncio.sleep(0.05)
|
| 179 |
+
except TelegramError as e:
|
| 180 |
+
logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
|
| 181 |
+
total_failed += 1
|
| 182 |
+
|
| 183 |
+
result_text = (
|
| 184 |
+
f"✅ **ارسال همگانی تمام شد**\n\n"
|
| 185 |
+
f"✅ موفق: `{total_sent}`\n"
|
| 186 |
+
f"❌ ناموفق: `{total_failed}`"
|
| 187 |
+
)
|
| 188 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 189 |
+
|
| 190 |
+
@admin_only
|
| 191 |
+
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 192 |
+
"""ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
|
| 193 |
+
if len(context.args) < 3:
|
| 194 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
|
| 195 |
+
"معیارهای موجود: `active_days`, `message_count`, `banned`")
|
| 196 |
+
return
|
| 197 |
+
|
| 198 |
+
criteria = context.args[0].lower()
|
| 199 |
+
value = context.args[1]
|
| 200 |
+
message_text = " ".join(context.args[2:])
|
| 201 |
+
|
| 202 |
+
target_users = []
|
| 203 |
+
|
| 204 |
+
if criteria == "active_days":
|
| 205 |
+
try:
|
| 206 |
+
days = int(value)
|
| 207 |
+
target_users = data_manager.get_active_users(days)
|
| 208 |
+
except ValueError:
|
| 209 |
+
await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
|
| 210 |
+
return
|
| 211 |
+
|
| 212 |
+
elif criteria == "message_count":
|
| 213 |
+
try:
|
| 214 |
+
min_count = int(value)
|
| 215 |
+
target_users = data_manager.get_users_by_message_count(min_count)
|
| 216 |
+
except ValueError:
|
| 217 |
+
await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
|
| 218 |
+
return
|
| 219 |
+
|
| 220 |
+
elif criteria == "banned":
|
| 221 |
+
if value.lower() == "true":
|
| 222 |
+
target_users = list(data_manager.DATA['banned_users'])
|
| 223 |
+
elif value.lower() == "false":
|
| 224 |
+
for user_id in data_manager.DATA['users']:
|
| 225 |
+
if int(user_id) not in data_manager.DATA['banned_users']:
|
| 226 |
+
target_users.append(int(user_id))
|
| 227 |
+
else:
|
| 228 |
+
await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
else:
|
| 232 |
+
await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
if not target_users:
|
| 236 |
+
await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
|
| 240 |
+
|
| 241 |
+
total_sent, total_failed = 0, 0
|
| 242 |
+
for user_id in target_users:
|
| 243 |
+
try:
|
| 244 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 245 |
+
total_sent += 1
|
| 246 |
+
await asyncio.sleep(0.05)
|
| 247 |
+
except TelegramError as e:
|
| 248 |
+
logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
|
| 249 |
+
total_failed += 1
|
| 250 |
+
|
| 251 |
+
result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
|
| 252 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 253 |
+
|
| 254 |
+
@admin_only
|
| 255 |
+
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 256 |
+
"""تنظیم ارسال برنامهریزی شده پیام به همه کاربران."""
|
| 257 |
+
if len(context.args) < 3:
|
| 258 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
|
| 259 |
+
return
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
date_str, time_str = context.args[0], context.args[1]
|
| 263 |
+
message_text = " ".join(context.args[2:])
|
| 264 |
+
|
| 265 |
+
scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
|
| 266 |
+
|
| 267 |
+
if scheduled_time <= datetime.now():
|
| 268 |
+
await update.message.reply_text("⚠️ زمان برنامهریزی شده باید در آینده باشد.")
|
| 269 |
+
return
|
| 270 |
+
|
| 271 |
+
data_manager.DATA['scheduled_broadcasts'].append({
|
| 272 |
+
'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 273 |
+
'message': message_text,
|
| 274 |
+
'status': 'pending'
|
| 275 |
+
})
|
| 276 |
+
data_manager.save_data()
|
| 277 |
+
|
| 278 |
+
await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامهریزی شد.")
|
| 279 |
+
|
| 280 |
+
except ValueError:
|
| 281 |
+
await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
|
| 282 |
+
|
| 283 |
+
@admin_only
|
| 284 |
+
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 285 |
+
"""نمایش لیست ارسالهای برنامهریزی شده."""
|
| 286 |
+
if not data_manager.DATA['scheduled_broadcasts']:
|
| 287 |
+
await update.message.reply_text("هیچ ارسال برنامهریزی شدهای وجود ندارد.")
|
| 288 |
+
return
|
| 289 |
+
|
| 290 |
+
broadcasts_text = "📅 **لیست ارسالهای برنامهریزی شده:**\n\n"
|
| 291 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
|
| 292 |
+
status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
|
| 293 |
+
broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
|
| 294 |
+
|
| 295 |
+
await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
|
| 296 |
+
|
| 297 |
+
@admin_only
|
| 298 |
+
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 299 |
+
"""حذف یک ارسال برنامهریزی شده."""
|
| 300 |
+
if not context.args or not context.args[0].isdigit():
|
| 301 |
+
await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامهریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
|
| 302 |
+
return
|
| 303 |
+
|
| 304 |
+
index = int(context.args[0]) - 1
|
| 305 |
+
|
| 306 |
+
if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
|
| 307 |
+
await update.message.reply_text("⚠️ شماره ارسال برنامهریزی شده نامعتبر است.")
|
| 308 |
+
return
|
| 309 |
+
|
| 310 |
+
removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
|
| 311 |
+
data_manager.save_data()
|
| 312 |
+
|
| 313 |
+
await update.message.reply_text(f"✅ ارسال برنامهریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
|
| 314 |
+
|
| 315 |
+
@admin_only
|
| 316 |
+
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 317 |
+
"""یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع میدهد."""
|
| 318 |
+
if not context.args or not context.args[0].isdigit():
|
| 319 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
|
| 320 |
+
return
|
| 321 |
+
|
| 322 |
+
user_id_to_ban = int(context.args[0])
|
| 323 |
+
|
| 324 |
+
if user_id_to_ban in ADMIN_IDS:
|
| 325 |
+
await update.message.reply_text("🛡️ شما نمیتوانید یک ادمین را مسدود کنید!")
|
| 326 |
+
return
|
| 327 |
+
|
| 328 |
+
if data_manager.is_user_banned(user_id_to_ban):
|
| 329 |
+
await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
|
| 330 |
+
return
|
| 331 |
+
|
| 332 |
+
data_manager.ban_user(user_id_to_ban)
|
| 333 |
+
|
| 334 |
+
# ارسال پیام به کاربر مسدود شده
|
| 335 |
+
try:
|
| 336 |
+
await context.bot.send_message(
|
| 337 |
+
chat_id=user_id_to_ban,
|
| 338 |
+
text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمیتوانید از خدمات ربات استفاده کنید."
|
| 339 |
+
)
|
| 340 |
+
except TelegramError as e:
|
| 341 |
+
logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
|
| 342 |
+
|
| 343 |
+
await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
|
| 344 |
+
|
| 345 |
+
@admin_only
|
| 346 |
+
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 347 |
+
"""مسدودیت یک کاربر را برمیدارد و به او اطلاع میدهد."""
|
| 348 |
+
if not context.args or not context.args[0].isdigit():
|
| 349 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
|
| 350 |
+
return
|
| 351 |
+
|
| 352 |
+
user_id_to_unban = int(context.args[0])
|
| 353 |
+
|
| 354 |
+
if not data_manager.is_user_banned(user_id_to_unban):
|
| 355 |
+
await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شدهها وجود ندارد.")
|
| 356 |
+
return
|
| 357 |
+
|
| 358 |
+
data_manager.unban_user(user_id_to_unban)
|
| 359 |
+
|
| 360 |
+
# ارسال پیام به کاربر برای رفع مسدودیت
|
| 361 |
+
try:
|
| 362 |
+
await context.bot.send_message(
|
| 363 |
+
chat_id=user_id_to_unban,
|
| 364 |
+
text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. میتوانید دوباره از ربات استفاده کنید."
|
| 365 |
+
)
|
| 366 |
+
except TelegramError as e:
|
| 367 |
+
logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
|
| 368 |
+
|
| 369 |
+
await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
|
| 370 |
+
|
| 371 |
+
@admin_only
|
| 372 |
+
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 373 |
+
"""ارسال پیام مستقیم به یک کاربر خاص."""
|
| 374 |
+
if len(context.args) < 2:
|
| 375 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
|
| 376 |
+
return
|
| 377 |
+
|
| 378 |
+
user_id_str = context.args[0]
|
| 379 |
+
if not user_id_str.isdigit():
|
| 380 |
+
await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
|
| 381 |
+
return
|
| 382 |
+
|
| 383 |
+
message_text = " ".join(context.args[1:])
|
| 384 |
+
user_id = int(user_id_str)
|
| 385 |
+
|
| 386 |
+
try:
|
| 387 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 388 |
+
await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
|
| 389 |
+
except TelegramError as e:
|
| 390 |
+
await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
|
| 391 |
+
|
| 392 |
+
@admin_only
|
| 393 |
+
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 394 |
+
"""اطلاعات یک کاربر خاص را نمایش میدهد."""
|
| 395 |
+
if not context.args or not context.args[0].isdigit():
|
| 396 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
|
| 397 |
+
return
|
| 398 |
+
|
| 399 |
+
user_id = int(context.args[0])
|
| 400 |
+
user_info = data_manager.DATA['users'].get(str(user_id))
|
| 401 |
+
|
| 402 |
+
if not user_info:
|
| 403 |
+
await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
|
| 404 |
+
return
|
| 405 |
+
|
| 406 |
+
is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
|
| 407 |
+
|
| 408 |
+
if 'first_seen' in user_info and 'last_seen' in user_info:
|
| 409 |
+
first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
|
| 410 |
+
last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 411 |
+
days_active = max(1, (last_date - first_date).days)
|
| 412 |
+
avg_messages = user_info.get('message_count', 0) / days_active
|
| 413 |
+
else:
|
| 414 |
+
avg_messages = user_info.get('message_count', 0)
|
| 415 |
+
|
| 416 |
+
# اطلاعات context
|
| 417 |
+
context_messages = len(user_info.get('context', []))
|
| 418 |
+
context_tokens = data_manager.get_context_token_count(user_id)
|
| 419 |
+
|
| 420 |
+
# اطلاعات Context هوشمند
|
| 421 |
+
smart_context_info = ""
|
| 422 |
+
if HAS_SMART_CONTEXT and 'smart_context' in user_info:
|
| 423 |
+
smart_data = user_info['smart_context']
|
| 424 |
+
if 'profile' in smart_data:
|
| 425 |
+
interests = smart_data['profile'].get('interests', [])
|
| 426 |
+
if interests:
|
| 427 |
+
smart_context_info = f"\n🧠 **علاقهمندیها:** {', '.join(interests[:3])}"
|
| 428 |
+
|
| 429 |
+
text = (
|
| 430 |
+
f"ℹ️ **اطلاعات کاربر**\n\n"
|
| 431 |
+
f"🆔 **آیدی:** `{user_id}`\n"
|
| 432 |
+
f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
|
| 433 |
+
f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
|
| 434 |
+
f"📊 **تعداد پیامها:** `{user_info.get('message_count', 0)}`\n"
|
| 435 |
+
f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
|
| 436 |
+
f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
|
| 437 |
+
f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
|
| 438 |
+
f"💭 **پیامهای context:** `{context_messages}`\n"
|
| 439 |
+
f"🔢 **توکنهای context:** `{context_tokens}`\n"
|
| 440 |
+
f"🚫 **وضعیت مسدودیت:** {is_banned}"
|
| 441 |
+
f"{smart_context_info}"
|
| 442 |
+
)
|
| 443 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 444 |
+
|
| 445 |
+
@admin_only
|
| 446 |
+
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 447 |
+
"""آخرین خطوط لاگ ربات را ارسال میکند."""
|
| 448 |
+
try:
|
| 449 |
+
with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
|
| 450 |
+
lines = f.readlines()
|
| 451 |
+
last_lines = lines[-30:]
|
| 452 |
+
log_text = "".join(last_lines)
|
| 453 |
+
if not log_text:
|
| 454 |
+
await update.message.reply_text("فایل لاگ خالی است.")
|
| 455 |
+
return
|
| 456 |
+
|
| 457 |
+
if len(log_text) > 4096:
|
| 458 |
+
for i in range(0, len(log_text), 4096):
|
| 459 |
+
await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
|
| 460 |
+
else:
|
| 461 |
+
await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
|
| 462 |
+
|
| 463 |
+
except FileNotFoundError:
|
| 464 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 465 |
+
except Exception as e:
|
| 466 |
+
await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
|
| 467 |
+
|
| 468 |
+
@admin_only
|
| 469 |
+
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 470 |
+
"""فایل کامل لاگ ربات را ارسال میکند."""
|
| 471 |
+
try:
|
| 472 |
+
await update.message.reply_document(
|
| 473 |
+
document=open(data_manager.LOG_FILE, 'rb'),
|
| 474 |
+
caption="📂 فایل کامل لاگهای ربات"
|
| 475 |
+
)
|
| 476 |
+
except FileNotFoundError:
|
| 477 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 478 |
+
except Exception as e:
|
| 479 |
+
await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
|
| 480 |
+
|
| 481 |
+
@admin_only
|
| 482 |
+
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 483 |
+
"""نمایش لیست کامل کاربران با صفحهبندی."""
|
| 484 |
+
users = data_manager.DATA['users']
|
| 485 |
+
|
| 486 |
+
page = 1
|
| 487 |
+
if context.args and context.args[0].isdigit():
|
| 488 |
+
page = int(context.args[0])
|
| 489 |
+
if page < 1: page = 1
|
| 490 |
+
|
| 491 |
+
users_per_page = 20
|
| 492 |
+
total_users = len(users)
|
| 493 |
+
total_pages = (total_users + users_per_page - 1) // users_per_page
|
| 494 |
+
|
| 495 |
+
if page > total_pages: page = total_pages
|
| 496 |
+
|
| 497 |
+
start_idx = (page - 1) * users_per_page
|
| 498 |
+
end_idx = min(start_idx + users_per_page, total_users)
|
| 499 |
+
|
| 500 |
+
sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
|
| 501 |
+
|
| 502 |
+
users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
|
| 503 |
+
|
| 504 |
+
for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
|
| 505 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 506 |
+
username = user_info.get('username', 'N/A')
|
| 507 |
+
first_name = user_info.get('first_name', 'N/A')
|
| 508 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 509 |
+
message_count = user_info.get('message_count', 0)
|
| 510 |
+
context_count = len(user_info.get('context', []))
|
| 511 |
+
|
| 512 |
+
users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
|
| 513 |
+
users_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 514 |
+
users_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 515 |
+
|
| 516 |
+
keyboard = []
|
| 517 |
+
if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
|
| 518 |
+
if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
|
| 519 |
+
|
| 520 |
+
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
|
| 521 |
+
await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
|
| 522 |
+
|
| 523 |
+
@admin_only
|
| 524 |
+
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 525 |
+
"""جستجوی کاربر بر اساس نام یا نام کاربری."""
|
| 526 |
+
if not context.args:
|
| 527 |
+
await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
|
| 528 |
+
return
|
| 529 |
+
|
| 530 |
+
search_term = " ".join(context.args).lower()
|
| 531 |
+
users = data_manager.DATA['users']
|
| 532 |
+
|
| 533 |
+
matching_users = []
|
| 534 |
+
for user_id, user_info in users.items():
|
| 535 |
+
# استفاده از (value or '') برای جلوگیری از خطا در صورت وجود None
|
| 536 |
+
first_name = (user_info.get('first_name') or '').lower()
|
| 537 |
+
username = (user_info.get('username') or '').lower()
|
| 538 |
+
|
| 539 |
+
if search_term in first_name or search_term in username:
|
| 540 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 541 |
+
matching_users.append((user_id, user_info, is_banned))
|
| 542 |
+
|
| 543 |
+
if not matching_users:
|
| 544 |
+
await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
|
| 545 |
+
return
|
| 546 |
+
|
| 547 |
+
results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
|
| 548 |
+
|
| 549 |
+
for user_id, user_info, is_banned in matching_users:
|
| 550 |
+
username_display = user_info.get('username', 'N/A')
|
| 551 |
+
first_name_display = user_info.get('first_name', 'N/A')
|
| 552 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 553 |
+
message_count = user_info.get('message_count', 0)
|
| 554 |
+
context_count = len(user_info.get('context', []))
|
| 555 |
+
|
| 556 |
+
results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
|
| 557 |
+
results_text += f" 📝 پیامها: `{message_count}` | 💭 context: `{context_count}`\n"
|
| 558 |
+
results_text += f" ⏰ آخرین فعالیت: `{last_seen}`\n\n"
|
| 559 |
+
|
| 560 |
+
await update.message.reply_text(results_text, parse_mode='Markdown')
|
| 561 |
+
|
| 562 |
+
@admin_only
|
| 563 |
+
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 564 |
+
"""ایجاد نسخه پشتیبان از دادههای ربات."""
|
| 565 |
+
try:
|
| 566 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 567 |
+
backup_file = f"bot_backup_{timestamp}.json"
|
| 568 |
+
|
| 569 |
+
data_to_backup = data_manager.DATA.copy()
|
| 570 |
+
data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
|
| 571 |
+
|
| 572 |
+
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 573 |
+
json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
|
| 574 |
+
|
| 575 |
+
await update.message.reply_document(
|
| 576 |
+
document=open(backup_file, 'rb'),
|
| 577 |
+
caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
logger.info(f"Backup created: {backup_file}")
|
| 581 |
+
os.remove(backup_file) # حذف فایل پس از ارسال
|
| 582 |
+
except Exception as e:
|
| 583 |
+
await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
|
| 584 |
+
logger.error(f"Error creating backup: {e}")
|
| 585 |
+
|
| 586 |
+
@admin_only
|
| 587 |
+
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 588 |
+
"""ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
|
| 589 |
+
users = data_manager.DATA['users']
|
| 590 |
+
|
| 591 |
+
df_data = []
|
| 592 |
+
for user_id, user_info in users.items():
|
| 593 |
+
is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
|
| 594 |
+
context_count = len(user_info.get('context', []))
|
| 595 |
+
context_tokens = data_manager.get_context_token_count(int(user_id))
|
| 596 |
+
|
| 597 |
+
df_data.append({
|
| 598 |
+
'User ID': user_id,
|
| 599 |
+
'First Name': user_info.get('first_name', 'N/A'),
|
| 600 |
+
'Username': user_info.get('username', 'N/A'),
|
| 601 |
+
'Message Count': user_info.get('message_count', 0),
|
| 602 |
+
'Context Messages': context_count,
|
| 603 |
+
'Context Tokens': context_tokens,
|
| 604 |
+
'First Seen': user_info.get('first_seen', 'N/A'),
|
| 605 |
+
'Last Seen': user_info.get('last_seen', 'N/A'),
|
| 606 |
+
'Banned': is_banned
|
| 607 |
+
})
|
| 608 |
+
|
| 609 |
+
df = pd.DataFrame(df_data)
|
| 610 |
+
|
| 611 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
|
| 612 |
+
df.to_csv(f.name, index=False)
|
| 613 |
+
temp_file_path = f.name
|
| 614 |
+
|
| 615 |
+
await update.message.reply_document(
|
| 616 |
+
document=open(temp_file_path, 'rb'),
|
| 617 |
+
caption="📊 فایل CSV اطلاعات کاربران"
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
os.unlink(temp_file_path)
|
| 621 |
+
|
| 622 |
+
@admin_only
|
| 623 |
+
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 624 |
+
"""حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع میدهد."""
|
| 625 |
+
if not context.args or context.args[0].lower() not in ['on', 'off']:
|
| 626 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
|
| 627 |
+
return
|
| 628 |
+
|
| 629 |
+
status = context.args[0].lower()
|
| 630 |
+
|
| 631 |
+
if status == 'on':
|
| 632 |
+
if data_manager.DATA.get('maintenance_mode', False):
|
| 633 |
+
await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
|
| 634 |
+
return
|
| 635 |
+
|
| 636 |
+
data_manager.DATA['maintenance_mode'] = True
|
| 637 |
+
data_manager.save_data()
|
| 638 |
+
|
| 639 |
+
await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاعرسانی به کاربران...")
|
| 640 |
+
|
| 641 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 642 |
+
for user_id_str in user_ids:
|
| 643 |
+
try:
|
| 644 |
+
# به ادمینها پیام ارسال نشود
|
| 645 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 646 |
+
await context.bot.send_message(
|
| 647 |
+
chat_id=int(user_id_str),
|
| 648 |
+
text="🔧 ربات در حال حاضر در حالت بهروزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
|
| 649 |
+
)
|
| 650 |
+
await asyncio.sleep(0.05) # جلوگیری از محدودیت تلگرام
|
| 651 |
+
except TelegramError:
|
| 652 |
+
continue # نادیده گرفتن کاربرانی که ربات را مسدود کردهاند
|
| 653 |
+
|
| 654 |
+
elif status == 'off':
|
| 655 |
+
if not data_manager.DATA.get('maintenance_mode', False):
|
| 656 |
+
await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
|
| 657 |
+
return
|
| 658 |
+
|
| 659 |
+
data_manager.DATA['maintenance_mode'] = False
|
| 660 |
+
data_manager.save_data()
|
| 661 |
+
|
| 662 |
+
await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاعرسانی به کاربران...")
|
| 663 |
+
|
| 664 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 665 |
+
for user_id_str in user_ids:
|
| 666 |
+
try:
|
| 667 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 668 |
+
await context.bot.send_message(
|
| 669 |
+
chat_id=int(user_id_str),
|
| 670 |
+
text="✅ بهروزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! میتوانید دوباره از ربات استفاده کنید."
|
| 671 |
+
)
|
| 672 |
+
await asyncio.sleep(0.05)
|
| 673 |
+
except TelegramError:
|
| 674 |
+
continue
|
| 675 |
+
|
| 676 |
+
@admin_only
|
| 677 |
+
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 678 |
+
"""تنظیم پیام خوشامدگویی جدید."""
|
| 679 |
+
if not context.args:
|
| 680 |
+
await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
|
| 681 |
+
"مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
|
| 682 |
+
return
|
| 683 |
+
|
| 684 |
+
new_message = " ".join(context.args)
|
| 685 |
+
data_manager.DATA['welcome_message'] = new_message
|
| 686 |
+
data_manager.save_data()
|
| 687 |
+
|
| 688 |
+
await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت بهروزرسانی شد.")
|
| 689 |
+
|
| 690 |
+
@admin_only
|
| 691 |
+
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 692 |
+
"""تنظیم پیام خداحافظی جدید."""
|
| 693 |
+
if not context.args:
|
| 694 |
+
await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
|
| 695 |
+
"مثال: `/set_goodbye {user_mention}، خداحافظ!`")
|
| 696 |
+
return
|
| 697 |
+
|
| 698 |
+
new_message = " ".join(context.args)
|
| 699 |
+
data_manager.DATA['goodbye_message'] = new_message
|
| 700 |
+
data_manager.save_data()
|
| 701 |
+
|
| 702 |
+
await update.message.reply_text("✅ پیام خداحافظی با موفقیت بهروزرسانی شد.")
|
| 703 |
+
|
| 704 |
+
@admin_only
|
| 705 |
+
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 706 |
+
"""ایجاد و ارسال نمودار فعالیت کاربران."""
|
| 707 |
+
users = data_manager.DATA['users']
|
| 708 |
+
activity_hours = [0] * 24
|
| 709 |
+
|
| 710 |
+
for user_info in users.values():
|
| 711 |
+
if 'last_seen' in user_info:
|
| 712 |
+
try:
|
| 713 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 714 |
+
activity_hours[last_seen.hour] += 1
|
| 715 |
+
except ValueError:
|
| 716 |
+
continue
|
| 717 |
+
|
| 718 |
+
plt.figure(figsize=(12, 6))
|
| 719 |
+
plt.bar(range(24), activity_hours, color='skyblue')
|
| 720 |
+
plt.title('نمودار فعالیت کاربران بر اساس ساعت')
|
| 721 |
+
plt.xlabel('ساعت')
|
| 722 |
+
plt.ylabel('تعداد کاربران فعال')
|
| 723 |
+
plt.xticks(range(24))
|
| 724 |
+
plt.grid(axis='y', alpha=0.3)
|
| 725 |
+
|
| 726 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
|
| 727 |
+
plt.savefig(f.name, bbox_inches='tight')
|
| 728 |
+
temp_file_path = f.name
|
| 729 |
+
|
| 730 |
+
plt.close()
|
| 731 |
+
|
| 732 |
+
await update.message.reply_photo(
|
| 733 |
+
photo=open(temp_file_path, 'rb'),
|
| 734 |
+
caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
os.unlink(temp_file_path)
|
| 738 |
+
|
| 739 |
+
@admin_only
|
| 740 |
+
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 741 |
+
"""نمایش آمار زمان پاسخگویی ربات."""
|
| 742 |
+
stats = data_manager.DATA['stats']
|
| 743 |
+
await update.message.reply_text(
|
| 744 |
+
"📈 **آمار زمان پاسخگویی ربات**\n\n"
|
| 745 |
+
f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
|
| 746 |
+
f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
|
| 747 |
+
f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
|
| 748 |
+
f"📊 کل پاسخهای ثبت شده: `{stats.get('total_responses', 0)}`"
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
@admin_only
|
| 752 |
+
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 753 |
+
"""افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
|
| 754 |
+
if not context.args:
|
| 755 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 756 |
+
"مثال: `/add_blocked_word کلمه_نامناسب`")
|
| 757 |
+
return
|
| 758 |
+
|
| 759 |
+
word = " ".join(context.args).lower()
|
| 760 |
+
|
| 761 |
+
if word in data_manager.DATA['blocked_words']:
|
| 762 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
|
| 763 |
+
return
|
| 764 |
+
|
| 765 |
+
data_manager.DATA['blocked_words'].append(word)
|
| 766 |
+
data_manager.save_data()
|
| 767 |
+
|
| 768 |
+
await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
|
| 769 |
+
|
| 770 |
+
@admin_only
|
| 771 |
+
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 772 |
+
"""حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
|
| 773 |
+
if not context.args:
|
| 774 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 775 |
+
"مثال: `/remove_blocked_word کلمه_نامناسب`")
|
| 776 |
+
return
|
| 777 |
+
|
| 778 |
+
word = " ".join(context.args).lower()
|
| 779 |
+
|
| 780 |
+
if word not in data_manager.DATA['blocked_words']:
|
| 781 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
|
| 782 |
+
return
|
| 783 |
+
|
| 784 |
+
data_manager.DATA['blocked_words'].remove(word)
|
| 785 |
+
data_manager.save_data()
|
| 786 |
+
|
| 787 |
+
await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
|
| 788 |
+
|
| 789 |
+
@admin_only
|
| 790 |
+
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 791 |
+
"""نمایش لیست کلمات مسدود شده."""
|
| 792 |
+
if not data_manager.DATA['blocked_words']:
|
| 793 |
+
await update.message.reply_text("هیچ کلمه مسدود شدهای در لیست وجود ندارد.")
|
| 794 |
+
return
|
| 795 |
+
|
| 796 |
+
words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
|
| 797 |
+
await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
|
| 798 |
+
|
| 799 |
+
@admin_only
|
| 800 |
+
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 801 |
+
"""نمایش اطلاعات سیستم و منابع."""
|
| 802 |
+
bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
|
| 803 |
+
bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
|
| 804 |
+
uptime = datetime.now() - bot_start_time
|
| 805 |
+
|
| 806 |
+
# محاسبه آمار context
|
| 807 |
+
total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
|
| 808 |
+
users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
|
| 809 |
+
|
| 810 |
+
system_info = (
|
| 811 |
+
f"💻 **اطلاعات سیستم:**\n\n"
|
| 812 |
+
f"🖥️ سیستمعامل: {platform.system()} {platform.release()}\n"
|
| 813 |
+
f"🐍 نسخه پایتون: {platform.python_version()}\n"
|
| 814 |
+
f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
|
| 815 |
+
f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
|
| 816 |
+
f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
|
| 817 |
+
f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
|
| 818 |
+
f"⏱️ زمان اجرای ربات: {uptime}\n"
|
| 819 |
+
f"💭 کاربران با context: {users_with_context}\n"
|
| 820 |
+
f"💬 کل پیامهای context: {total_context_messages}"
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
await update.message.reply_text(system_info, parse_mode='Markdown')
|
| 824 |
+
|
| 825 |
+
@admin_only
|
| 826 |
+
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 827 |
+
"""ریست کردن آمار ربات."""
|
| 828 |
+
if not context.args:
|
| 829 |
+
await update.message.reply_text("⚠️ لطفاً نوع آماری که میخواهید ریست کنید را مشخص کنید.\n"
|
| 830 |
+
"مثال: `/reset_stats messages` یا `/reset_stats all`")
|
| 831 |
+
return
|
| 832 |
+
|
| 833 |
+
stat_type = context.args[0].lower()
|
| 834 |
+
|
| 835 |
+
if stat_type == "messages":
|
| 836 |
+
data_manager.DATA['stats']['total_messages'] = 0
|
| 837 |
+
for user_id in data_manager.DATA['users']:
|
| 838 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 839 |
+
await update.message.reply_text("✅ آمار پیامها با موفقیت ریست شد.")
|
| 840 |
+
|
| 841 |
+
elif stat_type == "all":
|
| 842 |
+
data_manager.DATA['stats'] = {
|
| 843 |
+
'total_messages': 0,
|
| 844 |
+
'total_users': len(data_manager.DATA['users']),
|
| 845 |
+
'avg_response_time': 0,
|
| 846 |
+
'max_response_time': 0,
|
| 847 |
+
'min_response_time': 0,
|
| 848 |
+
'total_responses': 0
|
| 849 |
+
}
|
| 850 |
+
for user_id in data_manager.DATA['users']:
|
| 851 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 852 |
+
await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
|
| 853 |
+
|
| 854 |
+
else:
|
| 855 |
+
await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینههای موجود: messages, all")
|
| 856 |
+
return
|
| 857 |
+
|
| 858 |
+
data_manager.save_data()
|
| 859 |
+
|
| 860 |
+
# --- دستورات مدیریت context ---
|
| 861 |
+
|
| 862 |
+
@admin_only
|
| 863 |
+
async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 864 |
+
"""پاک کردن context یک کاربر"""
|
| 865 |
+
if not context.args or not context.args[0].isdigit():
|
| 866 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
|
| 867 |
+
return
|
| 868 |
+
|
| 869 |
+
user_id = int(context.args[0])
|
| 870 |
+
data_manager.clear_user_context(user_id)
|
| 871 |
+
|
| 872 |
+
# همچنین Context هوشمند را پاک کن
|
| 873 |
+
if HAS_SMART_CONTEXT and user_id in smart_context_managers:
|
| 874 |
+
smart_context_managers[user_id].clear_context()
|
| 875 |
+
|
| 876 |
+
await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")
|
| 877 |
+
|
| 878 |
+
@admin_only
|
| 879 |
+
async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 880 |
+
"""مشاهده context یک کاربر"""
|
| 881 |
+
if not context.args or not context.args[0].isdigit():
|
| 882 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
|
| 883 |
+
return
|
| 884 |
+
|
| 885 |
+
user_id = int(context.args[0])
|
| 886 |
+
user_context = data_manager.get_user_context(user_id)
|
| 887 |
+
|
| 888 |
+
if not user_context:
|
| 889 |
+
await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
|
| 890 |
+
return
|
| 891 |
+
|
| 892 |
+
context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
|
| 893 |
+
total_tokens = 0
|
| 894 |
+
|
| 895 |
+
for i, msg in enumerate(user_context, 1):
|
| 896 |
+
role_emoji = "👤" if msg['role'] == 'user' else "🤖"
|
| 897 |
+
tokens = data_manager.count_tokens(msg['content'])
|
| 898 |
+
total_tokens += tokens
|
| 899 |
+
|
| 900 |
+
# کوتاه کردن متن طولانی
|
| 901 |
+
content_preview = msg['content']
|
| 902 |
+
if len(content_preview) > 100:
|
| 903 |
+
content_preview = content_preview[:100] + "..."
|
| 904 |
+
|
| 905 |
+
context_text += f"{i}. {role_emoji} **{msg['role']}** ({tokens} توکن)\n"
|
| 906 |
+
context_text += f" ⏰ {msg.get('timestamp', 'N/A')}\n"
|
| 907 |
+
context_text += f" 📝 {content_preview}\n\n"
|
| 908 |
+
|
| 909 |
+
context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن"
|
| 910 |
+
|
| 911 |
+
await update.message.reply_text(context_text, parse_mode='Markdown')
|
| 912 |
+
|
| 913 |
+
# --- دستورات Context هوشمند ---
|
| 914 |
+
|
| 915 |
+
@admin_only
|
| 916 |
+
async def admin_smart_context_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 917 |
+
"""نمایش آمار context هوشمند برای کاربران"""
|
| 918 |
+
if not HAS_SMART_CONTEXT:
|
| 919 |
+
await update.message.reply_text("⚠️ سیستم context هوشمند فعال نیست.")
|
| 920 |
+
return
|
| 921 |
+
|
| 922 |
+
if not context.args:
|
| 923 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/smart_stats 123456789`")
|
| 924 |
+
return
|
| 925 |
+
|
| 926 |
+
user_id = int(context.args[0])
|
| 927 |
+
|
| 928 |
+
# بررسی وجود مدیر context
|
| 929 |
+
if user_id not in smart_context_managers:
|
| 930 |
+
smart_context_managers[user_id] = IntelligentContextManager(user_id)
|
| 931 |
+
|
| 932 |
+
smart_context = smart_context_managers[user_id]
|
| 933 |
+
summary = await asyncio.to_thread(smart_context.get_summary)
|
| 934 |
+
|
| 935 |
+
stats_text = (
|
| 936 |
+
f"🧠 **آمار context هوشمند کاربر** `{user_id}`\n\n"
|
| 937 |
+
f"📊 **حافظه:**\n"
|
| 938 |
+
f"• فعال: {summary['working_memory']} پیام\n"
|
| 939 |
+
f"• اخیر: {summary['recent_memory']} پیام\n"
|
| 940 |
+
f"• بلندمدت: {summary['long_term_memory']} پیام\n"
|
| 941 |
+
f"• هسته: {summary['core_memory']} پیام\n\n"
|
| 942 |
+
f"📈 **کارایی:**\n"
|
| 943 |
+
f"• میانگین اهمیت: {summary['average_importance']:.2%}\n"
|
| 944 |
+
f"• فشردهسازی: {summary['compression_ratio']:.2%}\n"
|
| 945 |
+
f"• بازیابی: {summary['retrieval_efficiency']:.2%}\n\n"
|
| 946 |
+
f"🎯 **علاقهمندیها:**\n"
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
interests = summary.get('profile_interests', [])
|
| 950 |
+
if interests:
|
| 951 |
+
stats_text += "\n".join([f"• {interest}" for interest in interests[:10]])
|
| 952 |
+
else:
|
| 953 |
+
stats_text += "هیچ علاقهمندی ثبت نشده است."
|
| 954 |
+
|
| 955 |
+
await update.message.reply_text(stats_text, parse_mode='Markdown')
|
| 956 |
+
|
| 957 |
+
@admin_only
|
| 958 |
+
async def admin_reset_smart_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 959 |
+
"""ریست context هوشمند کاربر"""
|
| 960 |
+
if not HAS_SMART_CONTEXT:
|
| 961 |
+
await update.message.reply_text("⚠️ سیستم context هوشمند فعال نیست.")
|
| 962 |
+
return
|
| 963 |
+
|
| 964 |
+
if not context.args:
|
| 965 |
+
await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/reset_smart_context 123456789`")
|
| 966 |
+
return
|
| 967 |
+
|
| 968 |
+
user_id = int(context.args[0])
|
| 969 |
+
|
| 970 |
+
if user_id in smart_context_managers:
|
| 971 |
+
del smart_context_managers[user_id]
|
| 972 |
+
|
| 973 |
+
# همچنین از data_manager پاک کن
|
| 974 |
+
user_id_str = str(user_id)
|
| 975 |
+
if user_id_str in data_manager.DATA['users']:
|
| 976 |
+
if 'smart_context' in data_manager.DATA['users'][user_id_str]:
|
| 977 |
+
del data_manager.DATA['users'][user_id_str]['smart_context']
|
| 978 |
+
data_manager.save_data()
|
| 979 |
+
|
| 980 |
+
await update.message.reply_text(f"✅ context هوشمند کاربر `{user_id}` با موفقیت ریست شد.")
|
| 981 |
+
|
| 982 |
+
@admin_only
|
| 983 |
+
async def admin_smart_analytics(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 984 |
+
"""تحلیل کلی Context هوشمند"""
|
| 985 |
+
if not HAS_SMART_CONTEXT:
|
| 986 |
+
await update.message.reply_text("⚠️ سیستم context هوشمند فعال نیست.")
|
| 987 |
+
return
|
| 988 |
+
|
| 989 |
+
# جمعآوری آمار از همه کاربران
|
| 990 |
+
total_users_with_smart = 0
|
| 991 |
+
total_memory_nodes = 0
|
| 992 |
+
total_connections = 0
|
| 993 |
+
user_interests = {}
|
| 994 |
+
|
| 995 |
+
for user_id_str, user_data in data_manager.DATA['users'].items():
|
| 996 |
+
if 'smart_context' in user_data:
|
| 997 |
+
total_users_with_smart += 1
|
| 998 |
+
|
| 999 |
+
smart_data = user_data['smart_context']
|
| 1000 |
+
if 'profile' in smart_data:
|
| 1001 |
+
interests = smart_data['profile'].get('interests', [])
|
| 1002 |
+
for interest in interests:
|
| 1003 |
+
user_interests[interest] = user_interests.get(interest, 0) + 1
|
| 1004 |
+
|
| 1005 |
+
# محاسبه رایجترین علاقهمندیها
|
| 1006 |
+
top_interests = sorted(user_interests.items(), key=lambda x: x[1], reverse=True)[:10]
|
| 1007 |
+
|
| 1008 |
+
analytics_text = (
|
| 1009 |
+
"📊 **تحلیل کلی Context هوشمند**\n\n"
|
| 1010 |
+
f"👥 **کاربران با Context هوشمند:** `{total_users_with_smart}`\n"
|
| 1011 |
+
f"📈 **کل کاربران:** `{len(data_manager.DATA['users'])}`\n"
|
| 1012 |
+
f"📊 **نرخ استفاده:** `{(total_users_with_smart / max(len(data_manager.DATA['users']), 1)):.1%}`\n\n"
|
| 1013 |
+
"🎯 **رایجترین علاقهمندیها:**\n"
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
if top_interests:
|
| 1017 |
+
for interest, count in top_interests:
|
| 1018 |
+
analytics_text += f"• {interest}: {count} کاربر\n"
|
| 1019 |
+
else:
|
| 1020 |
+
analytics_text += "هنوز علاقهمندیای ثبت نشده است."
|
| 1021 |
+
|
| 1022 |
+
# اطلاعات سیستم
|
| 1023 |
+
analytics_text += f"\n💻 **وضعیت سیستم:**\n"
|
| 1024 |
+
analytics_text += f"• مدیران فعال در حافظه: `{len(smart_context_managers)}`\n"
|
| 1025 |
+
|
| 1026 |
+
await update.message.reply_text(analytics_text, parse_mode='Markdown')
|
| 1027 |
+
|
| 1028 |
+
# --- هندلر برای دکمههای صفحهبندی ---
|
| 1029 |
+
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 1030 |
+
"""پردازش دکمههای صفحهبندی لیست کاربران."""
|
| 1031 |
+
query = update.callback_query
|
| 1032 |
+
await query.answer()
|
| 1033 |
+
|
| 1034 |
+
if query.data.startswith("users_list:"):
|
| 1035 |
+
page = int(query.data.split(":")[1])
|
| 1036 |
+
context.args = [str(page)]
|
| 1037 |
+
await admin_users_list(update, context)
|
| 1038 |
+
|
| 1039 |
+
# --- تابع برای پردازش ارسالهای برنامهریزی شده ---
|
| 1040 |
+
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
|
| 1041 |
+
"""پردازش ارسالهای برنامهریزی شده و ارسال پیامها در زمان مقرر."""
|
| 1042 |
+
now = datetime.now()
|
| 1043 |
+
broadcasts_to_send_indices = []
|
| 1044 |
+
|
| 1045 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
|
| 1046 |
+
if broadcast['status'] == 'pending':
|
| 1047 |
+
broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
|
| 1048 |
+
if broadcast_time <= now:
|
| 1049 |
+
broadcasts_to_send_indices.append(i)
|
| 1050 |
+
|
| 1051 |
+
if not broadcasts_to_send_indices:
|
| 1052 |
+
return
|
| 1053 |
+
|
| 1054 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 1055 |
+
|
| 1056 |
+
for index in broadcasts_to_send_indices:
|
| 1057 |
+
broadcast = data_manager.DATA['scheduled_broadcasts'][index]
|
| 1058 |
+
message_text = broadcast['message']
|
| 1059 |
+
total_sent, total_failed = 0, 0
|
| 1060 |
+
|
| 1061 |
+
for user_id_str in user_ids:
|
| 1062 |
+
try:
|
| 1063 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 1064 |
+
total_sent += 1
|
| 1065 |
+
await asyncio.sleep(0.05)
|
| 1066 |
+
except TelegramError as e:
|
| 1067 |
+
logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
|
| 1068 |
+
total_failed += 1
|
| 1069 |
+
|
| 1070 |
+
# بهروزرسانی وضعیت ارسال
|
| 1071 |
+
data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
|
| 1072 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
|
| 1073 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
|
| 1074 |
+
data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
|
| 1075 |
+
|
| 1076 |
+
logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
|
| 1077 |
+
|
| 1078 |
+
data_manager.save_data()
|
| 1079 |
+
|
| 1080 |
+
# --- تابع راهاندازی هندلرها ---
|
| 1081 |
+
def setup_admin_handlers(application):
|
| 1082 |
+
"""هندلرهای پنل ادمین را به اپلیکیشن اضافه میکند."""
|
| 1083 |
+
# هندلرهای اصلی
|
| 1084 |
+
application.add_handler(CommandHandler("commands", admin_commands))
|
| 1085 |
+
application.add_handler(CommandHandler("stats", admin_stats))
|
| 1086 |
+
application.add_handler(CommandHandler("broadcast", admin_broadcast))
|
| 1087 |
+
application.add_handler(CommandHandler("ban", admin_ban))
|
| 1088 |
+
application.add_handler(CommandHandler("unban", admin_unban))
|
| 1089 |
+
application.add_handler(CommandHandler("user_info", admin_userinfo))
|
| 1090 |
+
application.add_handler(CommandHandler("logs", admin_logs))
|
| 1091 |
+
application.add_handler(CommandHandler("logs_file", admin_logs_file))
|
| 1092 |
+
application.add_handler(CommandHandler("users_list", admin_users_list))
|
| 1093 |
+
application.add_handler(CommandHandler("user_search", admin_user_search))
|
| 1094 |
+
application.add_handler(CommandHandler("backup", admin_backup))
|
| 1095 |
+
|
| 1096 |
+
# هندلرهای جدید
|
| 1097 |
+
application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
|
| 1098 |
+
application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
|
| 1099 |
+
application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
|
| 1100 |
+
application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
|
| 1101 |
+
application.add_handler(CommandHandler("direct_message", admin_direct_message))
|
| 1102 |
+
application.add_handler(CommandHandler("export_csv", admin_export_csv))
|
| 1103 |
+
application.add_handler(CommandHandler("maintenance", admin_maintenance))
|
| 1104 |
+
application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
|
| 1105 |
+
application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
|
| 1106 |
+
application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
|
| 1107 |
+
application.add_handler(CommandHandler("response_stats", admin_response_stats))
|
| 1108 |
+
application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
|
| 1109 |
+
application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
|
| 1110 |
+
application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
|
| 1111 |
+
application.add_handler(CommandHandler("system_info", admin_system_info))
|
| 1112 |
+
application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
|
| 1113 |
+
|
| 1114 |
+
# هندلرهای مدیریت context
|
| 1115 |
+
application.add_handler(CommandHandler("clear_context", admin_clear_context))
|
| 1116 |
+
application.add_handler(CommandHandler("view_context", admin_view_context))
|
| 1117 |
+
|
| 1118 |
+
# هندلرهای Context هوشمند
|
| 1119 |
+
if HAS_SMART_CONTEXT:
|
| 1120 |
+
application.add_handler(CommandHandler("smart_stats", admin_smart_context_stats))
|
| 1121 |
+
application.add_handler(CommandHandler("reset_smart_context", admin_reset_smart_context))
|
| 1122 |
+
application.add_handler(CommandHandler("smart_analytics", admin_smart_analytics))
|
| 1123 |
+
|
| 1124 |
+
# هندلر برای دکمههای صفحهبندی
|
| 1125 |
+
application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
|
| 1126 |
+
|
| 1127 |
+
# شروع وظیفه دورهای برای بررسی ارسالهای برنامهریزی شده
|
| 1128 |
+
application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
|
| 1129 |
+
|
| 1130 |
+
logger.info("Admin panel handlers have been set up.")
|
Version4/render-main/data_manager.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"banned_users": set(),
|
| 18 |
+
"stats": {
|
| 19 |
+
"total_messages": 0,
|
| 20 |
+
"total_users": 0,
|
| 21 |
+
"avg_response_time": 0.0,
|
| 22 |
+
"max_response_time": 0.0,
|
| 23 |
+
"min_response_time": float('inf'),
|
| 24 |
+
"total_responses": 0
|
| 25 |
+
},
|
| 26 |
+
"welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
|
| 27 |
+
"goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
|
| 28 |
+
"maintenance_mode": False,
|
| 29 |
+
"blocked_words": [],
|
| 30 |
+
"scheduled_broadcasts": [],
|
| 31 |
+
"bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
# تابع برای شمارش توکنها
|
| 37 |
+
def count_tokens(text: str) -> int:
|
| 38 |
+
"""شمارش تعداد توکنهای متن با استفاده از tokenizer"""
|
| 39 |
+
try:
|
| 40 |
+
# استفاده از tokenizer برای gpt-3.5-turbo
|
| 41 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 42 |
+
return len(encoding.encode(text))
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.warning(f"Error counting tokens: {e}, using fallback")
|
| 45 |
+
# تقریب: هر 4 کاراکتر = 1 توکن
|
| 46 |
+
return max(1, len(text) // 4)
|
| 47 |
+
|
| 48 |
+
def load_data():
|
| 49 |
+
"""دادهها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره میکند."""
|
| 50 |
+
global DATA
|
| 51 |
+
try:
|
| 52 |
+
if not os.path.exists(DATA_FILE):
|
| 53 |
+
logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد میشود.")
|
| 54 |
+
save_data()
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
| 58 |
+
loaded_data = json.load(f)
|
| 59 |
+
loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
|
| 60 |
+
|
| 61 |
+
# اطمینان از وجود کلیدهای جدید در فایلهای قدیمی
|
| 62 |
+
if 'blocked_words' not in loaded_data: loaded_data['blocked_words'] = []
|
| 63 |
+
if 'scheduled_broadcasts' not in loaded_data: loaded_data['scheduled_broadcasts'] = []
|
| 64 |
+
if 'maintenance_mode' not in loaded_data: loaded_data['maintenance_mode'] = False
|
| 65 |
+
if 'bot_start_time' not in loaded_data: loaded_data['bot_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 66 |
+
if 'avg_response_time' not in loaded_data['stats']:
|
| 67 |
+
loaded_data['stats']['avg_response_time'] = 0.0
|
| 68 |
+
loaded_data['stats']['max_response_time'] = 0.0
|
| 69 |
+
loaded_data['stats']['min_response_time'] = float('inf')
|
| 70 |
+
loaded_data['stats']['total_responses'] = 0
|
| 71 |
+
|
| 72 |
+
# اطمینان از وجود context برای کاربران قدیمی
|
| 73 |
+
for user_id in loaded_data.get('users', {}):
|
| 74 |
+
if 'context' not in loaded_data['users'][user_id]:
|
| 75 |
+
loaded_data['users'][user_id]['context'] = []
|
| 76 |
+
|
| 77 |
+
DATA.update(loaded_data)
|
| 78 |
+
logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.")
|
| 79 |
+
|
| 80 |
+
except json.JSONDecodeError as e:
|
| 81 |
+
logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 84 |
+
|
| 85 |
+
def save_data():
|
| 86 |
+
"""کش گلوبال دادهها را در فایل JSON ذخیره میکند."""
|
| 87 |
+
global DATA
|
| 88 |
+
try:
|
| 89 |
+
data_to_save = DATA.copy()
|
| 90 |
+
data_to_save['banned_users'] = list(DATA['banned_users'])
|
| 91 |
+
|
| 92 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 93 |
+
json.dump(data_to_save, f, indent=4, ensure_ascii=False)
|
| 94 |
+
logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.")
|
| 95 |
+
except Exception as e:
|
| 96 |
+
logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}")
|
| 97 |
+
|
| 98 |
+
def update_user_stats(user_id: int, user):
|
| 99 |
+
"""آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند."""
|
| 100 |
+
global DATA
|
| 101 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 102 |
+
user_id_str = str(user_id)
|
| 103 |
+
|
| 104 |
+
if user_id_str not in DATA['users']:
|
| 105 |
+
DATA['users'][user_id_str] = {
|
| 106 |
+
'first_name': user.first_name,
|
| 107 |
+
'username': user.username,
|
| 108 |
+
'first_seen': now_str,
|
| 109 |
+
'message_count': 0,
|
| 110 |
+
'context': [] # اضافه کردن context خالی برای کاربر جدید
|
| 111 |
+
}
|
| 112 |
+
DATA['stats']['total_users'] += 1
|
| 113 |
+
logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
|
| 114 |
+
|
| 115 |
+
DATA['users'][user_id_str]['last_seen'] = now_str
|
| 116 |
+
DATA['users'][user_id_str]['message_count'] += 1
|
| 117 |
+
DATA['stats']['total_messages'] += 1
|
| 118 |
+
|
| 119 |
+
save_data()
|
| 120 |
+
|
| 121 |
+
def update_response_stats(response_time: float):
|
| 122 |
+
"""آمار زمان پاسخگویی را بهروز میکند."""
|
| 123 |
+
global DATA
|
| 124 |
+
|
| 125 |
+
if DATA['stats']['total_responses'] == 0:
|
| 126 |
+
DATA['stats']['min_response_time'] = response_time
|
| 127 |
+
|
| 128 |
+
DATA['stats']['total_responses'] += 1
|
| 129 |
+
|
| 130 |
+
# محاسبه میانگین جدید
|
| 131 |
+
current_avg = DATA['stats']['avg_response_time']
|
| 132 |
+
total_responses = DATA['stats']['total_responses']
|
| 133 |
+
new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
|
| 134 |
+
DATA['stats']['avg_response_time'] = new_avg
|
| 135 |
+
|
| 136 |
+
# بهروزرسانی حداکثر و حداقل زمان پاسخگویی
|
| 137 |
+
if response_time > DATA['stats']['max_response_time']:
|
| 138 |
+
DATA['stats']['max_response_time'] = response_time
|
| 139 |
+
|
| 140 |
+
if response_time < DATA['stats']['min_response_time']:
|
| 141 |
+
DATA['stats']['min_response_time'] = response_time
|
| 142 |
+
|
| 143 |
+
save_data()
|
| 144 |
+
|
| 145 |
+
def is_user_banned(user_id: int) -> bool:
|
| 146 |
+
"""بررسی میکند آیا کاربر مسدود شده است یا خیر."""
|
| 147 |
+
return user_id in DATA['banned_users']
|
| 148 |
+
|
| 149 |
+
def ban_user(user_id: int):
|
| 150 |
+
"""کاربر را مسدود کرده و ذخیره میکند."""
|
| 151 |
+
DATA['banned_users'].add(user_id)
|
| 152 |
+
save_data()
|
| 153 |
+
|
| 154 |
+
def unban_user(user_id: int):
|
| 155 |
+
"""مسدودیت کاربر را برداشته و ذخیره میکند."""
|
| 156 |
+
DATA['banned_users'].discard(user_id)
|
| 157 |
+
save_data()
|
| 158 |
+
|
| 159 |
+
def contains_blocked_words(text: str) -> bool:
|
| 160 |
+
"""بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر."""
|
| 161 |
+
if not DATA['blocked_words']:
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
text_lower = text.lower()
|
| 165 |
+
for word in DATA['blocked_words']:
|
| 166 |
+
if word in text_lower:
|
| 167 |
+
return True
|
| 168 |
+
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
def get_active_users(days: int) -> list:
|
| 172 |
+
"""لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند."""
|
| 173 |
+
now = datetime.now()
|
| 174 |
+
cutoff_date = now - timedelta(days=days)
|
| 175 |
+
|
| 176 |
+
active_users = []
|
| 177 |
+
for user_id, user_info in DATA['users'].items():
|
| 178 |
+
if 'last_seen' in user_info:
|
| 179 |
+
try:
|
| 180 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 181 |
+
if last_seen >= cutoff_date:
|
| 182 |
+
active_users.append(int(user_id))
|
| 183 |
+
except ValueError:
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
return active_users
|
| 187 |
+
|
| 188 |
+
def get_users_by_message_count(min_count: int) -> list:
|
| 189 |
+
"""لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند."""
|
| 190 |
+
users = []
|
| 191 |
+
for user_id, user_info in DATA['users'].items():
|
| 192 |
+
if user_info.get('message_count', 0) >= min_count:
|
| 193 |
+
users.append(int(user_id))
|
| 194 |
+
|
| 195 |
+
return users
|
| 196 |
+
|
| 197 |
+
# --- توابع مدیریت context ---
|
| 198 |
+
|
| 199 |
+
def add_to_user_context(user_id: int, role: str, content: str):
|
| 200 |
+
"""اضافه کردن پیام به context کاربر و محدود کردن به 512 توکن"""
|
| 201 |
+
user_id_str = str(user_id)
|
| 202 |
+
|
| 203 |
+
if user_id_str not in DATA['users']:
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
if 'context' not in DATA['users'][user_id_str]:
|
| 207 |
+
DATA['users'][user_id_str]['context'] = []
|
| 208 |
+
|
| 209 |
+
# اضافه کردن پیام جدید
|
| 210 |
+
message = {
|
| 211 |
+
'role': role, # 'user' یا 'assistant'
|
| 212 |
+
'content': content,
|
| 213 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
DATA['users'][user_id_str]['context'].append(message)
|
| 217 |
+
|
| 218 |
+
# محدود کردن context به 512 توکن
|
| 219 |
+
trim_user_context(user_id)
|
| 220 |
+
|
| 221 |
+
save_data()
|
| 222 |
+
|
| 223 |
+
def trim_user_context(user_id: int, max_tokens: int = 512):
|
| 224 |
+
"""کوتاه کردن context کاربر به تعداد توکن مشخص"""
|
| 225 |
+
user_id_str = str(user_id)
|
| 226 |
+
|
| 227 |
+
if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
|
| 228 |
+
return
|
| 229 |
+
|
| 230 |
+
context = DATA['users'][user_id_str]['context']
|
| 231 |
+
|
| 232 |
+
if not context:
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
# محاسبه توکنهای کل
|
| 236 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 237 |
+
|
| 238 |
+
# حذف قدیمیترین پیامها تا زمانی که توکنها زیر حد مجاز باشد
|
| 239 |
+
while total_tokens > max_tokens and len(context) > 1:
|
| 240 |
+
removed_message = context.pop(0) # حذف قدیمیترین پیام
|
| 241 |
+
total_tokens -= count_tokens(removed_message['content'])
|
| 242 |
+
|
| 243 |
+
# اگر هنوز بیشتر از حد مجاز است، از محتوای پیا��ها کم کن
|
| 244 |
+
if total_tokens > max_tokens and context:
|
| 245 |
+
# از آخرین پیام (جدیدترین) شروع به کوتاه کردن کن
|
| 246 |
+
last_message = context[-1]
|
| 247 |
+
content = last_message['content']
|
| 248 |
+
|
| 249 |
+
# کوتاه کردن محتوا
|
| 250 |
+
tokens = count_tokens(content)
|
| 251 |
+
if tokens > max_tokens:
|
| 252 |
+
# اگر یک پیام به تنهایی بیشتر از حد مجاز باشد، آن را حذف کن
|
| 253 |
+
context.pop()
|
| 254 |
+
else:
|
| 255 |
+
# در غیر این صورت، محتوای پیام را کوتاه کن
|
| 256 |
+
while tokens > (max_tokens - (total_tokens - tokens)) and content:
|
| 257 |
+
# حذف کلمات از انتها
|
| 258 |
+
words = content.split()
|
| 259 |
+
if len(words) > 1:
|
| 260 |
+
content = ' '.join(words[:-1])
|
| 261 |
+
else:
|
| 262 |
+
content = content[:-1] if len(content) > 1 else ''
|
| 263 |
+
tokens = count_tokens(content)
|
| 264 |
+
|
| 265 |
+
if content: # اگر محتوایی باقی مانده
|
| 266 |
+
context[-1]['content'] = content
|
| 267 |
+
else: # اگر تمام محتوا حذف شد
|
| 268 |
+
context.pop()
|
| 269 |
+
|
| 270 |
+
save_data()
|
| 271 |
+
|
| 272 |
+
def get_user_context(user_id: int) -> list:
|
| 273 |
+
"""دریافت context کاربر"""
|
| 274 |
+
user_id_str = str(user_id)
|
| 275 |
+
|
| 276 |
+
if user_id_str not in DATA['users']:
|
| 277 |
+
return []
|
| 278 |
+
|
| 279 |
+
return DATA['users'][user_id_str].get('context', [])
|
| 280 |
+
|
| 281 |
+
def clear_user_context(user_id: int):
|
| 282 |
+
"""پاک کردن context کاربر"""
|
| 283 |
+
user_id_str = str(user_id)
|
| 284 |
+
|
| 285 |
+
if user_id_str in DATA['users']:
|
| 286 |
+
if 'context' in DATA['users'][user_id_str]:
|
| 287 |
+
DATA['users'][user_id_str]['context'] = []
|
| 288 |
+
save_data()
|
| 289 |
+
logger.info(f"Context cleared for user {user_id}")
|
| 290 |
+
|
| 291 |
+
def get_context_summary(user_id: int) -> str:
|
| 292 |
+
"""خلاصهای از context کاربر"""
|
| 293 |
+
context = get_user_context(user_id)
|
| 294 |
+
if not context:
|
| 295 |
+
return "بدون تاریخچه"
|
| 296 |
+
|
| 297 |
+
total_messages = len(context)
|
| 298 |
+
total_tokens = sum(count_tokens(msg['content']) for msg in context)
|
| 299 |
+
|
| 300 |
+
# نمایش آخرین پیام
|
| 301 |
+
last_message = context[-1] if context else {}
|
| 302 |
+
last_content = last_message.get('content', '')[:50]
|
| 303 |
+
if len(last_message.get('content', '')) > 50:
|
| 304 |
+
last_content += "..."
|
| 305 |
+
|
| 306 |
+
return f"{total_messages} پیام ({total_tokens} توکن) - آخرین: {last_message.get('role', '')}: {last_content}"
|
| 307 |
+
|
| 308 |
+
def get_context_for_api(user_id: int) -> list:
|
| 309 |
+
"""فرمت context برای ارسال به API"""
|
| 310 |
+
context = get_user_context(user_id)
|
| 311 |
+
|
| 312 |
+
# تبدیل به فرمت مورد نیاز API
|
| 313 |
+
api_context = []
|
| 314 |
+
for msg in context:
|
| 315 |
+
api_context.append({
|
| 316 |
+
'role': msg['role'],
|
| 317 |
+
'content': msg['content']
|
| 318 |
+
})
|
| 319 |
+
|
| 320 |
+
return api_context
|
| 321 |
+
|
| 322 |
+
def get_context_token_count(user_id: int) -> int:
|
| 323 |
+
"""تعداد کل توکنهای context کاربر"""
|
| 324 |
+
context = get_user_context(user_id)
|
| 325 |
+
return sum(count_tokens(msg['content']) for msg in context)
|
| 326 |
+
|
| 327 |
+
# بارگذاری اولیه دادهها در زمان ایمپورت شدن ماژول
|
| 328 |
+
load_data()
|
Version4/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()
|
Version4/render-main/main.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
import asyncio
|
| 6 |
+
import httpx
|
| 7 |
+
import time
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from telegram import Update
|
| 10 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
|
| 11 |
+
from openai import AsyncOpenAI
|
| 12 |
+
from keep_alive import start_keep_alive
|
| 13 |
+
|
| 14 |
+
# وارد کردن مدیر دادهها و پنل ادمین
|
| 15 |
+
import data_manager
|
| 16 |
+
import admin_panel
|
| 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 |
+
# --- سیستم Context هوشمند ---
|
| 52 |
+
try:
|
| 53 |
+
from smart_context import IntelligentContextManager
|
| 54 |
+
HAS_SMART_CONTEXT = True
|
| 55 |
+
logger.info("Smart context module loaded successfully")
|
| 56 |
+
except ImportError as e:
|
| 57 |
+
HAS_SMART_CONTEXT = False
|
| 58 |
+
logger.warning(f"Smart context module not available: {e}. Using basic context.")
|
| 59 |
+
|
| 60 |
+
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
|
| 61 |
+
user_tasks = {}
|
| 62 |
+
|
| 63 |
+
# --- دیکشنری برای مدیران Context هوشمند ---
|
| 64 |
+
smart_context_managers = {}
|
| 65 |
+
|
| 66 |
+
# --- توابع کمکی برای مدیریت وظایف ---
|
| 67 |
+
def _cleanup_task(task: asyncio.Task, user_id: int):
|
| 68 |
+
if user_id in user_tasks and user_tasks[user_id] == task:
|
| 69 |
+
del user_tasks[user_id]
|
| 70 |
+
logger.info(f"Cleaned up finished task for user {user_id}.")
|
| 71 |
+
try:
|
| 72 |
+
exception = task.exception()
|
| 73 |
+
if exception:
|
| 74 |
+
logger.error(f"Background task for user {user_id} failed: {exception}")
|
| 75 |
+
except asyncio.CancelledError:
|
| 76 |
+
logger.info(f"Task for user {user_id} was cancelled.")
|
| 77 |
+
|
| 78 |
+
def _get_or_create_smart_context(user_id: int) -> IntelligentContextManager:
|
| 79 |
+
"""دریافت یا ایجاد مدیر Context هوشمند برای کاربر"""
|
| 80 |
+
if user_id not in smart_context_managers:
|
| 81 |
+
smart_context_managers[user_id] = IntelligentContextManager(user_id)
|
| 82 |
+
return smart_context_managers[user_id]
|
| 83 |
+
|
| 84 |
+
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 85 |
+
chat_id = update.effective_chat.id
|
| 86 |
+
user_message = update.message.text
|
| 87 |
+
user_id = update.effective_user.id
|
| 88 |
+
|
| 89 |
+
start_time = time.time()
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 93 |
+
|
| 94 |
+
# استفاده از Context هوشمند اگر فعال باشد
|
| 95 |
+
if HAS_SMART_CONTEXT:
|
| 96 |
+
smart_context = _get_or_create_smart_context(user_id)
|
| 97 |
+
|
| 98 |
+
# پردازش پیام کاربر با سیستم هوشمند
|
| 99 |
+
await smart_context.process_message("user", user_message)
|
| 100 |
+
|
| 101 |
+
# بازیابی context مرتبط
|
| 102 |
+
retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024)
|
| 103 |
+
|
| 104 |
+
# آمادهسازی پیامها برای API
|
| 105 |
+
messages = await smart_context.get_context_for_api(user_message)
|
| 106 |
+
|
| 107 |
+
logger.info(f"Smart context: {len(messages)} messages retrieved for user {user_id}")
|
| 108 |
+
else:
|
| 109 |
+
# استفاده از سیستم قدیمی
|
| 110 |
+
user_context = data_manager.get_context_for_api(user_id)
|
| 111 |
+
data_manager.add_to_user_context(user_id, "user", user_message)
|
| 112 |
+
messages = user_context.copy()
|
| 113 |
+
messages.append({"role": "user", "content": user_message})
|
| 114 |
+
|
| 115 |
+
# ارسال به API
|
| 116 |
+
response = await client.chat.completions.create(
|
| 117 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 118 |
+
messages=messages,
|
| 119 |
+
temperature=0.7,
|
| 120 |
+
top_p=0.95,
|
| 121 |
+
stream=False,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
end_time = time.time()
|
| 125 |
+
response_time = end_time - start_time
|
| 126 |
+
data_manager.update_response_stats(response_time)
|
| 127 |
+
|
| 128 |
+
ai_response = response.choices[0].message.content
|
| 129 |
+
|
| 130 |
+
# ذخیره پاسخ در سیستم مناسب
|
| 131 |
+
if HAS_SMART_CONTEXT:
|
| 132 |
+
await smart_context.process_message("assistant", ai_response)
|
| 133 |
+
else:
|
| 134 |
+
data_manager.add_to_user_context(user_id, "assistant", ai_response)
|
| 135 |
+
|
| 136 |
+
await update.message.reply_text(ai_response)
|
| 137 |
+
data_manager.update_user_stats(user_id, update.effective_user)
|
| 138 |
+
|
| 139 |
+
except httpx.TimeoutException:
|
| 140 |
+
logger.warning(f"Request timed out for user {user_id}.")
|
| 141 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 142 |
+
except Exception as e:
|
| 143 |
+
logger.error(f"Error while processing message for user {user_id}: {e}")
|
| 144 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 145 |
+
# --- هندلرهای اصلی ربات ---
|
| 146 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 147 |
+
user = update.effective_user
|
| 148 |
+
user_id = user.id
|
| 149 |
+
|
| 150 |
+
data_manager.update_user_stats(user_id, user)
|
| 151 |
+
|
| 152 |
+
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
|
| 153 |
+
await update.message.reply_html(
|
| 154 |
+
welcome_msg.format(user_mention=user.mention_html()),
|
| 155 |
+
disable_web_page_preview=True
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 159 |
+
"""پاک کردن تاریخچه چت برای کاربر"""
|
| 160 |
+
user_id = update.effective_user.id
|
| 161 |
+
|
| 162 |
+
if HAS_SMART_CONTEXT:
|
| 163 |
+
if user_id in smart_context_managers:
|
| 164 |
+
smart_context_managers[user_id].clear_context()
|
| 165 |
+
else:
|
| 166 |
+
data_manager.clear_user_context(user_id)
|
| 167 |
+
|
| 168 |
+
await update.message.reply_text(
|
| 169 |
+
"🧹 تاریخچه مکالمه شما پاک شد.\n"
|
| 170 |
+
"از این لحظه مکالمه جدیدی شروع خواهد شد."
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 174 |
+
"""نمایش اطلاعات context کاربر"""
|
| 175 |
+
user_id = update.effective_user.id
|
| 176 |
+
|
| 177 |
+
if HAS_SMART_CONTEXT:
|
| 178 |
+
if user_id in smart_context_managers:
|
| 179 |
+
summary = smart_context_managers[user_id].get_summary()
|
| 180 |
+
|
| 181 |
+
info_text = (
|
| 182 |
+
"🧠 **وضعیت حافظه هوشمند شما:**\n\n"
|
| 183 |
+
f"📊 **آمار کلی:**\n"
|
| 184 |
+
f"• کل پیامها: {summary['total_messages']}\n"
|
| 185 |
+
f"• حافظه فعال: {summary['working_memory']} پیام\n"
|
| 186 |
+
f"• حافظه بلندمدت: {summary['long_term_memory']} پیام\n"
|
| 187 |
+
f"• حافظه هسته: {summary['core_memory']} پیام\n\n"
|
| 188 |
+
f"🎯 **علاقهمندیها:**\n"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
interests = summary.get('profile_interests', [])
|
| 192 |
+
if interests:
|
| 193 |
+
info_text += "• " + "\n• ".join(interests[:5])
|
| 194 |
+
if len(interests) > 5:
|
| 195 |
+
info_text += f"\n• و {len(interests) - 5} مورد دیگر..."
|
| 196 |
+
else:
|
| 197 |
+
info_text += "هنوز علاقهمندیای ثبت نشده است."
|
| 198 |
+
|
| 199 |
+
info_text += f"\n\n📈 **کارایی:**\n"
|
| 200 |
+
info_text += f"• میانگین اهمیت: {summary['average_importance']:.2%}\n"
|
| 201 |
+
info_text += f"• نرخ فشردهسازی: {summary['compression_ratio']:.2%}\n"
|
| 202 |
+
info_text += f"• کارایی بازیابی: {summary['retrieval_efficiency']:.2%}"
|
| 203 |
+
else:
|
| 204 |
+
info_text = "هنوز context هوشمندی ایجاد نشده است."
|
| 205 |
+
else:
|
| 206 |
+
context_summary = data_manager.get_context_summary(user_id)
|
| 207 |
+
info_text = (
|
| 208 |
+
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
|
| 209 |
+
f"{context_summary}\n\n"
|
| 210 |
+
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
await update.message.reply_text(info_text, parse_mode='Markdown')
|
| 214 |
+
|
| 215 |
+
async def smart_context_status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 216 |
+
"""نمایش وضعیت سیستم Context هوشمند"""
|
| 217 |
+
if not HAS_SMART_CONTEXT:
|
| 218 |
+
await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")
|
| 219 |
+
return
|
| 220 |
+
|
| 221 |
+
user_id = update.effective_user.id
|
| 222 |
+
smart_context = _get_or_create_smart_context(user_id)
|
| 223 |
+
|
| 224 |
+
# دریافت اطلاعات دقیق
|
| 225 |
+
debug_info = smart_context.export_debug_info()
|
| 226 |
+
|
| 227 |
+
status_text = (
|
| 228 |
+
"🤖 **وضعیت سیستم Context هوشمند:**\n\n"
|
| 229 |
+
f"✅ **سیستم فعال:** بله\n"
|
| 230 |
+
f"👤 **کاربر:** {user_id}\n"
|
| 231 |
+
f"📊 **تعداد گرههای حافظه:** {debug_info['memory_graph_size']}\n"
|
| 232 |
+
f"🔗 **اتصالات حافظه:** {debug_info['memory_graph_connections']}\n"
|
| 233 |
+
f"🎯 **تعداد علاقهمندیها:** {debug_info['user_profile']['interests_count']}\n"
|
| 234 |
+
f"⚙️ **تنظیمات مکالمه:** {debug_info['user_profile']['conversation_style']}\n\n"
|
| 235 |
+
"📈 **حافظه لایهای:**\n"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
for layer, size in debug_info['layer_sizes'].items():
|
| 239 |
+
status_text += f"• {layer}: {size} پیام\n"
|
| 240 |
+
|
| 241 |
+
await update.message.reply_text(status_text, parse_mode='Markdown')
|
| 242 |
+
|
| 243 |
+
async def optimize_memory(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 244 |
+
"""بهینهسازی دستی حافظه"""
|
| 245 |
+
if not HAS_SMART_CONTEXT:
|
| 246 |
+
await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")
|
| 247 |
+
return
|
| 248 |
+
|
| 249 |
+
user_id = update.effective_user.id
|
| 250 |
+
|
| 251 |
+
if user_id in smart_context_managers:
|
| 252 |
+
before_stats = smart_context_managers[user_id].export_debug_info()
|
| 253 |
+
|
| 254 |
+
# اجرای بهینهسازی
|
| 255 |
+
smart_context_managers[user_id]._optimize_memory()
|
| 256 |
+
|
| 257 |
+
after_stats = smart_context_managers[user_id].export_debug_info()
|
| 258 |
+
|
| 259 |
+
# محاسبه بهبود
|
| 260 |
+
improvements = []
|
| 261 |
+
for layer in before_stats['layer_sizes'].keys():
|
| 262 |
+
before = before_stats['layer_sizes'][layer]
|
| 263 |
+
after = after_stats['layer_sizes'][layer]
|
| 264 |
+
if before > after:
|
| 265 |
+
improvement = before - after
|
| 266 |
+
improvements.append(f"• {layer}: {improvement} پیام آزاد شد")
|
| 267 |
+
|
| 268 |
+
if improvements:
|
| 269 |
+
improvement_text = "\n".join(improvements)
|
| 270 |
+
message = (
|
| 271 |
+
"✅ **حافظه بهینهسازی شد!**\n\n"
|
| 272 |
+
"📊 **بهبودها:**\n"
|
| 273 |
+
f"{improvement_text}\n\n"
|
| 274 |
+
"🔧 حافظههای غیرضروری پاکسازی شدند و اطلاعات مهم اولویتبندی شدند."
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
message = "✅ حافظه قبلاً بهینه بود. هیچ تغییری اعمال نشد."
|
| 278 |
+
else:
|
| 279 |
+
message = "⚠️ هنوز حافظهای برای بهینهسازی وجود ندارد."
|
| 280 |
+
|
| 281 |
+
await update.message.reply_text(message, parse_mode='Markdown')
|
| 282 |
+
|
| 283 |
+
async def export_context(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 284 |
+
"""صدور دادههای Context"""
|
| 285 |
+
if not HAS_SMART_CONTEXT:
|
| 286 |
+
await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")
|
| 287 |
+
return
|
| 288 |
+
|
| 289 |
+
user_id = update.effective_user.id
|
| 290 |
+
|
| 291 |
+
if user_id not in smart_context_managers:
|
| 292 |
+
await update.message.reply_text("⚠️ هنوز context هوشمندی ایجاد نشده است.")
|
| 293 |
+
return
|
| 294 |
+
|
| 295 |
+
smart_context = smart_context_managers[user_id]
|
| 296 |
+
debug_info = smart_context.export_debug_info()
|
| 297 |
+
|
| 298 |
+
# ذخیره در فایل موقت
|
| 299 |
+
import tempfile
|
| 300 |
+
import json
|
| 301 |
+
|
| 302 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
|
| 303 |
+
json.dump(debug_info, f, indent=4, ensure_ascii=False)
|
| 304 |
+
temp_file_path = f.name
|
| 305 |
+
|
| 306 |
+
await update.message.reply_document(
|
| 307 |
+
document=open(temp_file_path, 'rb'),
|
| 308 |
+
caption=f"📊 دادههای Context هوشمند کاربر {user_id}"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# پاک کردن فایل موقت
|
| 312 |
+
import os
|
| 313 |
+
os.unlink(temp_file_path)
|
| 314 |
+
|
| 315 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 316 |
+
"""نمایش دستورات کمک"""
|
| 317 |
+
base_commands = (
|
| 318 |
+
"🤖 **دستورات اصلی ربات:**\n\n"
|
| 319 |
+
"🟢 `/start` - شروع کار با ربات\n"
|
| 320 |
+
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
|
| 321 |
+
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
|
| 322 |
+
"🟢 `/help` - نمایش این پیام راهنما\n\n"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
smart_commands = ""
|
| 326 |
+
if HAS_SMART_CONTEXT:
|
| 327 |
+
smart_commands = (
|
| 328 |
+
"🧠 **دستورات Context هوشمند:**\n\n"
|
| 329 |
+
"🔷 `/smart_status` - نمایش وضعیت سیستم هوشمند\n"
|
| 330 |
+
"🔷 `/optimize` - بهینهسازی دستی حافظه\n"
|
| 331 |
+
"🔷 `/export_context` - صدور دادههای Context\n\n"
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
note = (
|
| 335 |
+
"📝 **نکته:** ربات تاریخچه مکالمه شما را هوشمندانه مدیریت میکند.\n"
|
| 336 |
+
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
await update.message.reply_text(base_commands + smart_commands + note, parse_mode='Markdown')
|
| 340 |
+
|
| 341 |
+
# main.py - اضافه کردن fallback handler
|
| 342 |
+
|
| 343 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 344 |
+
user_id = update.effective_user.id
|
| 345 |
+
|
| 346 |
+
# بررسی مسدود بودن کاربر
|
| 347 |
+
if data_manager.is_user_banned(user_id):
|
| 348 |
+
logger.info(f"Banned user {user_id} tried to send a message.")
|
| 349 |
+
return
|
| 350 |
+
|
| 351 |
+
# بررسی حالت نگهداری (فقط برای ��اربران عادی)
|
| 352 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 353 |
+
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
|
| 354 |
+
return
|
| 355 |
+
|
| 356 |
+
# بررسی کلمات مسدود شده
|
| 357 |
+
if data_manager.contains_blocked_words(update.message.text):
|
| 358 |
+
logger.info(f"User {user_id} sent a message with a blocked word.")
|
| 359 |
+
return
|
| 360 |
+
|
| 361 |
+
# مدیریت وظایف همزمان با timeout
|
| 362 |
+
if user_id in user_tasks:
|
| 363 |
+
try:
|
| 364 |
+
# بررسی اگر task قبلی هنوز در حال اجرا است
|
| 365 |
+
if not user_tasks[user_id].done():
|
| 366 |
+
# منتظر پایان task قبلی با timeout
|
| 367 |
+
try:
|
| 368 |
+
await asyncio.wait_for(user_tasks[user_id], timeout=5.0)
|
| 369 |
+
except asyncio.TimeoutError:
|
| 370 |
+
logger.warning(f"Previous task for user {user_id} timed out, cancelling...")
|
| 371 |
+
user_tasks[user_id].cancel()
|
| 372 |
+
except Exception as e:
|
| 373 |
+
logger.error(f"Error handling previous task for user {user_id}: {e}")
|
| 374 |
+
|
| 375 |
+
# ایجاد وظیفه جدید با timeout
|
| 376 |
+
task = asyncio.create_task(
|
| 377 |
+
_process_user_request_with_timeout(update, context)
|
| 378 |
+
)
|
| 379 |
+
user_tasks[user_id] = task
|
| 380 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
|
| 381 |
+
|
| 382 |
+
async def _process_user_request_with_timeout(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 383 |
+
"""پردازش درخواست کاربر با timeout"""
|
| 384 |
+
try:
|
| 385 |
+
# اجرا با timeout 30 ثانیه
|
| 386 |
+
await asyncio.wait_for(
|
| 387 |
+
_process_user_request(update, context),
|
| 388 |
+
timeout=30.0
|
| 389 |
+
)
|
| 390 |
+
except asyncio.TimeoutError:
|
| 391 |
+
logger.error(f"Processing timed out for user {update.effective_user.id}")
|
| 392 |
+
await update.message.reply_text("⏱️ پردازش درخواست شما زمان زیادی برد. لطفاً دوباره تلاش کنید.")
|
| 393 |
+
except Exception as e:
|
| 394 |
+
logger.error(f"Unexpected error in task for user {update.effective_user.id}: {e}")
|
| 395 |
+
|
| 396 |
+
def main() -> None:
|
| 397 |
+
token = os.environ.get("BOT_TOKEN")
|
| 398 |
+
if not token:
|
| 399 |
+
logger.error("BOT_TOKEN not set in environment variables!")
|
| 400 |
+
return
|
| 401 |
+
|
| 402 |
+
application = (
|
| 403 |
+
Application.builder()
|
| 404 |
+
.token(token)
|
| 405 |
+
.concurrent_updates(True)
|
| 406 |
+
.build()
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
# هندلرهای کاربران
|
| 410 |
+
application.add_handler(CommandHandler("start", start))
|
| 411 |
+
application.add_handler(CommandHandler("clear", clear_chat))
|
| 412 |
+
application.add_handler(CommandHandler("context", context_info))
|
| 413 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 414 |
+
|
| 415 |
+
# هندلرهای Context هوشمند
|
| 416 |
+
if HAS_SMART_CONTEXT:
|
| 417 |
+
application.add_handler(CommandHandler("smart_status", smart_context_status))
|
| 418 |
+
application.add_handler(CommandHandler("optimize", optimize_memory))
|
| 419 |
+
application.add_handler(CommandHandler("export_context", export_context))
|
| 420 |
+
|
| 421 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 422 |
+
|
| 423 |
+
# راهاندازی و ثبت هندلرهای پنل ادمین
|
| 424 |
+
admin_panel.setup_admin_handlers(application)
|
| 425 |
+
|
| 426 |
+
# تنظیمات Webhook برای Render
|
| 427 |
+
port = int(os.environ.get("PORT", 8443))
|
| 428 |
+
webhook_url = os.environ.get("RENDER_EXTERNAL_URL", "")
|
| 429 |
+
|
| 430 |
+
if webhook_url:
|
| 431 |
+
# حالت Webhook (برای Render)
|
| 432 |
+
application.run_webhook(
|
| 433 |
+
listen="0.0.0.0",
|
| 434 |
+
port=port,
|
| 435 |
+
webhook_url=webhook_url + "/webhook",
|
| 436 |
+
url_path="webhook",
|
| 437 |
+
drop_pending_updates=True
|
| 438 |
+
)
|
| 439 |
+
logger.info(f"Bot running in webhook mode on port {port}")
|
| 440 |
+
else:
|
| 441 |
+
# حالت Polling (برای توسعه)
|
| 442 |
+
application.run_polling(drop_pending_updates=True)
|
| 443 |
+
logger.info("Bot running in polling mode")
|
| 444 |
+
|
| 445 |
+
if __name__ == "__main__":
|
| 446 |
+
main()
|
Version4/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 وارد کنید
|
Version4/render-main/requirements.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 12 |
+
sentence-transformers
|
| 13 |
+
numpy
|
| 14 |
+
scikit-learn
|
| 15 |
+
scipy
|
| 16 |
+
nest-asyncio
|
Version4/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)
|
Version4/render-main/smart_context.py
ADDED
|
@@ -0,0 +1,1180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
}
|
render-main/admin_panel.py
ADDED
|
@@ -0,0 +1,880 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# --- کتابخانههای جدید برای ویژگیهای اضافه شده ---
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use('Agg') # تنظیم برای استفاده در محیط بدون رابط کاربری گرافیکی
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import tempfile
|
| 20 |
+
import psutil
|
| 21 |
+
import platform
|
| 22 |
+
|
| 23 |
+
# --- تنظیمات ---
|
| 24 |
+
ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []
|
| 25 |
+
|
| 26 |
+
# وارد کردن مدیر دادهها
|
| 27 |
+
import data_manager
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# --- دکوراتور برای دسترسی ادمین ---
|
| 32 |
+
|
| 33 |
+
def admin_only(func):
|
| 34 |
+
"""این دکوراتور تضمین میکند که فقط ادمینها بتوانند دستور را اجرا کنند."""
|
| 35 |
+
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
| 36 |
+
if update.effective_user.id not in ADMIN_IDS:
|
| 37 |
+
await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
|
| 38 |
+
return
|
| 39 |
+
return await func(update, context, *args, **kwargs)
|
| 40 |
+
return wrapped
|
| 41 |
+
|
| 42 |
+
# --- هندلرهای دستورات ادمین ---
|
| 43 |
+
|
| 44 |
+
@admin_only
|
| 45 |
+
async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 46 |
+
"""نمایش تمام دستورات موجود ادمین."""
|
| 47 |
+
commands_text = (
|
| 48 |
+
"📋 **دستورات ادمین ربات:**\n\n"
|
| 49 |
+
"📊 `/stats` - نمایش آمار ربات\n"
|
| 50 |
+
"📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
|
| 51 |
+
"🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
|
| 52 |
+
"📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامهریزی شده\n"
|
| 53 |
+
"📋 `/list_scheduled` - نمایش لیست ارسالهای برنامهریزی شده\n"
|
| 54 |
+
"🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامهریزی شده\n"
|
| 55 |
+
"🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
|
| 56 |
+
"✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
|
| 57 |
+
"💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
|
| 58 |
+
"ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
|
| 59 |
+
"📝 `/logs` - نمایش آخرین لاگها\n"
|
| 60 |
+
"📂 `/logs_file` - دانلود فایل کامل لاگها\n"
|
| 61 |
+
"👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
|
| 62 |
+
"🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
|
| 63 |
+
"💾 `/backup` - ایجاد نسخه پشتیبان از دادهها\n"
|
| 64 |
+
"📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
|
| 65 |
+
"🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
|
| 66 |
+
"👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
|
| 67 |
+
"👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
|
| 68 |
+
"📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
|
| 69 |
+
"⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
|
| 70 |
+
"🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
|
| 71 |
+
"✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
|
| 72 |
+
"📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
|
| 73 |
+
"💻 `/system_info` - نمایش اطلاعات سیستم\n"
|
| 74 |
+
"🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
|
| 75 |
+
"📋 `/commands` - نمایش این لیست دستورات"
|
| 76 |
+
)
|
| 77 |
+
await update.message.reply_text(commands_text, parse_mode='Markdown')
|
| 78 |
+
|
| 79 |
+
@admin_only
|
| 80 |
+
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 81 |
+
"""آمار ربات را نمایش میدهد."""
|
| 82 |
+
total_users = len(data_manager.DATA['users'])
|
| 83 |
+
total_messages = data_manager.DATA['stats']['total_messages']
|
| 84 |
+
banned_count = len(data_manager.DATA['banned_users'])
|
| 85 |
+
|
| 86 |
+
now = datetime.now()
|
| 87 |
+
active_24h = sum(1 for user in data_manager.DATA['users'].values()
|
| 88 |
+
if 'last_seen' in user and
|
| 89 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
|
| 90 |
+
|
| 91 |
+
active_7d = sum(1 for user in data_manager.DATA['users'].values()
|
| 92 |
+
if 'last_seen' in user and
|
| 93 |
+
datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))
|
| 94 |
+
|
| 95 |
+
active_users = sorted(
|
| 96 |
+
data_manager.DATA['users'].items(),
|
| 97 |
+
key=lambda item: item[1].get('last_seen', ''),
|
| 98 |
+
reverse=True
|
| 99 |
+
)[:5]
|
| 100 |
+
|
| 101 |
+
active_users_text = "\n".join(
|
| 102 |
+
[f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
|
| 103 |
+
for user_id, info in active_users]
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
text = (
|
| 107 |
+
f"📊 **آمار ربات**\n\n"
|
| 108 |
+
f"👥 **تعداد کل کاربران:** `{total_users}`\n"
|
| 109 |
+
f"📝 **تعداد کل پیامها:** `{total_messages}`\n"
|
| 110 |
+
f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
|
| 111 |
+
f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
|
| 112 |
+
f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n\n"
|
| 113 |
+
f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
|
| 114 |
+
)
|
| 115 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 116 |
+
|
| 117 |
+
@admin_only
|
| 118 |
+
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 119 |
+
"""یک پیام را به تمام کاربران ارسال میکند."""
|
| 120 |
+
if not context.args:
|
| 121 |
+
await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
message_text = " ".join(context.args)
|
| 125 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 126 |
+
total_sent = 0
|
| 127 |
+
total_failed = 0
|
| 128 |
+
|
| 129 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")
|
| 130 |
+
|
| 131 |
+
for user_id_str in user_ids:
|
| 132 |
+
try:
|
| 133 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 134 |
+
total_sent += 1
|
| 135 |
+
await asyncio.sleep(0.05)
|
| 136 |
+
except TelegramError as e:
|
| 137 |
+
logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
|
| 138 |
+
total_failed += 1
|
| 139 |
+
|
| 140 |
+
result_text = (
|
| 141 |
+
f"✅ **ارسال همگانی تمام شد**\n\n"
|
| 142 |
+
f"✅ موفق: `{total_sent}`\n"
|
| 143 |
+
f"❌ ناموفق: `{total_failed}`"
|
| 144 |
+
)
|
| 145 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 146 |
+
|
| 147 |
+
@admin_only
|
| 148 |
+
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 149 |
+
"""ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
|
| 150 |
+
if len(context.args) < 3:
|
| 151 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
|
| 152 |
+
"معیارهای موجود: `active_days`, `message_count`, `banned`")
|
| 153 |
+
return
|
| 154 |
+
|
| 155 |
+
criteria = context.args[0].lower()
|
| 156 |
+
value = context.args[1]
|
| 157 |
+
message_text = " ".join(context.args[2:])
|
| 158 |
+
|
| 159 |
+
target_users = []
|
| 160 |
+
|
| 161 |
+
if criteria == "active_days":
|
| 162 |
+
try:
|
| 163 |
+
days = int(value)
|
| 164 |
+
target_users = data_manager.get_active_users(days)
|
| 165 |
+
except ValueError:
|
| 166 |
+
await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
elif criteria == "message_count":
|
| 170 |
+
try:
|
| 171 |
+
min_count = int(value)
|
| 172 |
+
target_users = data_manager.get_users_by_message_count(min_count)
|
| 173 |
+
except ValueError:
|
| 174 |
+
await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
elif criteria == "banned":
|
| 178 |
+
if value.lower() == "true":
|
| 179 |
+
target_users = list(data_manager.DATA['banned_users'])
|
| 180 |
+
elif value.lower() == "false":
|
| 181 |
+
for user_id in data_manager.DATA['users']:
|
| 182 |
+
if int(user_id) not in data_manager.DATA['banned_users']:
|
| 183 |
+
target_users.append(int(user_id))
|
| 184 |
+
else:
|
| 185 |
+
await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
else:
|
| 189 |
+
await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
|
| 190 |
+
return
|
| 191 |
+
|
| 192 |
+
if not target_users:
|
| 193 |
+
await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
|
| 194 |
+
return
|
| 195 |
+
|
| 196 |
+
await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
|
| 197 |
+
|
| 198 |
+
total_sent, total_failed = 0, 0
|
| 199 |
+
for user_id in target_users:
|
| 200 |
+
try:
|
| 201 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 202 |
+
total_sent += 1
|
| 203 |
+
await asyncio.sleep(0.05)
|
| 204 |
+
except TelegramError as e:
|
| 205 |
+
logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
|
| 206 |
+
total_failed += 1
|
| 207 |
+
|
| 208 |
+
result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
|
| 209 |
+
await update.message.reply_text(result_text, parse_mode='Markdown')
|
| 210 |
+
|
| 211 |
+
@admin_only
|
| 212 |
+
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 213 |
+
"""تنظیم ارسال برنامهریزی شده پیام به همه کاربران."""
|
| 214 |
+
if len(context.args) < 3:
|
| 215 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
date_str, time_str = context.args[0], context.args[1]
|
| 220 |
+
message_text = " ".join(context.args[2:])
|
| 221 |
+
|
| 222 |
+
scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
|
| 223 |
+
|
| 224 |
+
if scheduled_time <= datetime.now():
|
| 225 |
+
await update.message.reply_text("⚠️ زمان برنامهریزی شده باید در آینده باشد.")
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
data_manager.DATA['scheduled_broadcasts'].append({
|
| 229 |
+
'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 230 |
+
'message': message_text,
|
| 231 |
+
'status': 'pending'
|
| 232 |
+
})
|
| 233 |
+
data_manager.save_data()
|
| 234 |
+
|
| 235 |
+
await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامهریزی شد.")
|
| 236 |
+
|
| 237 |
+
except ValueError:
|
| 238 |
+
await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")
|
| 239 |
+
|
| 240 |
+
@admin_only
|
| 241 |
+
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 242 |
+
"""نمایش لیست ارسالهای برنامهریزی شده."""
|
| 243 |
+
if not data_manager.DATA['scheduled_broadcasts']:
|
| 244 |
+
await update.message.reply_text("هیچ ارسال برنامهریزی شدهای وجود ندارد.")
|
| 245 |
+
return
|
| 246 |
+
|
| 247 |
+
broadcasts_text = "📅 **لیست ارسالهای برنامهریزی شده:**\n\n"
|
| 248 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
|
| 249 |
+
status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
|
| 250 |
+
broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
|
| 251 |
+
|
| 252 |
+
await update.message.reply_text(broadcasts_text, parse_mode='Markdown')
|
| 253 |
+
|
| 254 |
+
@admin_only
|
| 255 |
+
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 256 |
+
"""حذف یک ارسال برنامهریزی شده."""
|
| 257 |
+
if not context.args or not context.args[0].isdigit():
|
| 258 |
+
await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامهریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
|
| 259 |
+
return
|
| 260 |
+
|
| 261 |
+
index = int(context.args[0]) - 1
|
| 262 |
+
|
| 263 |
+
if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
|
| 264 |
+
await update.message.reply_text("⚠️ شماره ارسال برنامهریزی شده نامعتبر است.")
|
| 265 |
+
return
|
| 266 |
+
|
| 267 |
+
removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
|
| 268 |
+
data_manager.save_data()
|
| 269 |
+
|
| 270 |
+
await update.message.reply_text(f"✅ ارسال برنامهریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")
|
| 271 |
+
|
| 272 |
+
@admin_only
|
| 273 |
+
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 274 |
+
"""یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع میدهد."""
|
| 275 |
+
if not context.args or not context.args[0].isdigit():
|
| 276 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
|
| 277 |
+
return
|
| 278 |
+
|
| 279 |
+
user_id_to_ban = int(context.args[0])
|
| 280 |
+
|
| 281 |
+
if user_id_to_ban in ADMIN_IDS:
|
| 282 |
+
await update.message.reply_text("🛡️ شما نمیتوانید یک ادمین را مسدود کنید!")
|
| 283 |
+
return
|
| 284 |
+
|
| 285 |
+
if data_manager.is_user_banned(user_id_to_ban):
|
| 286 |
+
await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
|
| 287 |
+
return
|
| 288 |
+
|
| 289 |
+
data_manager.ban_user(user_id_to_ban)
|
| 290 |
+
|
| 291 |
+
# ارسال پیام به کاربر مسدود شده
|
| 292 |
+
try:
|
| 293 |
+
await context.bot.send_message(
|
| 294 |
+
chat_id=user_id_to_ban,
|
| 295 |
+
text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمیتوانید از خدمات ربات استفاده کنید."
|
| 296 |
+
)
|
| 297 |
+
except TelegramError as e:
|
| 298 |
+
logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")
|
| 299 |
+
|
| 300 |
+
await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')
|
| 301 |
+
|
| 302 |
+
@admin_only
|
| 303 |
+
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 304 |
+
"""مسدودیت یک کاربر را برمیدارد و به او اطلاع میدهد."""
|
| 305 |
+
if not context.args or not context.args[0].isdigit():
|
| 306 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
|
| 307 |
+
return
|
| 308 |
+
|
| 309 |
+
user_id_to_unban = int(context.args[0])
|
| 310 |
+
|
| 311 |
+
if not data_manager.is_user_banned(user_id_to_unban):
|
| 312 |
+
await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شدهها وجود ندارد.")
|
| 313 |
+
return
|
| 314 |
+
|
| 315 |
+
data_manager.unban_user(user_id_to_unban)
|
| 316 |
+
|
| 317 |
+
# ارسال پیام به کاربر برای رفع مسدودیت
|
| 318 |
+
try:
|
| 319 |
+
await context.bot.send_message(
|
| 320 |
+
chat_id=user_id_to_unban,
|
| 321 |
+
text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. میتوانید دوباره از ربات استفاده کنید."
|
| 322 |
+
)
|
| 323 |
+
except TelegramError as e:
|
| 324 |
+
logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")
|
| 325 |
+
|
| 326 |
+
await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')
|
| 327 |
+
|
| 328 |
+
@admin_only
|
| 329 |
+
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 330 |
+
"""ارسال پیام مستقیم به یک کاربر خاص."""
|
| 331 |
+
if len(context.args) < 2:
|
| 332 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
|
| 333 |
+
return
|
| 334 |
+
|
| 335 |
+
user_id_str = context.args[0]
|
| 336 |
+
if not user_id_str.isdigit():
|
| 337 |
+
await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
|
| 338 |
+
return
|
| 339 |
+
|
| 340 |
+
message_text = " ".join(context.args[1:])
|
| 341 |
+
user_id = int(user_id_str)
|
| 342 |
+
|
| 343 |
+
try:
|
| 344 |
+
await context.bot.send_message(chat_id=user_id, text=message_text)
|
| 345 |
+
await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
|
| 346 |
+
except TelegramError as e:
|
| 347 |
+
await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")
|
| 348 |
+
|
| 349 |
+
@admin_only
|
| 350 |
+
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 351 |
+
"""اطلاعات یک کاربر خاص را نمایش میدهد."""
|
| 352 |
+
if not context.args or not context.args[0].isdigit():
|
| 353 |
+
await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
|
| 354 |
+
return
|
| 355 |
+
|
| 356 |
+
user_id = int(context.args[0])
|
| 357 |
+
user_info = data_manager.DATA['users'].get(str(user_id))
|
| 358 |
+
|
| 359 |
+
if not user_info:
|
| 360 |
+
await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
|
| 361 |
+
return
|
| 362 |
+
|
| 363 |
+
is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
|
| 364 |
+
|
| 365 |
+
if 'first_seen' in user_info and 'last_seen' in user_info:
|
| 366 |
+
first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
|
| 367 |
+
last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 368 |
+
days_active = max(1, (last_date - first_date).days)
|
| 369 |
+
avg_messages = user_info.get('message_count', 0) / days_active
|
| 370 |
+
else:
|
| 371 |
+
avg_messages = user_info.get('message_count', 0)
|
| 372 |
+
|
| 373 |
+
text = (
|
| 374 |
+
f"ℹ️ **اطلاعات کاربر**\n\n"
|
| 375 |
+
f"🆔 **آیدی:** `{user_id}`\n"
|
| 376 |
+
f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
|
| 377 |
+
f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
|
| 378 |
+
f"📊 **تعداد پیامها:** `{user_info.get('message_count', 0)}`\n"
|
| 379 |
+
f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
|
| 380 |
+
f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
|
| 381 |
+
f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
|
| 382 |
+
f"🚫 **وضعیت مسدودیت:** {is_banned}"
|
| 383 |
+
)
|
| 384 |
+
await update.message.reply_text(text, parse_mode='Markdown')
|
| 385 |
+
|
| 386 |
+
@admin_only
|
| 387 |
+
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 388 |
+
"""آخرین خطوط لاگ ربات را ارسال میکند."""
|
| 389 |
+
try:
|
| 390 |
+
with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
|
| 391 |
+
lines = f.readlines()
|
| 392 |
+
last_lines = lines[-30:]
|
| 393 |
+
log_text = "".join(last_lines)
|
| 394 |
+
if not log_text:
|
| 395 |
+
await update.message.reply_text("فایل لاگ خالی است.")
|
| 396 |
+
return
|
| 397 |
+
|
| 398 |
+
if len(log_text) > 4096:
|
| 399 |
+
for i in range(0, len(log_text), 4096):
|
| 400 |
+
await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
|
| 401 |
+
else:
|
| 402 |
+
await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')
|
| 403 |
+
|
| 404 |
+
except FileNotFoundError:
|
| 405 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 406 |
+
except Exception as e:
|
| 407 |
+
await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")
|
| 408 |
+
|
| 409 |
+
@admin_only
|
| 410 |
+
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 411 |
+
"""فایل کامل لاگ ربات را ارسال میکند."""
|
| 412 |
+
try:
|
| 413 |
+
await update.message.reply_document(
|
| 414 |
+
document=open(data_manager.LOG_FILE, 'rb'),
|
| 415 |
+
caption="📂 فایل کامل لاگهای ربات"
|
| 416 |
+
)
|
| 417 |
+
except FileNotFoundError:
|
| 418 |
+
await update.message.reply_text("فایل لاگ یافت نشد.")
|
| 419 |
+
except Exception as e:
|
| 420 |
+
await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")
|
| 421 |
+
|
| 422 |
+
@admin_only
|
| 423 |
+
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 424 |
+
"""نمایش لیست کامل کاربران با صفحهبندی."""
|
| 425 |
+
users = data_manager.DATA['users']
|
| 426 |
+
|
| 427 |
+
page = 1
|
| 428 |
+
if context.args and context.args[0].isdigit():
|
| 429 |
+
page = int(context.args[0])
|
| 430 |
+
if page < 1: page = 1
|
| 431 |
+
|
| 432 |
+
users_per_page = 20
|
| 433 |
+
total_users = len(users)
|
| 434 |
+
total_pages = (total_users + users_per_page - 1) // users_per_page
|
| 435 |
+
|
| 436 |
+
if page > total_pages: page = total_pages
|
| 437 |
+
|
| 438 |
+
start_idx = (page - 1) * users_per_page
|
| 439 |
+
end_idx = min(start_idx + users_per_page, total_users)
|
| 440 |
+
|
| 441 |
+
sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
|
| 442 |
+
|
| 443 |
+
users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
|
| 444 |
+
|
| 445 |
+
for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
|
| 446 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 447 |
+
username = user_info.get('username', 'N/A')
|
| 448 |
+
first_name = user_info.get('first_name', 'N/A')
|
| 449 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 450 |
+
message_count = user_info.get('message_count', 0)
|
| 451 |
+
|
| 452 |
+
users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
|
| 453 |
+
users_text += f" پیامها: `{message_count}` | آخرین فعالیت: `{last_seen}`\n\n"
|
| 454 |
+
|
| 455 |
+
keyboard = []
|
| 456 |
+
if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
|
| 457 |
+
if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
|
| 458 |
+
|
| 459 |
+
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
|
| 460 |
+
await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)
|
| 461 |
+
|
| 462 |
+
@admin_only
|
| 463 |
+
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 464 |
+
"""جستجوی کاربر بر اساس نام یا نام کاربری."""
|
| 465 |
+
if not context.args:
|
| 466 |
+
await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
|
| 467 |
+
return
|
| 468 |
+
|
| 469 |
+
search_term = " ".join(context.args).lower()
|
| 470 |
+
users = data_manager.DATA['users']
|
| 471 |
+
|
| 472 |
+
matching_users = []
|
| 473 |
+
for user_id, user_info in users.items():
|
| 474 |
+
# --- کد اصلاح شده ---
|
| 475 |
+
# استفاده از (value or '') برای جلوگیری از خطا در صورت وجود None
|
| 476 |
+
first_name = (user_info.get('first_name') or '').lower()
|
| 477 |
+
username = (user_info.get('username') or '').lower()
|
| 478 |
+
# --- پایان کد اصلاح شده ---
|
| 479 |
+
|
| 480 |
+
if search_term in first_name or search_term in username:
|
| 481 |
+
is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
|
| 482 |
+
matching_users.append((user_id, user_info, is_banned))
|
| 483 |
+
|
| 484 |
+
if not matching_users:
|
| 485 |
+
await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
|
| 486 |
+
return
|
| 487 |
+
|
| 488 |
+
results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
|
| 489 |
+
|
| 490 |
+
for user_id, user_info, is_banned in matching_users:
|
| 491 |
+
username_display = user_info.get('username', 'N/A') # برای نمایش نیازی به lower نیست
|
| 492 |
+
first_name_display = user_info.get('first_name', 'N/A') # برای نمایش نیازی به lower نیست
|
| 493 |
+
last_seen = user_info.get('last_seen', 'N/A')
|
| 494 |
+
message_count = user_info.get('message_count', 0)
|
| 495 |
+
|
| 496 |
+
results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
|
| 497 |
+
results_text += f" پیامها: `{message_count}` | آخرین فعالیت: `{last_seen}`\n\n"
|
| 498 |
+
|
| 499 |
+
await update.message.reply_text(results_text, parse_mode='Markdown')
|
| 500 |
+
|
| 501 |
+
@admin_only
|
| 502 |
+
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 503 |
+
"""ایجاد نسخه پشتیبان از دادههای ربات."""
|
| 504 |
+
try:
|
| 505 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 506 |
+
backup_file = f"bot_backup_{timestamp}.json"
|
| 507 |
+
|
| 508 |
+
data_to_backup = data_manager.DATA.copy()
|
| 509 |
+
data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
|
| 510 |
+
|
| 511 |
+
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 512 |
+
json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
|
| 513 |
+
|
| 514 |
+
await update.message.reply_document(
|
| 515 |
+
document=open(backup_file, 'rb'),
|
| 516 |
+
caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
logger.info(f"Backup created: {backup_file}")
|
| 520 |
+
os.remove(backup_file) # حذف فایل پس از ارسال
|
| 521 |
+
except Exception as e:
|
| 522 |
+
await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
|
| 523 |
+
logger.error(f"Error creating backup: {e}")
|
| 524 |
+
|
| 525 |
+
@admin_only
|
| 526 |
+
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 527 |
+
"""ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
|
| 528 |
+
users = data_manager.DATA['users']
|
| 529 |
+
|
| 530 |
+
df_data = []
|
| 531 |
+
for user_id, user_info in users.items():
|
| 532 |
+
is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
|
| 533 |
+
df_data.append({
|
| 534 |
+
'User ID': user_id,
|
| 535 |
+
'First Name': user_info.get('first_name', 'N/A'),
|
| 536 |
+
'Username': user_info.get('username', 'N/A'),
|
| 537 |
+
'Message Count': user_info.get('message_count', 0),
|
| 538 |
+
'First Seen': user_info.get('first_seen', 'N/A'),
|
| 539 |
+
'Last Seen': user_info.get('last_seen', 'N/A'),
|
| 540 |
+
'Banned': is_banned
|
| 541 |
+
})
|
| 542 |
+
|
| 543 |
+
df = pd.DataFrame(df_data)
|
| 544 |
+
|
| 545 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
|
| 546 |
+
df.to_csv(f.name, index=False)
|
| 547 |
+
temp_file_path = f.name
|
| 548 |
+
|
| 549 |
+
await update.message.reply_document(
|
| 550 |
+
document=open(temp_file_path, 'rb'),
|
| 551 |
+
caption="📊 فایل CSV اطلاعات کاربران"
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
os.unlink(temp_file_path)
|
| 555 |
+
|
| 556 |
+
@admin_only
|
| 557 |
+
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 558 |
+
"""حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع میدهد."""
|
| 559 |
+
if not context.args or context.args[0].lower() not in ['on', 'off']:
|
| 560 |
+
await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
|
| 561 |
+
return
|
| 562 |
+
|
| 563 |
+
status = context.args[0].lower()
|
| 564 |
+
|
| 565 |
+
if status == 'on':
|
| 566 |
+
if data_manager.DATA.get('maintenance_mode', False):
|
| 567 |
+
await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
|
| 568 |
+
return
|
| 569 |
+
|
| 570 |
+
data_manager.DATA['maintenance_mode'] = True
|
| 571 |
+
data_manager.save_data()
|
| 572 |
+
|
| 573 |
+
await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاعرسانی به کاربران...")
|
| 574 |
+
|
| 575 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 576 |
+
for user_id_str in user_ids:
|
| 577 |
+
try:
|
| 578 |
+
# به ادمینها پیام ارسال نشود
|
| 579 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 580 |
+
await context.bot.send_message(
|
| 581 |
+
chat_id=int(user_id_str),
|
| 582 |
+
text="🔧 ربات در حال حاضر در حالت بهروزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
|
| 583 |
+
)
|
| 584 |
+
await asyncio.sleep(0.05) # جلوگیری از محدودیت تلگرام
|
| 585 |
+
except TelegramError:
|
| 586 |
+
continue # نادیده گرفتن کاربرانی که ربات را مسدود کردهاند
|
| 587 |
+
|
| 588 |
+
elif status == 'off':
|
| 589 |
+
if not data_manager.DATA.get('maintenance_mode', False):
|
| 590 |
+
await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
|
| 591 |
+
return
|
| 592 |
+
|
| 593 |
+
data_manager.DATA['maintenance_mode'] = False
|
| 594 |
+
data_manager.save_data()
|
| 595 |
+
|
| 596 |
+
await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاعرسانی به کاربران...")
|
| 597 |
+
|
| 598 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 599 |
+
for user_id_str in user_ids:
|
| 600 |
+
try:
|
| 601 |
+
if int(user_id_str) not in ADMIN_IDS:
|
| 602 |
+
await context.bot.send_message(
|
| 603 |
+
chat_id=int(user_id_str),
|
| 604 |
+
text="✅ بهروزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! میتوانید دوباره از ربات استفاده کنید."
|
| 605 |
+
)
|
| 606 |
+
await asyncio.sleep(0.05)
|
| 607 |
+
except TelegramError:
|
| 608 |
+
continue
|
| 609 |
+
|
| 610 |
+
@admin_only
|
| 611 |
+
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 612 |
+
"""تنظیم پیام خوشامدگویی جدید."""
|
| 613 |
+
if not context.args:
|
| 614 |
+
await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
|
| 615 |
+
"مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
|
| 616 |
+
return
|
| 617 |
+
|
| 618 |
+
new_message = " ".join(context.args)
|
| 619 |
+
data_manager.DATA['welcome_message'] = new_message
|
| 620 |
+
data_manager.save_data()
|
| 621 |
+
|
| 622 |
+
await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت بهروزرسانی شد.")
|
| 623 |
+
|
| 624 |
+
@admin_only
|
| 625 |
+
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 626 |
+
"""تنظیم پیام خداحافظی جدید."""
|
| 627 |
+
if not context.args:
|
| 628 |
+
await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
|
| 629 |
+
"مثال: `/set_goodbye {user_mention}، خداحافظ!`")
|
| 630 |
+
return
|
| 631 |
+
|
| 632 |
+
new_message = " ".join(context.args)
|
| 633 |
+
data_manager.DATA['goodbye_message'] = new_message
|
| 634 |
+
data_manager.save_data()
|
| 635 |
+
|
| 636 |
+
await update.message.reply_text("✅ پیام خداحافظی با موفقیت بهروزرسانی شد.")
|
| 637 |
+
|
| 638 |
+
@admin_only
|
| 639 |
+
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 640 |
+
"""ایجاد و ارسال نمودار فعالیت کاربران."""
|
| 641 |
+
users = data_manager.DATA['users']
|
| 642 |
+
activity_hours = [0] * 24
|
| 643 |
+
|
| 644 |
+
for user_info in users.values():
|
| 645 |
+
if 'last_seen' in user_info:
|
| 646 |
+
try:
|
| 647 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 648 |
+
activity_hours[last_seen.hour] += 1
|
| 649 |
+
except ValueError:
|
| 650 |
+
continue
|
| 651 |
+
|
| 652 |
+
plt.figure(figsize=(12, 6))
|
| 653 |
+
plt.bar(range(24), activity_hours, color='skyblue')
|
| 654 |
+
plt.title('نمودار فعالیت کاربران بر اساس ساعت')
|
| 655 |
+
plt.xlabel('ساعت')
|
| 656 |
+
plt.ylabel('تعداد کاربران فعال')
|
| 657 |
+
plt.xticks(range(24))
|
| 658 |
+
plt.grid(axis='y', alpha=0.3)
|
| 659 |
+
|
| 660 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
|
| 661 |
+
plt.savefig(f.name, bbox_inches='tight')
|
| 662 |
+
temp_file_path = f.name
|
| 663 |
+
|
| 664 |
+
plt.close()
|
| 665 |
+
|
| 666 |
+
await update.message.reply_photo(
|
| 667 |
+
photo=open(temp_file_path, 'rb'),
|
| 668 |
+
caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
os.unlink(temp_file_path)
|
| 672 |
+
|
| 673 |
+
@admin_only
|
| 674 |
+
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 675 |
+
"""نمایش آمار زمان پاسخگویی ربات."""
|
| 676 |
+
stats = data_manager.DATA['stats']
|
| 677 |
+
await update.message.reply_text(
|
| 678 |
+
"📈 **آمار زمان پاسخگویی ربات**\n\n"
|
| 679 |
+
f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 'N/A'):.2f}` ثانیه\n"
|
| 680 |
+
f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 'N/A'):.2f}` ثانیه\n"
|
| 681 |
+
f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 'N/A'):.2f}` ثانیه\n"
|
| 682 |
+
f"📊 کل پاسخهای ثبت شده: `{stats.get('total_responses', 'N/A')}`"
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
@admin_only
|
| 686 |
+
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 687 |
+
"""افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
|
| 688 |
+
if not context.args:
|
| 689 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 690 |
+
"مثال: `/add_blocked_word کلمه_نامناسب`")
|
| 691 |
+
return
|
| 692 |
+
|
| 693 |
+
word = " ".join(context.args).lower()
|
| 694 |
+
|
| 695 |
+
if word in data_manager.DATA['blocked_words']:
|
| 696 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
|
| 697 |
+
return
|
| 698 |
+
|
| 699 |
+
data_manager.DATA['blocked_words'].append(word)
|
| 700 |
+
data_manager.save_data()
|
| 701 |
+
|
| 702 |
+
await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")
|
| 703 |
+
|
| 704 |
+
@admin_only
|
| 705 |
+
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 706 |
+
"""حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
|
| 707 |
+
if not context.args:
|
| 708 |
+
await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
|
| 709 |
+
"مثال: `/remove_blocked_word کلمه_نامناسب`")
|
| 710 |
+
return
|
| 711 |
+
|
| 712 |
+
word = " ".join(context.args).lower()
|
| 713 |
+
|
| 714 |
+
if word not in data_manager.DATA['blocked_words']:
|
| 715 |
+
await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
|
| 716 |
+
return
|
| 717 |
+
|
| 718 |
+
data_manager.DATA['blocked_words'].remove(word)
|
| 719 |
+
data_manager.save_data()
|
| 720 |
+
|
| 721 |
+
await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")
|
| 722 |
+
|
| 723 |
+
@admin_only
|
| 724 |
+
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 725 |
+
"""نمایش لیست کلمات مسدود شده."""
|
| 726 |
+
if not data_manager.DATA['blocked_words']:
|
| 727 |
+
await update.message.reply_text("هیچ کلمه مسدود شد��ای در لیست وجود ندارد.")
|
| 728 |
+
return
|
| 729 |
+
|
| 730 |
+
words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
|
| 731 |
+
await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")
|
| 732 |
+
|
| 733 |
+
@admin_only
|
| 734 |
+
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 735 |
+
"""نمایش اطلاعات سیستم و منابع."""
|
| 736 |
+
bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
|
| 737 |
+
bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
|
| 738 |
+
uptime = datetime.now() - bot_start_time
|
| 739 |
+
|
| 740 |
+
system_info = (
|
| 741 |
+
f"💻 **اطلاعات سیستم:**\n\n"
|
| 742 |
+
f"🖥️ سیستمعامل: {platform.system()} {platform.release()}\n"
|
| 743 |
+
f"🐍 نسخه پایتون: {platform.python_version()}\n"
|
| 744 |
+
f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
|
| 745 |
+
f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
|
| 746 |
+
f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
|
| 747 |
+
f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
|
| 748 |
+
f"⏱️ زمان اجرای ربات: {uptime}"
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
await update.message.reply_text(system_info, parse_mode='Markdown')
|
| 752 |
+
|
| 753 |
+
@admin_only
|
| 754 |
+
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 755 |
+
"""ریست کردن آمار ربات."""
|
| 756 |
+
if not context.args:
|
| 757 |
+
await update.message.reply_text("⚠️ لطفاً نوع آماری که میخواهید ریست کنید را مشخص کنید.\n"
|
| 758 |
+
"مثال: `/reset_stats messages` یا `/reset_stats all`")
|
| 759 |
+
return
|
| 760 |
+
|
| 761 |
+
stat_type = context.args[0].lower()
|
| 762 |
+
|
| 763 |
+
if stat_type == "messages":
|
| 764 |
+
data_manager.DATA['stats']['total_messages'] = 0
|
| 765 |
+
for user_id in data_manager.DATA['users']:
|
| 766 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 767 |
+
await update.message.reply_text("✅ آمار پیامها با موفقیت ریست شد.")
|
| 768 |
+
|
| 769 |
+
elif stat_type == "all":
|
| 770 |
+
data_manager.DATA['stats'] = {
|
| 771 |
+
'total_messages': 0,
|
| 772 |
+
'total_users': len(data_manager.DATA['users']),
|
| 773 |
+
'avg_response_time': 0,
|
| 774 |
+
'max_response_time': 0,
|
| 775 |
+
'min_response_time': 0,
|
| 776 |
+
'total_responses': 0
|
| 777 |
+
}
|
| 778 |
+
for user_id in data_manager.DATA['users']:
|
| 779 |
+
data_manager.DATA['users'][user_id]['message_count'] = 0
|
| 780 |
+
await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
|
| 781 |
+
|
| 782 |
+
else:
|
| 783 |
+
await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینههای موجود: messages, all")
|
| 784 |
+
return
|
| 785 |
+
|
| 786 |
+
data_manager.save_data()
|
| 787 |
+
|
| 788 |
+
# --- هندلر برای دکمههای صفحهبندی ---
|
| 789 |
+
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 790 |
+
"""پردازش دکمههای صفحهبندی لیست کاربران."""
|
| 791 |
+
query = update.callback_query
|
| 792 |
+
await query.answer()
|
| 793 |
+
|
| 794 |
+
if query.data.startswith("users_list:"):
|
| 795 |
+
page = int(query.data.split(":")[1])
|
| 796 |
+
context.args = [str(page)]
|
| 797 |
+
await admin_users_list(update, context)
|
| 798 |
+
|
| 799 |
+
# --- تابع برای پردازش ارسالهای برنامهریزی شده ---
|
| 800 |
+
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
|
| 801 |
+
"""پردازش ارسالهای برنامهریزی شده و ارسال پیامها در زمان مقرر."""
|
| 802 |
+
now = datetime.now()
|
| 803 |
+
broadcasts_to_send_indices = []
|
| 804 |
+
|
| 805 |
+
for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
|
| 806 |
+
if broadcast['status'] == 'pending':
|
| 807 |
+
broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
|
| 808 |
+
if broadcast_time <= now:
|
| 809 |
+
broadcasts_to_send_indices.append(i)
|
| 810 |
+
|
| 811 |
+
if not broadcasts_to_send_indices:
|
| 812 |
+
return
|
| 813 |
+
|
| 814 |
+
user_ids = list(data_manager.DATA['users'].keys())
|
| 815 |
+
|
| 816 |
+
for index in broadcasts_to_send_indices:
|
| 817 |
+
broadcast = data_manager.DATA['scheduled_broadcasts'][index]
|
| 818 |
+
message_text = broadcast['message']
|
| 819 |
+
total_sent, total_failed = 0, 0
|
| 820 |
+
|
| 821 |
+
for user_id_str in user_ids:
|
| 822 |
+
try:
|
| 823 |
+
await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
|
| 824 |
+
total_sent += 1
|
| 825 |
+
await asyncio.sleep(0.05)
|
| 826 |
+
except TelegramError as e:
|
| 827 |
+
logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
|
| 828 |
+
total_failed += 1
|
| 829 |
+
|
| 830 |
+
# بهروزرسانی وضعیت ارسال
|
| 831 |
+
data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
|
| 832 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
|
| 833 |
+
data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
|
| 834 |
+
data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
|
| 835 |
+
|
| 836 |
+
logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
|
| 837 |
+
|
| 838 |
+
data_manager.save_data()
|
| 839 |
+
|
| 840 |
+
# --- تابع راهاندازی هندلرها ---
|
| 841 |
+
def setup_admin_handlers(application):
|
| 842 |
+
"""هندلرهای پنل ادمین را به اپلیکیشن اضافه میکند."""
|
| 843 |
+
# هندلرهای اصلی
|
| 844 |
+
application.add_handler(CommandHandler("commands", admin_commands))
|
| 845 |
+
application.add_handler(CommandHandler("stats", admin_stats))
|
| 846 |
+
application.add_handler(CommandHandler("broadcast", admin_broadcast))
|
| 847 |
+
application.add_handler(CommandHandler("ban", admin_ban))
|
| 848 |
+
application.add_handler(CommandHandler("unban", admin_unban))
|
| 849 |
+
application.add_handler(CommandHandler("user_info", admin_userinfo))
|
| 850 |
+
application.add_handler(CommandHandler("logs", admin_logs))
|
| 851 |
+
application.add_handler(CommandHandler("logs_file", admin_logs_file)) # <--- هندلر جدید
|
| 852 |
+
application.add_handler(CommandHandler("users_list", admin_users_list))
|
| 853 |
+
application.add_handler(CommandHandler("user_search", admin_user_search))
|
| 854 |
+
application.add_handler(CommandHandler("backup", admin_backup))
|
| 855 |
+
|
| 856 |
+
# هندلرهای جدید
|
| 857 |
+
application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
|
| 858 |
+
application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
|
| 859 |
+
application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
|
| 860 |
+
application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
|
| 861 |
+
application.add_handler(CommandHandler("direct_message", admin_direct_message))
|
| 862 |
+
application.add_handler(CommandHandler("export_csv", admin_export_csv))
|
| 863 |
+
application.add_handler(CommandHandler("maintenance", admin_maintenance)) # <--- هندلر جایگزین شده
|
| 864 |
+
application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
|
| 865 |
+
application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
|
| 866 |
+
application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
|
| 867 |
+
application.add_handler(CommandHandler("response_stats", admin_response_stats))
|
| 868 |
+
application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
|
| 869 |
+
application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
|
| 870 |
+
application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
|
| 871 |
+
application.add_handler(CommandHandler("system_info", admin_system_info))
|
| 872 |
+
application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
|
| 873 |
+
|
| 874 |
+
# هندلر برای دکمههای صفحهبندی
|
| 875 |
+
application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
|
| 876 |
+
|
| 877 |
+
# شروع وظیفه دورهای برای بررسی ارسالهای برنامهریزی شده
|
| 878 |
+
application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
|
| 879 |
+
|
| 880 |
+
logger.info("Admin panel handlers have been set up.")
|
render-main/data_manager.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# data_manager.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
|
| 8 |
+
# --- تنظیمات مسیر فایلها ---
|
| 9 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
+
DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
|
| 11 |
+
LOG_FILE = os.path.join(BASE_DIR, "bot.log")
|
| 12 |
+
|
| 13 |
+
# --- کش دادههای گلوبال ---
|
| 14 |
+
DATA = {
|
| 15 |
+
"users": {},
|
| 16 |
+
"banned_users": set(),
|
| 17 |
+
"stats": {
|
| 18 |
+
"total_messages": 0,
|
| 19 |
+
"total_users": 0,
|
| 20 |
+
"avg_response_time": 0.0,
|
| 21 |
+
"max_response_time": 0.0,
|
| 22 |
+
"min_response_time": float('inf'),
|
| 23 |
+
"total_responses": 0
|
| 24 |
+
},
|
| 25 |
+
"welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
|
| 26 |
+
"goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
|
| 27 |
+
"maintenance_mode": False,
|
| 28 |
+
"blocked_words": [],
|
| 29 |
+
"scheduled_broadcasts": [],
|
| 30 |
+
"bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
def load_data():
|
| 36 |
+
"""دادهها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره میکند."""
|
| 37 |
+
global DATA
|
| 38 |
+
try:
|
| 39 |
+
if not os.path.exists(DATA_FILE):
|
| 40 |
+
logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد میشود.")
|
| 41 |
+
save_data()
|
| 42 |
+
return
|
| 43 |
+
|
| 44 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
| 45 |
+
loaded_data = json.load(f)
|
| 46 |
+
loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
|
| 47 |
+
|
| 48 |
+
# اطمینان از وجود کلیدهای جدید در فایلهای قدیمی
|
| 49 |
+
if 'blocked_words' not in loaded_data: loaded_data['blocked_words'] = []
|
| 50 |
+
if 'scheduled_broadcasts' not in loaded_data: loaded_data['scheduled_broadcasts'] = []
|
| 51 |
+
if 'maintenance_mode' not in loaded_data: loaded_data['maintenance_mode'] = False
|
| 52 |
+
if 'bot_start_time' not in loaded_data: loaded_data['bot_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 53 |
+
if 'avg_response_time' not in loaded_data['stats']:
|
| 54 |
+
loaded_data['stats']['avg_response_time'] = 0.0
|
| 55 |
+
loaded_data['stats']['max_response_time'] = 0.0
|
| 56 |
+
loaded_data['stats']['min_response_time'] = float('inf')
|
| 57 |
+
loaded_data['stats']['total_responses'] = 0
|
| 58 |
+
|
| 59 |
+
DATA.update(loaded_data)
|
| 60 |
+
logger.info(f"دادهها با موفقیت از {DATA_FILE} بارگذاری شدند.")
|
| 61 |
+
|
| 62 |
+
except json.JSONDecodeError as e:
|
| 63 |
+
logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"خطای غیرمنتظره هنگام بارگذاری دادهها: {e}. ربات با دادههای اولیه شروع به کار میکند.")
|
| 66 |
+
|
| 67 |
+
def save_data():
|
| 68 |
+
"""کش گلوبال دادهها را در فایل JSON ذخیره میکند."""
|
| 69 |
+
global DATA
|
| 70 |
+
try:
|
| 71 |
+
data_to_save = DATA.copy()
|
| 72 |
+
data_to_save['banned_users'] = list(DATA['banned_users'])
|
| 73 |
+
|
| 74 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 75 |
+
json.dump(data_to_save, f, indent=4, ensure_ascii=False)
|
| 76 |
+
logger.debug(f"دادهها با موفقیت در {DATA_FILE} ذخیره شدند.")
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logger.error(f"خطای مهلک: امکان ذخیره دادهها در {DATA_FILE} وجود ندارد. خطا: {e}")
|
| 79 |
+
|
| 80 |
+
def update_user_stats(user_id: int, user):
|
| 81 |
+
"""آمار کاربر را پس از هر پیام بهروز کرده و دادهها را ذخیره میکند."""
|
| 82 |
+
global DATA
|
| 83 |
+
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 84 |
+
user_id_str = str(user_id)
|
| 85 |
+
|
| 86 |
+
if user_id_str not in DATA['users']:
|
| 87 |
+
DATA['users'][user_id_str] = {
|
| 88 |
+
'first_name': user.first_name,
|
| 89 |
+
'username': user.username,
|
| 90 |
+
'first_seen': now_str,
|
| 91 |
+
'message_count': 0
|
| 92 |
+
}
|
| 93 |
+
DATA['stats']['total_users'] += 1
|
| 94 |
+
logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")
|
| 95 |
+
|
| 96 |
+
DATA['users'][user_id_str]['last_seen'] = now_str
|
| 97 |
+
DATA['users'][user_id_str]['message_count'] += 1
|
| 98 |
+
DATA['stats']['total_messages'] += 1
|
| 99 |
+
|
| 100 |
+
save_data()
|
| 101 |
+
|
| 102 |
+
def update_response_stats(response_time: float):
|
| 103 |
+
"""آمار زمان پاسخگویی را بهروز میکند."""
|
| 104 |
+
global DATA
|
| 105 |
+
|
| 106 |
+
if DATA['stats']['total_responses'] == 0:
|
| 107 |
+
DATA['stats']['min_response_time'] = response_time
|
| 108 |
+
|
| 109 |
+
DATA['stats']['total_responses'] += 1
|
| 110 |
+
|
| 111 |
+
# محاسبه میانگین جدید
|
| 112 |
+
current_avg = DATA['stats']['avg_response_time']
|
| 113 |
+
total_responses = DATA['stats']['total_responses']
|
| 114 |
+
new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
|
| 115 |
+
DATA['stats']['avg_response_time'] = new_avg
|
| 116 |
+
|
| 117 |
+
# بهروزرسانی حداکثر و حداقل زمان پاسخگویی
|
| 118 |
+
if response_time > DATA['stats']['max_response_time']:
|
| 119 |
+
DATA['stats']['max_response_time'] = response_time
|
| 120 |
+
|
| 121 |
+
if response_time < DATA['stats']['min_response_time']:
|
| 122 |
+
DATA['stats']['min_response_time'] = response_time
|
| 123 |
+
|
| 124 |
+
save_data()
|
| 125 |
+
|
| 126 |
+
def is_user_banned(user_id: int) -> bool:
|
| 127 |
+
"""بررسی میکند آیا کاربر مسدود شده است یا خیر."""
|
| 128 |
+
return user_id in DATA['banned_users']
|
| 129 |
+
|
| 130 |
+
def ban_user(user_id: int):
|
| 131 |
+
"""کاربر را مسدود کرده و ذخیره میکند."""
|
| 132 |
+
DATA['banned_users'].add(user_id)
|
| 133 |
+
save_data()
|
| 134 |
+
|
| 135 |
+
def unban_user(user_id: int):
|
| 136 |
+
"""مسدودیت کاربر را برداشته و ذخیره میکند."""
|
| 137 |
+
DATA['banned_users'].discard(user_id)
|
| 138 |
+
save_data()
|
| 139 |
+
|
| 140 |
+
def contains_blocked_words(text: str) -> bool:
|
| 141 |
+
"""بررسی میکند آیا متن حاوی کلمات مسدود شده است یا خیر."""
|
| 142 |
+
if not DATA['blocked_words']:
|
| 143 |
+
return False
|
| 144 |
+
|
| 145 |
+
text_lower = text.lower()
|
| 146 |
+
for word in DATA['blocked_words']:
|
| 147 |
+
if word in text_lower:
|
| 148 |
+
return True
|
| 149 |
+
|
| 150 |
+
return False
|
| 151 |
+
|
| 152 |
+
def get_active_users(days: int) -> list:
|
| 153 |
+
"""لیست کاربران فعال در بازه زمانی مشخص را برمیگرداند."""
|
| 154 |
+
now = datetime.now()
|
| 155 |
+
cutoff_date = now - timedelta(days=days)
|
| 156 |
+
|
| 157 |
+
active_users = []
|
| 158 |
+
for user_id, user_info in DATA['users'].items():
|
| 159 |
+
if 'last_seen' in user_info:
|
| 160 |
+
try:
|
| 161 |
+
last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
|
| 162 |
+
if last_seen >= cutoff_date:
|
| 163 |
+
active_users.append(int(user_id))
|
| 164 |
+
except ValueError:
|
| 165 |
+
continue
|
| 166 |
+
|
| 167 |
+
return active_users
|
| 168 |
+
|
| 169 |
+
def get_users_by_message_count(min_count: int) -> list:
|
| 170 |
+
"""لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمیگرداند."""
|
| 171 |
+
users = []
|
| 172 |
+
for user_id, user_info in DATA['users'].items():
|
| 173 |
+
if user_info.get('message_count', 0) >= min_count:
|
| 174 |
+
users.append(int(user_id))
|
| 175 |
+
|
| 176 |
+
return users
|
| 177 |
+
|
| 178 |
+
# بارگذاری اولیه دادهها در زمان ایمپورت شدن ماژول
|
| 179 |
+
load_data()
|
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()
|
render-main/main.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# شروع سرویس نگه داشتن ربات فعال
|
| 18 |
+
start_keep_alive()
|
| 19 |
+
|
| 20 |
+
# --- بهبود لاگینگ ---
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
filename=data_manager.LOG_FILE,
|
| 25 |
+
filemode='a'
|
| 26 |
+
)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
with open(data_manager.LOG_FILE, 'a') as f:
|
| 31 |
+
f.write("")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
|
| 34 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 35 |
+
|
| 36 |
+
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
|
| 37 |
+
http_client = httpx.AsyncClient(
|
| 38 |
+
http2=True,
|
| 39 |
+
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
|
| 40 |
+
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# کلاینت OpenAI (HuggingFace)
|
| 44 |
+
client = AsyncOpenAI(
|
| 45 |
+
base_url="https://router.huggingface.co/v1",
|
| 46 |
+
api_key=os.environ["HF_TOKEN"],
|
| 47 |
+
http_client=http_client
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
|
| 51 |
+
user_tasks = {}
|
| 52 |
+
|
| 53 |
+
# --- توابع کمکی برای مدیریت وظایف ---
|
| 54 |
+
def _cleanup_task(task: asyncio.Task, user_id: int):
|
| 55 |
+
if user_id in user_tasks and user_tasks[user_id] == task:
|
| 56 |
+
del user_tasks[user_id]
|
| 57 |
+
logger.info(f"Cleaned up finished task for user {user_id}.")
|
| 58 |
+
try:
|
| 59 |
+
exception = task.exception()
|
| 60 |
+
if exception:
|
| 61 |
+
logger.error(f"Background task for user {user_id} failed: {exception}")
|
| 62 |
+
except asyncio.CancelledError:
|
| 63 |
+
logger.info(f"Task for user {user_id} was cancelled.")
|
| 64 |
+
|
| 65 |
+
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 66 |
+
chat_id = update.effective_chat.id
|
| 67 |
+
user_message = update.message.text
|
| 68 |
+
user_id = update.effective_user.id
|
| 69 |
+
|
| 70 |
+
start_time = time.time()
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 74 |
+
response = await client.chat.completions.create(
|
| 75 |
+
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
|
| 76 |
+
messages=[{"role": "user", "content": user_message}],
|
| 77 |
+
temperature=0.7,
|
| 78 |
+
top_p=0.95,
|
| 79 |
+
stream=False,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
end_time = time.time()
|
| 83 |
+
response_time = end_time - start_time
|
| 84 |
+
data_manager.update_response_stats(response_time)
|
| 85 |
+
|
| 86 |
+
await update.message.reply_text(response.choices[0].message.content)
|
| 87 |
+
data_manager.update_user_stats(user_id, update.effective_user)
|
| 88 |
+
|
| 89 |
+
except httpx.TimeoutException:
|
| 90 |
+
logger.warning(f"Request timed out for user {user_id}.")
|
| 91 |
+
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
|
| 92 |
+
except Exception as e:
|
| 93 |
+
logger.error(f"Error while processing message for user {user_id}: {e}")
|
| 94 |
+
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
|
| 95 |
+
|
| 96 |
+
# --- هندلرهای اصلی ربات ---
|
| 97 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 98 |
+
user = update.effective_user
|
| 99 |
+
user_id = user.id
|
| 100 |
+
|
| 101 |
+
data_manager.update_user_stats(user_id, user)
|
| 102 |
+
|
| 103 |
+
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
|
| 104 |
+
await update.message.reply_html(
|
| 105 |
+
welcome_msg.format(user_mention=user.mention_html()),
|
| 106 |
+
disable_web_page_preview=True
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 110 |
+
user_id = update.effective_user.id
|
| 111 |
+
|
| 112 |
+
# بررسی مسدود بودن کاربر
|
| 113 |
+
if data_manager.is_user_banned(user_id):
|
| 114 |
+
logger.info(f"Banned user {user_id} tried to send a message.")
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
# بررسی حالت نگهداری (فقط برای کاربران عادی)
|
| 118 |
+
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
|
| 119 |
+
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
# بررسی کلمات مسدود شده
|
| 123 |
+
if data_manager.contains_blocked_words(update.message.text):
|
| 124 |
+
logger.info(f"User {user_id} sent a message with a blocked word.")
|
| 125 |
+
# میتوانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید
|
| 126 |
+
# await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
if user_id in user_tasks and not user_tasks[user_id].done():
|
| 130 |
+
user_tasks[user_id].cancel()
|
| 131 |
+
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
|
| 132 |
+
|
| 133 |
+
task = asyncio.create_task(_process_user_request(update, context))
|
| 134 |
+
user_tasks[user_id] = task
|
| 135 |
+
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
|
| 136 |
+
|
| 137 |
+
def main() -> None:
|
| 138 |
+
token = os.environ.get("BOT_TOKEN")
|
| 139 |
+
if not token:
|
| 140 |
+
logger.error("BOT_TOKEN not set in environment variables!")
|
| 141 |
+
return
|
| 142 |
+
|
| 143 |
+
application = (
|
| 144 |
+
Application.builder()
|
| 145 |
+
.token(token)
|
| 146 |
+
.concurrent_updates(True)
|
| 147 |
+
.build()
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
application.add_handler(CommandHandler("start", start))
|
| 151 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 152 |
+
|
| 153 |
+
# راهاندازی و ثبت هندلرهای پنل ادمین
|
| 154 |
+
admin_panel.setup_admin_handlers(application)
|
| 155 |
+
|
| 156 |
+
port = int(os.environ.get("PORT", 8443))
|
| 157 |
+
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
|
| 158 |
+
|
| 159 |
+
application.run_webhook(
|
| 160 |
+
listen="0.0.0.0",
|
| 161 |
+
port=port,
|
| 162 |
+
webhook_url=webhook_url,
|
| 163 |
+
url_path="webhook"
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
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 وارد کنید
|
render-main/requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|