File size: 9,280 Bytes
db37698 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
# main.py
import os
import logging
import asyncio
import httpx
import time
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from openai import AsyncOpenAI
from keep_alive import start_keep_alive
# وارد کردن مدیر دادهها و پنل ادمین
import data_manager
import admin_panel
# شروع سرویس نگه داشتن ربات فعال
start_keep_alive()
# --- بهبود لاگینگ ---
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
filename=data_manager.LOG_FILE,
filemode='a'
)
logger = logging.getLogger(__name__)
try:
with open(data_manager.LOG_FILE, 'a') as f:
f.write("")
except Exception as e:
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
http_client = httpx.AsyncClient(
http2=True,
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
)
# کلاینت OpenAI (HuggingFace)
client = AsyncOpenAI(
base_url="https://router.huggingface.co/v1",
api_key=os.environ["HF_TOKEN"],
http_client=http_client
)
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
user_tasks = {}
# --- توابع کمکی برای مدیریت وظایف ---
def _cleanup_task(task: asyncio.Task, user_id: int):
if user_id in user_tasks and user_tasks[user_id] == task:
del user_tasks[user_id]
logger.info(f"Cleaned up finished task for user {user_id}.")
try:
exception = task.exception()
if exception:
logger.error(f"Background task for user {user_id} failed: {exception}")
except asyncio.CancelledError:
logger.info(f"Task for user {user_id} was cancelled.")
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_chat.id
user_message = update.message.text
user_id = update.effective_user.id
start_time = time.time()
try:
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
# دریافت context کاربر
user_context = data_manager.get_context_for_api(user_id)
# اضافه کردن پیام کاربر به context
data_manager.add_to_user_context(user_id, "user", user_message)
# ایجاد لیست پیامها برای API
messages = user_context.copy()
# اضافه کردن پیام جدید به انتهای لیست
messages.append({"role": "user", "content": user_message})
logger.info(f"User {user_id} sending {len(messages)} messages to AI ({data_manager.get_context_token_count(user_id)} tokens)")
response = await client.chat.completions.create(
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
messages=messages,
temperature=0.7,
top_p=0.95,
stream=False,
)
end_time = time.time()
response_time = end_time - start_time
data_manager.update_response_stats(response_time)
ai_response = response.choices[0].message.content
# اضافه کردن پاسخ هوش مصنوعی به context
data_manager.add_to_user_context(user_id, "assistant", ai_response)
await update.message.reply_text(ai_response)
data_manager.update_user_stats(user_id, update.effective_user)
except httpx.TimeoutException:
logger.warning(f"Request timed out for user {user_id}.")
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
except Exception as e:
logger.error(f"Error while processing message for user {user_id}: {e}")
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
# --- هندلرهای اصلی ربات ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
user_id = user.id
data_manager.update_user_stats(user_id, user)
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
await update.message.reply_html(
welcome_msg.format(user_mention=user.mention_html()),
disable_web_page_preview=True
)
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""پاک کردن تاریخچه چت برای کاربر"""
user_id = update.effective_user.id
data_manager.clear_user_context(user_id)
await update.message.reply_text(
"🧹 تاریخچه مکالمه شما پاک شد.\n"
"از این لحظه مکالمه جدیدی شروع خواهد شد."
)
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""نمایش اطلاعات context کاربر"""
user_id = update.effective_user.id
context_summary = data_manager.get_context_summary(user_id)
await update.message.reply_text(
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
f"{context_summary}\n\n"
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""نمایش دستورات کمک"""
help_text = (
"🤖 **دستورات ربات:**\n\n"
"🟢 `/start` - شروع کار با ربات\n"
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
"🟢 `/help` - نمایش این پیام راهنما\n\n"
"📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۱۰۲۴ توکن ذخیره میکند. " # از 512 به 1024 تغییر یافت
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
)
await update.message.reply_text(help_text, parse_mode='Markdown')
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.effective_user.id
# بررسی مسدود بودن کاربر
if data_manager.is_user_banned(user_id):
logger.info(f"Banned user {user_id} tried to send a message.")
return
# بررسی حالت نگهداری (فقط برای کاربران عادی)
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
return
# بررسی کلمات مسدود شده
if data_manager.contains_blocked_words(update.message.text):
logger.info(f"User {user_id} sent a message with a blocked word.")
# میتوانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید
# await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")
return
if user_id in user_tasks and not user_tasks[user_id].done():
user_tasks[user_id].cancel()
logger.info(f"Cancelled previous task for user {user_id} to start a new one.")
task = asyncio.create_task(_process_user_request(update, context))
user_tasks[user_id] = task
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
def main() -> None:
token = os.environ.get("BOT_TOKEN")
if not token:
logger.error("BOT_TOKEN not set in environment variables!")
return
application = (
Application.builder()
.token(token)
.concurrent_updates(True)
.build()
)
# هندلرهای کاربران
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("clear", clear_chat))
application.add_handler(CommandHandler("context", context_info))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# راهاندازی و ثبت هندلرهای پنل ادمین
admin_panel.setup_admin_handlers(application)
port = int(os.environ.get("PORT", 8443))
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"
application.run_webhook(
listen="0.0.0.0",
port=port,
webhook_url=webhook_url,
url_path="webhook"
)
if __name__ == "__main__":
main() |