|
|
|
|
|
|
|
|
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_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) |
|
|
) |
|
|
|
|
|
|
|
|
client = AsyncOpenAI( |
|
|
base_url="https://router.huggingface.co/v1", |
|
|
api_key=os.environ["HF_TOKEN"], |
|
|
http_client=http_client |
|
|
) |
|
|
|
|
|
|
|
|
user_tasks = {} |
|
|
group_tasks = {} |
|
|
|
|
|
|
|
|
def extract_reply_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> tuple: |
|
|
"""استخراج اطلاعات از ریپلای""" |
|
|
message = update.message |
|
|
|
|
|
|
|
|
if not message or not message.reply_to_message: |
|
|
return None, None, None, None |
|
|
|
|
|
replied_message = message.reply_to_message |
|
|
|
|
|
|
|
|
replied_user_id = replied_message.from_user.id if replied_message.from_user else None |
|
|
replied_user_name = replied_message.from_user.first_name if replied_message.from_user else "Unknown" |
|
|
|
|
|
|
|
|
replied_text = "" |
|
|
if replied_message.text: |
|
|
replied_text = replied_message.text |
|
|
elif replied_message.caption: |
|
|
replied_text = replied_message.caption |
|
|
|
|
|
|
|
|
is_reply_to_bot = False |
|
|
if replied_message.from_user: |
|
|
|
|
|
if replied_message.from_user.is_bot: |
|
|
is_reply_to_bot = True |
|
|
|
|
|
elif context.bot and context.bot.username and replied_message.text: |
|
|
if f"@{context.bot.username}" in replied_message.text: |
|
|
is_reply_to_bot = True |
|
|
|
|
|
return replied_user_id, replied_user_name, replied_text, is_reply_to_bot |
|
|
|
|
|
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: |
|
|
"""فرمتدهی پیام با در نظر گرفتن ریپلای""" |
|
|
if not replied_text: |
|
|
return user_message |
|
|
|
|
|
|
|
|
if len(replied_text) > 100: |
|
|
replied_preview = replied_text[:97] + "..." |
|
|
else: |
|
|
replied_preview = replied_text |
|
|
|
|
|
|
|
|
replied_preview = replied_preview.replace("@", "(at)") |
|
|
|
|
|
if is_reply_to_bot: |
|
|
|
|
|
if current_user_name: |
|
|
return f"📎 {current_user_name} در پاسخ به ربات: «{replied_preview}»\n\n{user_message}" |
|
|
else: |
|
|
return f"📎 ریپلای به ربات: «{replied_preview}»\n\n{user_message}" |
|
|
else: |
|
|
|
|
|
if current_user_name: |
|
|
return f"📎 {current_user_name} در پاسخ به {replied_user_name}: «{replied_preview}»\n\n{user_message}" |
|
|
else: |
|
|
return f"📎 ریپلای به {replied_user_name}: «{replied_preview}»\n\n{user_message}" |
|
|
|
|
|
def create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot): |
|
|
"""ایجاد دیکشنری اطلاعات ریپلای""" |
|
|
if not replied_text: |
|
|
return None |
|
|
|
|
|
return { |
|
|
'replied_user_id': replied_user_id, |
|
|
'replied_user_name': replied_user_name, |
|
|
'replied_text': replied_text[:500], |
|
|
'is_reply_to_bot': is_reply_to_bot, |
|
|
'timestamp': time.time() |
|
|
} |
|
|
|
|
|
|
|
|
def _cleanup_task(task: asyncio.Task, task_dict: dict, task_id: int): |
|
|
if task_id in task_dict and task_dict[task_id] == task: |
|
|
del task_dict[task_id] |
|
|
logger.info(f"Cleaned up finished task for ID {task_id}.") |
|
|
try: |
|
|
exception = task.exception() |
|
|
if exception: |
|
|
logger.error(f"Background task for ID {task_id} failed: {exception}") |
|
|
except asyncio.CancelledError: |
|
|
logger.info(f"Task for ID {task_id} was cancelled.") |
|
|
except asyncio.InvalidStateError: |
|
|
pass |
|
|
|
|
|
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None): |
|
|
"""پردازش درخواست کاربر در چت خصوصی""" |
|
|
chat_id = update.effective_chat.id |
|
|
user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "") |
|
|
user_id = update.effective_user.id |
|
|
|
|
|
if not user_message: |
|
|
logger.warning(f"No message content for user {user_id}") |
|
|
return |
|
|
|
|
|
|
|
|
if reply_info is None: |
|
|
replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context) |
|
|
reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot) |
|
|
|
|
|
|
|
|
if reply_info and reply_info.get('replied_text'): |
|
|
formatted_message = format_reply_message( |
|
|
user_message, |
|
|
reply_info.get('replied_user_name', 'Unknown'), |
|
|
reply_info.get('replied_text'), |
|
|
reply_info.get('is_reply_to_bot', False) |
|
|
) |
|
|
else: |
|
|
formatted_message = user_message |
|
|
|
|
|
start_time = time.time() |
|
|
|
|
|
try: |
|
|
await context.bot.send_chat_action(chat_id=chat_id, action="typing") |
|
|
|
|
|
|
|
|
user_context = data_manager.get_context_for_api(user_id) |
|
|
|
|
|
|
|
|
data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info) |
|
|
|
|
|
|
|
|
messages = user_context.copy() |
|
|
messages.append({"role": "user", "content": formatted_message}) |
|
|
|
|
|
logger.info(f"User {user_id} sending {len(messages)} messages to AI") |
|
|
if reply_info and reply_info.get('replied_text'): |
|
|
logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}") |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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 _process_group_request(update: Update, context: ContextTypes.DEFAULT_TYPE, custom_message: str = None, reply_info: dict = None): |
|
|
"""پردازش درخواست در گروه""" |
|
|
chat_id = update.effective_chat.id |
|
|
user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "") |
|
|
user_id = update.effective_user.id |
|
|
user_name = update.effective_user.first_name |
|
|
|
|
|
if not user_message: |
|
|
logger.warning(f"No message content for group {chat_id}, user {user_id}") |
|
|
return |
|
|
|
|
|
|
|
|
if reply_info is None: |
|
|
replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context) |
|
|
reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot) |
|
|
|
|
|
|
|
|
if reply_info and reply_info.get('replied_text'): |
|
|
formatted_message = format_reply_message( |
|
|
user_message, |
|
|
reply_info.get('replied_user_name', 'Unknown'), |
|
|
reply_info.get('replied_text'), |
|
|
reply_info.get('is_reply_to_bot', False), |
|
|
user_name |
|
|
) |
|
|
else: |
|
|
formatted_message = user_message |
|
|
|
|
|
start_time = time.time() |
|
|
|
|
|
try: |
|
|
await context.bot.send_chat_action(chat_id=chat_id, action="typing") |
|
|
|
|
|
|
|
|
context_mode = data_manager.get_context_mode() |
|
|
|
|
|
if context_mode == 'group_shared': |
|
|
|
|
|
messages = data_manager.get_context_for_api_group(chat_id) |
|
|
data_manager.add_to_group_context_with_reply(chat_id, "user", formatted_message, user_name, reply_info) |
|
|
|
|
|
elif context_mode == 'hybrid': |
|
|
|
|
|
messages = data_manager.get_hybrid_context_for_api(user_id, chat_id) |
|
|
data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "user", formatted_message, user_name, reply_info) |
|
|
|
|
|
else: |
|
|
|
|
|
messages = data_manager.get_context_for_api(user_id) |
|
|
data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info) |
|
|
|
|
|
|
|
|
if context_mode == 'group_shared': |
|
|
messages.append({"role": "user", "content": f"{user_name}: {formatted_message}"}) |
|
|
else: |
|
|
messages.append({"role": "user", "content": formatted_message}) |
|
|
|
|
|
logger.info(f"Group {chat_id} ({context_mode} mode) sending {len(messages)} messages to AI") |
|
|
if reply_info and reply_info.get('replied_text'): |
|
|
logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}") |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
if context_mode == 'group_shared': |
|
|
data_manager.add_to_group_context(chat_id, "assistant", ai_response) |
|
|
elif context_mode == 'hybrid': |
|
|
|
|
|
data_manager.add_to_hybrid_context_with_reply(user_id, chat_id, "assistant", ai_response, None, None) |
|
|
else: |
|
|
data_manager.add_to_user_context(user_id, "assistant", ai_response) |
|
|
|
|
|
|
|
|
data_manager.update_group_stats(chat_id, update.effective_chat, user_id) |
|
|
|
|
|
await update.message.reply_text(ai_response) |
|
|
|
|
|
except httpx.TimeoutException: |
|
|
logger.warning(f"Request timed out for group {chat_id}.") |
|
|
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.") |
|
|
except Exception as e: |
|
|
logger.error(f"Error while processing message for group {chat_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 |
|
|
chat = update.effective_chat |
|
|
|
|
|
if chat.type in ['group', 'supergroup']: |
|
|
|
|
|
data_manager.update_group_stats(chat.id, chat, user_id) |
|
|
|
|
|
welcome_msg = data_manager.DATA.get('group_welcome_message', |
|
|
"سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید\n3. یا روی پیامها ریپلای کنید") |
|
|
|
|
|
context_mode = data_manager.get_context_mode() |
|
|
mode_info = "" |
|
|
if context_mode == 'group_shared': |
|
|
mode_info = "\n\n📝 **نکته:** در این گروه از context مشترک استفاده میشود. همه کاربران تاریخچه مکالمه یکسانی دارند (تا 16384 توکن)." |
|
|
elif context_mode == 'hybrid': |
|
|
mode_info = "\n\n📝 **نکته:** در این گروه از context ترکیبی استفاده میشود." |
|
|
|
|
|
await update.message.reply_html( |
|
|
welcome_msg + mode_info, |
|
|
disable_web_page_preview=True |
|
|
) |
|
|
else: |
|
|
|
|
|
data_manager.update_user_stats(user_id, user) |
|
|
|
|
|
welcome_msg = data_manager.DATA.get('welcome_message', |
|
|
"سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.\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 |
|
|
chat = update.effective_chat |
|
|
|
|
|
if chat.type in ['group', 'supergroup']: |
|
|
|
|
|
data_manager.clear_group_context(chat.id) |
|
|
|
|
|
context_mode = data_manager.get_context_mode() |
|
|
if context_mode == 'group_shared': |
|
|
await update.message.reply_text( |
|
|
"🧹 تاریخچه مکالمه گروه پاک شد.\n" |
|
|
"از این لحظه مکالمه جدیدی برای همه اعضای گروه شروع خواهد شد." |
|
|
) |
|
|
else: |
|
|
await update.message.reply_text( |
|
|
"🧹 تاریخچه مکالمه شخصی شما در این گروه پاک شد.\n" |
|
|
"از این لحظه مکالمه جدیدی شروع خواهد شد." |
|
|
) |
|
|
else: |
|
|
|
|
|
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 |
|
|
chat = update.effective_chat |
|
|
|
|
|
if chat.type in ['group', 'supergroup']: |
|
|
context_mode = data_manager.get_context_mode() |
|
|
|
|
|
if context_mode == 'group_shared': |
|
|
context_summary = data_manager.get_group_context_summary(chat.id) |
|
|
await update.message.reply_text( |
|
|
f"📊 **اطلاعات تاریخچه مکالمه گروه:**\n\n" |
|
|
f"{context_summary}\n\n" |
|
|
f"**حالت:** مشترک بین همه اعضای گروه\n" |
|
|
f"**سقف توکن:** 16384 توکن\n" |
|
|
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید." |
|
|
) |
|
|
elif context_mode == 'hybrid': |
|
|
group_summary = data_manager.get_group_context_summary(chat.id) |
|
|
user_summary = data_manager.get_context_summary(user_id) |
|
|
await update.message.reply_text( |
|
|
f"📊 **اطلاعات تاریخچه مکالمه (حالت ترکیبی):**\n\n" |
|
|
f"**گروه:** {group_summary}\n" |
|
|
f"**شخصی:** {user_summary}\n\n" |
|
|
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید." |
|
|
) |
|
|
else: |
|
|
context_summary = data_manager.get_context_summary(user_id) |
|
|
await update.message.reply_text( |
|
|
f"📊 **اطلاعات تاریخچه مکالمه شخصی شما در این گروه:**\n\n" |
|
|
f"{context_summary}\n\n" |
|
|
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید." |
|
|
) |
|
|
else: |
|
|
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: |
|
|
"""نمایش دستورات کمک""" |
|
|
chat = update.effective_chat |
|
|
|
|
|
if chat.type in ['group', 'supergroup']: |
|
|
help_text = ( |
|
|
"🤖 **دستورات ربات در گروه:**\n\n" |
|
|
"🟢 `/start` - شروع کار با ربات در گروه\n" |
|
|
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n" |
|
|
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n" |
|
|
"🟢 `/help` - نمایش این پیام راهنما\n\n" |
|
|
"📝 **نکته:** ربات به سه صورت کار میکند:\n" |
|
|
"1. پاسخ به پیامهای مستقیم\n" |
|
|
"2. پاسخ وقتی منشن میشوید\n" |
|
|
"3. پاسخ به ریپلایها (روی پیامهای من یا دیگران)\n\n" |
|
|
f"**حالت فعلی:** {data_manager.get_context_mode()}\n" |
|
|
"• separate: هر کاربر تاریخچه جداگانه (8192 توکن)\n" |
|
|
"• group_shared: تاریخچه مشترک برای همه (16384 توکن)\n" |
|
|
"• hybrid: ترکیب هر دو\n\n" |
|
|
"💡 **توجه:** در حالت group_shared، ربات میتواند تا 16384 توکن از تاریخچه مکالمه گروه را به خاطر بسپارد." |
|
|
) |
|
|
else: |
|
|
help_text = ( |
|
|
"🤖 **دستورات ربات:**\n\n" |
|
|
"🟢 `/start` - شروع کار با ربات\n" |
|
|
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n" |
|
|
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n" |
|
|
"🟢 `/help` - نمایش این پیام راهنما\n\n" |
|
|
"📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۲۰۴۸ توکن ذخیره میکند. " |
|
|
"میتوانید روی پیامهای من ریپلای کنید تا من ارتباط را بهتر بفهمم.\n" |
|
|
"برای شروع مکالمه جدید از دستور /clear استفاده کنید." |
|
|
) |
|
|
|
|
|
await update.message.reply_text(help_text, parse_mode='Markdown') |
|
|
|
|
|
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: |
|
|
|
|
|
if not update.message: |
|
|
return |
|
|
|
|
|
user_id = update.effective_user.id |
|
|
chat = update.effective_chat |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
message_text = update.message.text or update.message.caption or "" |
|
|
if not message_text: |
|
|
return |
|
|
|
|
|
if data_manager.contains_blocked_words(message_text): |
|
|
logger.info(f"User {user_id} sent a message with a blocked word.") |
|
|
return |
|
|
|
|
|
if chat.type in ['group', 'supergroup']: |
|
|
|
|
|
if chat.id in group_tasks and not group_tasks[chat.id].done(): |
|
|
group_tasks[chat.id].cancel() |
|
|
logger.info(f"Cancelled previous task for group {chat.id} to start a new one.") |
|
|
|
|
|
task = asyncio.create_task(_process_group_request(update, context)) |
|
|
group_tasks[chat.id] = task |
|
|
task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, chat.id)) |
|
|
else: |
|
|
|
|
|
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_tasks, user_id)) |
|
|
|
|
|
async def mention_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: |
|
|
"""هندلر برای زمانی که ربات در گروه منشن میشود""" |
|
|
if not update.message: |
|
|
return |
|
|
|
|
|
if update.effective_chat.type in ['group', 'supergroup']: |
|
|
|
|
|
replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context) |
|
|
reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot) |
|
|
|
|
|
|
|
|
message_text = update.message.text or "" |
|
|
bot_username = context.bot.username |
|
|
|
|
|
|
|
|
if bot_username and f"@{bot_username}" in message_text: |
|
|
message_text = message_text.replace(f"@{bot_username}", "").strip() |
|
|
|
|
|
if message_text: |
|
|
|
|
|
user_name = update.effective_user.first_name |
|
|
|
|
|
|
|
|
if reply_info and reply_info.get('replied_text'): |
|
|
formatted_message = format_reply_message( |
|
|
message_text, |
|
|
reply_info.get('replied_user_name', 'Unknown'), |
|
|
reply_info.get('replied_text'), |
|
|
reply_info.get('is_reply_to_bot', False), |
|
|
user_name |
|
|
) |
|
|
else: |
|
|
formatted_message = message_text |
|
|
|
|
|
|
|
|
if update.effective_chat.id in group_tasks and not group_tasks[update.effective_chat.id].done(): |
|
|
group_tasks[update.effective_chat.id].cancel() |
|
|
logger.info(f"Cancelled previous task for group {update.effective_chat.id} to start a new one.") |
|
|
|
|
|
task = asyncio.create_task(_process_group_request(update, context, formatted_message, reply_info)) |
|
|
group_tasks[update.effective_chat.id] = task |
|
|
task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, update.effective_chat.id)) |
|
|
else: |
|
|
await update.message.reply_text("بله؟ چگونه میتوانم کمک کنم؟") |
|
|
|
|
|
async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: |
|
|
"""هندلر مخصوص ریپلایها""" |
|
|
|
|
|
if not update.message: |
|
|
return |
|
|
|
|
|
|
|
|
message_text = update.message.text or update.message.caption or "" |
|
|
if not message_text: |
|
|
return |
|
|
|
|
|
user_id = update.effective_user.id |
|
|
chat = update.effective_chat |
|
|
|
|
|
|
|
|
if data_manager.is_user_banned(user_id): |
|
|
return |
|
|
|
|
|
|
|
|
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS: |
|
|
return |
|
|
|
|
|
|
|
|
if data_manager.contains_blocked_words(message_text): |
|
|
return |
|
|
|
|
|
if chat.type in ['group', 'supergroup']: |
|
|
|
|
|
if chat.id in group_tasks and not group_tasks[chat.id].done(): |
|
|
group_tasks[chat.id].cancel() |
|
|
logger.info(f"Cancelled previous task for group {chat.id} to start a new one.") |
|
|
|
|
|
task = asyncio.create_task(_process_group_request(update, context)) |
|
|
group_tasks[chat.id] = task |
|
|
task.add_done_callback(lambda t: _cleanup_task(t, group_tasks, chat.id)) |
|
|
else: |
|
|
|
|
|
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_tasks, 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.REPLY, |
|
|
reply_handler |
|
|
)) |
|
|
|
|
|
|
|
|
application.add_handler(MessageHandler( |
|
|
filters.TEXT & filters.Entity("mention") & filters.ChatType.GROUPS, |
|
|
mention_handler |
|
|
)) |
|
|
|
|
|
|
|
|
application.add_handler(MessageHandler( |
|
|
filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE & ~filters.REPLY, |
|
|
handle_message |
|
|
)) |
|
|
|
|
|
|
|
|
application.add_handler(MessageHandler( |
|
|
filters.TEXT & ~filters.COMMAND & filters.ChatType.GROUPS & ~filters.Entity("mention") & ~filters.REPLY, |
|
|
handle_message |
|
|
)) |
|
|
|
|
|
|
|
|
admin_panel.setup_admin_handlers(application) |
|
|
|
|
|
|
|
|
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: |
|
|
logger.error(f"Exception while handling an update: {context.error}") |
|
|
try: |
|
|
if update and update.message: |
|
|
await update.message.reply_text("❌ خطایی در پردازش درخواست شما رخ داد.") |
|
|
except: |
|
|
pass |
|
|
|
|
|
application.add_error_handler(error_handler) |
|
|
|
|
|
port = int(os.environ.get("PORT", 8443)) |
|
|
webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook" |
|
|
|
|
|
if webhook_url: |
|
|
application.run_webhook( |
|
|
listen="0.0.0.0", |
|
|
port=port, |
|
|
webhook_url=webhook_url, |
|
|
url_path="webhook" |
|
|
) |
|
|
else: |
|
|
application.run_polling() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |