Spaces:
Running
Running
Upload bot_core.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838import asyncioimport reimport loggingimport tempfileimport os
from pyrogram import Client, filtersfrom pyrogram.handlers import MessageHandler, CallbackQueryHandlerfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButtonfrom pyrogram.errors import MessageNotModified
import configimport database as db
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
bot_client = Noneuser_client = Noneuser_states = {}
def is_admin(user_id): return user_id in config.ADMINS
def clean_text(text): if not text: return text
if isinstance(text, str): text = re.sub(r'https?://\S+', '', text) text = re.sub(r'@\w+', '', text)
for word in db.get_blocked_words(): if word and word in text: return None
return '\n'.join(line for line in text.splitlines() if line.strip())
return text
def apply_tail(text, tail): if tail: return f"{text}\n{tail}" if text else tail return text
async def notify_admins(text): for admin_id in config.ADMINS: try: await bot_client.send_message(admin_id, f"⚠️ {text}") except Exception as e: logger.error(f"فشل إشعار الأدمن {admin_id}: {e}")
async def safe_edit(callback, text, reply_markup=None): try: await callback.edit_message_text(text, reply_markup=reply_markup) except MessageNotModified: try: await callback.answer() except Exception: pass except Exception as e: logger.error(f"فشل تعديل الرسالة: {e}") try: await callback.answer("حدث خطأ أثناء تحديث القائمة.", show_alert=True) except Exception: pass
async def resolve_chat_id(raw, prefer_user=True): raw = str(raw).strip()
match = re.match(r'(?:https?://)?t\.me/([A-Za-z0-9_]+)', raw) if match: raw = "@" + match.group(1)
client = user_client if prefer_user and user_client else bot_client
if raw.startswith("@"): chat = await client.get_chat(raw) return int(chat.id)
return int(raw)
main_keyboard = InlineKeyboardMarkup([ [ InlineKeyboardButton("📢 إدارة قنوات النشر", callback_data="menu_channels"), InlineKeyboardButton("🌐 إدارة المصادر العامة", callback_data="menu_public_src") ], [ InlineKeyboardButton("🚫 إدارة الكلمات المحظورة", callback_data="menu_blocked"), InlineKeyboardButton("📊 إدارة الإحصائيات", callback_data="stats") ], [ InlineKeyboardButton("📥 تصدير الإعدادات", callback_data="export_data"), InlineKeyboardButton("📤 استيراد الإعدادات", callback_data="import_data") ]])
async def start(client, message): user_id = message.from_user.id user_states.pop(user_id, None)
logger.info(f"📥 /start من ID: {user_id}")
if not is_admin(user_id): await message.reply(f"❌ غير مصرح. معرفك: `{user_id}`") return
await message.reply("أهلاً بك في لوحة تحكم البوت:", reply_markup=main_keyboard)
async def export_callback(client, callback): try: data_str = db.export_data()
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as tmp: tmp.write(data_str) tmp_path = tmp.name
await callback.message.reply_document(document=tmp_path, file_name="backup.json") os.unlink(tmp_path) await callback.answer("تم إرسال ملف النسخة الاحتياطية.") except Exception as e: logger.error(f"فشل التصدير: {e}") await callback.answer("فشل التصدير.", show_alert=True)
async def import_callback(client, callback): user_states[callback.from_user.id] = {"state": "waiting_import"} await safe_edit(callback, "أرسل ملف JSON الذي تريد استيراده:")
async def handle_import(client, message): if not is_admin(message.from_user.id): return
uid = message.from_user.id
if uid not in user_states or user_states[uid].get("state") != "waiting_import": return
if not message.document: await message.reply("❌ أرفق ملف JSON صحيح.") return
try: file_path = await message.download() with open(file_path, "r", encoding="utf-8") as f: data = f.read()
db.import_data(data) await message.reply("✅ تم استيراد الإعدادات بنجاح.") except Exception as e: await message.reply(f"❌ فشل الاستيراد: {e}") finally: user_states.pop(uid, None)
def channel_buttons(ch_id, ch): paused_text = "⏸️ موقوفة" if ch.get('paused') else "✅ شغالة"
return InlineKeyboardMarkup([ [InlineKeyboardButton(f"⏯️ {paused_text}", callback_data=f"toggle_{ch_id}")], [InlineKeyboardButton("📝 التوقيع", callback_data=f"tailmenu_{ch_id}")], [InlineKeyboardButton("🔍 المصادر المخصصة", callback_data=f"specsrc_{ch_id}")], [InlineKeyboardButton("🗑 حذف القناة", callback_data=f"delchannel_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels")] ])
async def menu_channels(client, callback): channels = db.get_all_channels()
if not channels: text = "لا توجد قنوات." buttons = [ [InlineKeyboardButton("➕ إضافة قناة", callback_data="add_channel")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")] ] else: text = "**اختر قناة لإدارتها:**\n" buttons = []
for ch in channels: paused = " ⏸️" if ch.get('paused') else "" name = ch.get("name") or ch["id"] text += f"\n✅ `{ch['id']}` - {name}{paused}" buttons.append([InlineKeyboardButton(f"{name} ⚙️", callback_data=f"ch_{ch['id']}")])
buttons.append([InlineKeyboardButton("➕ إضافة قناة", callback_data="add_channel")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")])
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def show_channels_menu_from_message(message): channels = db.get_all_channels()
if not channels: text = "لا توجد قنوات." buttons = [ [InlineKeyboardButton("➕ إضافة قناة", callback_data="add_channel")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")] ] else: text = "**قنوات النشر المضافة:**\n" buttons = []
for ch in channels: paused = " ⏸️" if ch.get('paused') else "" name = ch.get("name") or ch["id"] text += f"\n✅ `{ch['id']}` - {name}{paused}" buttons.append([InlineKeyboardButton(f"{name} ⚙️", callback_data=f"ch_{ch['id']}")])
buttons.append([InlineKeyboardButton("➕ إضافة قناة", callback_data="add_channel")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")])
await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
async def channel_settings(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
await safe_edit(callback, f"إعدادات القناة `{ch_id}`", channel_buttons(ch_id, ch))
async def add_channel_prompt(client, callback): user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_channel_id"} await safe_edit(callback, "أرسل يوزر القناة أو رابطها أو ID:")
async def toggle_pause(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
db.update_channel(ch_id, "paused", not ch.get("paused")) await callback.answer("تم التحديث.") await channel_settings(client, callback)
async def delete_channel_prompt(client, callback): channels = db.get_all_channels()
if not channels: await callback.answer("لا توجد قنوات.") return
buttons = []
for ch in channels: name = ch.get("name") or ch["id"] buttons.append([InlineKeyboardButton(f"{name} ({ch['id']})", callback_data=f"confirm_del_{ch['id']}")])
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels")]) await safe_edit(callback, "اختر القناة التي تريد حذفها:", InlineKeyboardMarkup(buttons))
async def confirm_delete_channel(client, callback): ch_id = callback.data.split("_", 2)[2] db.delete_channel(ch_id) await callback.answer("تم الحذف.") await menu_channels(client, callback)
async def tail_menu(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
current = ch.get("tail", "") text = f"التوقيع الحالي:\n`{current}`" if current else "لا يوجد توقيع."
buttons = [ [InlineKeyboardButton("✏️ تعديل/إضافة", callback_data=f"edittail_{ch_id}")], [InlineKeyboardButton("🗑 حذف التوقيع", callback_data=f"deltail_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")] ]
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def edit_tail_prompt(client, callback): ch_id = callback.data.split("_", 1)[1] user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_tail", "ch_id": ch_id} await safe_edit(callback, "أرسل نص التوقيع الجديد:")
async def delete_tail(client, callback): ch_id = callback.data.split("_", 1)[1] db.update_channel(ch_id, "tail", "") await callback.answer("تم حذف التوقيع.") await tail_menu(client, callback)
async def menu_public_sources(client, callback): srcs = db.get_public_sources()
text = "**المصادر العامة:**\n" text += "\n".join(f"`{s}`" for s in srcs) if srcs else "لا توجد."
buttons = [ [InlineKeyboardButton("➕ إضافة مصدر عام", callback_data="add_public_src")], [InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")] ]
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def add_public_src_prompt(client, callback): user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_public_source"} await safe_edit(callback, "أرسل رابط أو يوزر أو ID المصدر العام:")
async def del_public_src_prompt(client, callback): srcs = db.get_public_sources()
if not srcs: await callback.answer("لا توجد مصادر.") return
buttons = []
for idx, src in enumerate(srcs): buttons.append([InlineKeyboardButton(f"حذف {src}", callback_data=f"del_pub_idx_{idx}")])
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_public_src")]) await safe_edit(callback, "اختر المصدر للحذف:", InlineKeyboardMarkup(buttons))
async def confirm_del_public_src(client, callback): idx = int(callback.data.split("_")[-1]) srcs = db.get_public_sources()
if idx < 0 or idx >= len(srcs): await callback.answer("المصدر غير موجود.") return
db.remove_public_source(srcs[idx]) await callback.answer("تم الحذف.") await menu_public_sources(client, callback)
async def menu_blocked_words(client, callback): words = db.get_blocked_words()
text = "**الكلمات المحظورة:**\n" text += ", ".join(words) if words else "لا توجد."
buttons = [ [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")], [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")] ]
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def add_blocked_word_prompt(client, callback): user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_blocked_word"} await safe_edit(callback, "أرسل الكلمة المحظورة:")
async def del_blocked_word_prompt(client, callback): words = db.get_blocked_words()
if not words: await callback.answer("لا توجد.") return
buttons = []
for idx, word in enumerate(words): buttons.append([InlineKeyboardButton(f"حذف {word}", callback_data=f"delword_idx_{idx}")])
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_blocked")]) await safe_edit(callback, "اختر الكلمة:", InlineKeyboardMarkup(buttons))
async def confirm_del_blocked_word(client, callback): idx = int(callback.data.split("_")[-1]) words = db.get_blocked_words()
if idx < 0 or idx >= len(words): await callback.answer("الكلمة غير موجودة.") return
db.remove_blocked_word(words[idx]) await callback.answer("تم الحذف.") await menu_blocked_words(client, callback)
async def manage_special_sources(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
sources = ch.get("special_sources", [])
text = "**المصادر المخصصة:**\n" text += "\n".join(f"• `{s}`" for s in sources) if sources else "لا توجد."
buttons = [ [InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}")], [InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")] ]
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def add_special_source_prompt(client, callback): ch_id = callback.data.split("_", 1)[1] user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = { "state": "waiting_special_source", "ch_id": ch_id } await safe_edit(callback, "أرسل رابط أو يوزر أو ID المصدر المخ��ص:")
async def delete_special_source_prompt(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
sources = ch.get("special_sources", [])
if not sources: await callback.answer("لا توجد مصادر.") return
buttons = []
for idx, src in enumerate(sources): buttons.append([InlineKeyboardButton(f"حذف {src}", callback_data=f"confdelspec_{ch_id}_{idx}")])
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"specsrc_{ch_id}")]) await safe_edit(callback, "اختر المصدر لحذفه:", InlineKeyboardMarkup(buttons))
async def confirm_delete_special_source(client, callback): parts = callback.data.split("_") ch_id = parts[1] idx = int(parts[2])
ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
sources = ch.get("special_sources", [])
if idx < 0 or idx >= len(sources): await callback.answer("المصدر غير موجود.") return
sources.pop(idx) db.update_channel(ch_id, "special_sources", sources)
await callback.answer("تم الحذف.") await manage_special_sources(client, callback)
async def show_stats(client, callback): channels = db.get_all_channels() total_posts = sum(ch.get("posts_count", 0) for ch in channels) pub_src = len(db.get_public_sources()) words = len(db.get_blocked_words())
text = "📊 **الإحصائيات:**\n\n" text += f"• إجمالي المنشورات: **{total_posts}**\n" text += f"• قنوات النشر: {len(channels)}\n" text += f"• المصادر العامة: {pub_src}\n" text += f"• الكلمات المحظورة: {words}\n\n"
if channels: text += "**تفصيل المنشورات:**\n" for ch in channels: text += f"`{ch['id']}`: {ch.get('posts_count', 0)}\n"
await safe_edit( callback, text, InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]]) )
async def handle_text_input(client, message): if not is_admin(message.from_user.id): return
uid = message.from_user.id
if uid not in user_states: return
state = user_states[uid].get("state") text = message.text.strip()
try: if state == "waiting_channel_id": chat_id = await resolve_chat_id(text, prefer_user=False) db.add_channel(chat_id, name=text) await message.reply("✅ تمت إضافة القناة. تأكد أن البوت أدمن فيها.") await show_channels_menu_from_message(message)
elif state == "waiting_tail": ch_id = user_states[uid]["ch_id"] db.update_channel(ch_id, "tail", text) await message.reply("✅ تم حفظ التوقيع.")
elif state == "waiting_public_source": source_id = await resolve_chat_id(text, prefer_user=True) db.add_public_source(source_id) await message.reply(f"✅ تم إضافة المصدر العام:\n`{source_id}`")
elif state == "waiting_blocked_word": db.add_blocked_word(text) await message.reply("✅ تم إضافة الكلمة المحظورة.")
elif state == "waiting_special_source": ch_id = user_states[uid]["ch_id"] source_id = await resolve_chat_id(text, prefer_user=True)
ch = db.get_channel(ch_id) if not ch: await message.reply("❌ القناة غير موجودة.") return
sources = ch.get("special_sources", [])
if source_id not in sources: sources.append(source_id)
db.update_channel(ch_id, "special_sources", sources) await message.reply(f"✅ تم إضافة المصدر المخصص:\n`{source_id}`")
except Exception as e: logger.error(f"خطأ في إدخال المستخدم: {e}") await message.reply(f"❌ فشل التنفيذ: {e}")
finally: user_states.pop(uid, None)
async def user_message_handler(client, message): if message.chat.type not in ("channel", "supergroup"): return
chat_id = int(message.chat.id) raw_text = message.text or message.caption or ""
logger.info("🔥 تم التقاط رسالة جديدة بواسطة user_client") logger.info(f"🔥 نوع المحادثة = {message.chat.type}") logger.info(f"🔥 chat_id = {chat_id}") logger.info(f"🔥 public_sources = {db.get_public_sources()}") logger.info(f"🔥 channels = {db.get_all_channels()}")
logger.info(f"📨 رسالة من {chat_id} | نص: {str(raw_text)[:50]}...")
all_channels = db.get_all_channels() public_sources = set()
for src in db.get_public_sources(): try: public_sources.add(int(src)) except Exception: pass
target_ids = set()
if chat_id in public_sources: for ch in all_channels: specials = ch.get("special_sources") or [] if not specials and not ch.get("paused"): target_ids.add(int(ch["id"]))
for ch in all_channels: specials = set() for src in ch.get("special_sources") or []: try: specials.add(int(src)) except Exception: pass
if chat_id in specials and not ch.get("paused"): target_ids.add(int(ch["id"]))
logger.info(f"🎯 القنوات المستهدفة: {target_ids}")
if not target_ids: return
if raw_text and any(w in raw_text for w in db.get_blocked_words()): logger.info("⛔ منشور مرفوض لكلمة محظورة") return
if message.media: try: fwd = await user_client.forward_messages( config.MIDDLE_CHANNEL, message.chat.id, message.id ) await asyncio.sleep(0.3) except Exception as e: logger.error(f"فشل التوجيه للوسيطة: {e}") await notify_admins(f"فشل توجيه رسالة من {chat_id} إلى الوسيطة: {e}") return
for target in target_ids: try: ch = db.get_channel(target) if not ch: continue
cleaned = clean_text(raw_text) if cleaned is None: continue
final = apply_tail(cleaned, ch.get("tail", ""))
await bot_client.copy_message( chat_id=target, from_chat_id=config.MIDDLE_CHANNEL, message_id=fwd.id, caption=final if final else None )
db.increment_post_count(target) logger.info(f"✅ نُشر إلى {target}") await asyncio.sleep(0.5)
except Exception as e: logger.error(f"نشر فاشل إلى {target}: {e}") await notify_admins(f"فشل النشر إلى {target}: {e}")
else: for target in target_ids: try: ch = db.get_channel(target) if not ch: continue
cleaned = clean_text(raw_text) if cleaned is None: continue
final = apply_tail(cleaned, ch.get("tail", ""))
if final: await bot_client.send_message(target, final)
db.increment_post_count(target) logger.info(f"✅ نُشر نص إلى {target}") await asyncio.sleep(0.5)
except Exception as e: logger.error(f"إرسال فاشل إلى {target}: {e}") await notify_admins(f"فشل الإرسال إلى {target}: {e}")
async def middle_channel_handler(client, message): if int(message.chat.id) != int(config.MIDDLE_CHANNEL): return
logger.info("📥 رسالة في الوسيطة، جارٍ النشر...")
all_channels = db.get_all_channels() raw_text = message.text or message.caption or ""
if raw_text and any(w in raw_text for w in db.get_blocked_words()): logger.info("⛔ كلمة محظورة - لم تُنشر") return
for ch in all_channels: if ch.get("paused"): continue
target = int(ch["id"])
try: cleaned = clean_text(raw_text) if raw_text else "" if cleaned is None: continue
final = apply_tail(cleaned, ch.get("tail", ""))
if message.media: await bot_client.copy_message( chat_id=target, from_chat_id=config.MIDDLE_CHANNEL, message_id=message.id, caption=final if final else None ) else: await bot_client.send_message(target, final if final else ".")
db.increment_post_count(target) logger.info(f"✅ نُشر من الوسيطة إلى {target}") await asyncio.sleep(0.5)
except Exception as e: logger.error(f"نشر فاشل من الوسيطة إلى {target}: {e}") await notify_admins(f"فشل النشر من الوسيطة إلى {target}: {e}")
def register_bot_handlers(app: Client): app.add_handler(MessageHandler(start, filters.command("start"))) app.add_handler(MessageHandler(handle_import, filters.document))
async def callback_dispatcher(client, callback): data = callback.data
if data == "main_menu": await safe_edit(callback, "القائمة الرئيسية:", main_keyboard) elif data == "menu_channels": await menu_channels(client, callback) elif data.startswith("ch_"): await channel_settings(client, callback) elif data == "add_channel": await add_channel_prompt(client, callback) elif data.startswith("toggle_"): await toggle_pause(client, callback) elif data.startswith("delchannel_"): await delete_channel_prompt(client, callback) elif data.startswith("confirm_del_"): await confirm_delete_channel(client, callback) elif data.startswith("tailmenu_"): await tail_menu(client, callback) elif data.startswith("edittail_"): await edit_tail_prompt(client, callback) elif data.startswith("deltail_"): await delete_tail(client, callback) elif data == "menu_public_src": await menu_public_sources(client, callback) elif data == "add_public_src": await add_public_src_prompt(client, callback) elif data == "del_public_src": await del_public_src_prompt(client, callback) elif data.startswith("del_pub_idx_"): await confirm_del_public_src(client, callback) elif data == "menu_blocked": await menu_blocked_words(client, callback) elif data == "add_blocked_word": await add_blocked_word_prompt(client, callback) elif data == "del_blocked_word": await del_blocked_word_prompt(client, callback) elif data.startswith("delword_idx_"): await confirm_del_blocked_word(client, callback) elif data.startswith("specsrc_"): await manage_special_sources(client, callback) elif data.startswith("addspecsrc_"): await add_special_source_prompt(client, callback) elif data.startswith("delspecsrc_"): await delete_special_source_prompt(client, callback) elif data.startswith("confdelspec_"): await confirm_delete_special_source(client, callback) elif data == "stats": await show_stats(client, callback) elif data == "export_data": await export_callback(client, callback) elif data == "import_data": await import_callback(client, callback) else: await callback.answer("غير معروف.")
app.add_handler(CallbackQueryHandler(callback_dispatcher)) app.add_handler(MessageHandler(handle_text_input, filters.text & filters.private))
def register_user_handlers(app: Client): # نلتقط كل رسائل حساب المستخدم ثم نفلتر داخل user_message_handler # هذا يساعدنا نعرف هل SESSION_STRING يلتقط المصادر العامة أو لا app.add_handler(MessageHandler(user_message_handler))
def register_middle_handlers(app: Client): app.add_handler(MessageHandler(middle_channel_handler, filters.chat(config.MIDDLE_CHANNEL)))
async def run_clients(): global bot_client, user_client
os.makedirs("/data/sessions", exist_ok=True)
bot_client = Client( "/data/sessions/bot_session", api_id=config.API_ID, api_hash=config.API_HASH, bot_token=config.BOT_TOKEN )
user_client = Client( "/data/sessions/user_session", api_id=config.API_ID, api_hash=config.API_HASH, session_string=config.SESSION_STRING )
register_bot_handlers(bot_client) register_user_handlers(user_client) register_middle_handlers(bot_client)
await bot_client.start() await user_client.start()
logger.info("✅ البوتان شغّالان") await asyncio.Event().wait()
def run_bot(): lock_file = "/tmp/telegram_bot_core_running.lock"
if os.path.exists(lock_file): logger.warning("⚠️ البوت يعمل مسبقاً، تم منع تشغيل نسخة ثانية.") return
with open(lock_file, "w") as f: f.write(str(os.getpid()))
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
try: loop.run_until_complete(run_clients()) except KeyboardInterrupt: pass except Exception as e: logger.exception(f"توقف البوت بسبب خطأ: {e}") finally: try: if bot_client: loop.run_until_complete(bot_client.stop()) except Exception: pass
try: if user_client: loop.run_until_complete(user_client.stop()) except Exception: pass
try: if os.path.exists(lock_file): os.remove(lock_file) except Exception: pass
loop.close()bot_core.pyAdded+838