Homam1997's picture
Create main.py
ac935b2 verified
Raw History Blame Contribute Delete
7.64 kB
import os
import re
import logging
import traceback
import html
import asyncio
from typing import Optional
from threading import Thread
from flask import Flask
from dotenv import load_dotenv
# ุงู„ุญุฒู… ุงู„ุฃุณุงุณูŠุฉ
import motor.motor_asyncio
import google.generativeai as genai
from telegram import Update, User, Sticker, ReplyKeyboardMarkup
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
MessageHandler,
ContextTypes,
filters,
)
# --- 1. ุฅุนุฏุงุฏ Flask ู„ุถู…ุงู† ุงุณุชู‚ุฑุงุฑ ุงู„ุงุณุชุถุงูุฉ ---
flask_app = Flask('')
@flask_app.route('/')
def home():
return "CyberZone Bot is Online! ๐Ÿš€"
def run_flask():
# Hugging Face ูˆ Render ูŠุณุชุฎุฏู…ูˆู† ุงู„ู…ู†ูุฐ 7860 ุฃูˆ PORT
port = int(os.environ.get("PORT", 7860))
flask_app.run(host='0.0.0.0', port=port)
def keep_alive():
t = Thread(target=run_flask)
t.daemon = True
t.start()
# --- 2. ุงู„ุฅุนุฏุงุฏุงุช ูˆุงู„ุจูŠุฆุฉ ---
load_dotenv()
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
# ุฅุนุฏุงุฏ Gemini
GEMINI_KEY = os.getenv("GEMINI_API_KEY")
if GEMINI_KEY:
genai.configure(api_key=GEMINI_KEY)
model = genai.GenerativeModel('gemini-1.5-flash')
else:
logger.warning("GEMINI_API_KEY missing. AI features disabled.")
model = None
# ุฅุนุฏุงุฏ MongoDB
MONGO_URI = os.getenv("MONGO_URI")
client = motor.motor_asyncio.AsyncIOMotorClient(
MONGO_URI,
serverSelectionTimeoutMS=5000
)
db = client["CyberZone_DB"]
users_col = db["users"]
stickers_col = db["stickers"]
BOT_DISPLAY_NAME = "CyberZone ID Inspector"
ID_REGEX = re.compile(r"\b(\d{8,12})\b")
# --- 3. ุงู„ุฏูˆุงู„ ุงู„ู…ุณุงุนุฏุฉ ---
def clean_markdown(text: str) -> str:
if not text: return "N/A"
escape_chars = r'_*[]()~`>#+-=|{}.!'
return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', str(text))
def format_size(size_bytes: Optional[int]) -> str:
if not size_bytes: return "Unknown"
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024.0: return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} TB"
# --- 4. ู…ุนุงู„ุฌ ุงู„ุฃุฎุทุงุก ุงู„ุฐูƒูŠ ---
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
logger.error("Exception:", exc_info=context.error)
tb_string = "".join(traceback.format_exception(None, context.error, context.error.__traceback__))
ai_explanation = "AI Analysis is disabled."
if model:
try:
prompt = f"Explain this Telegram Bot error in Arabic briefly:\n{tb_string[-1000:]}"
response = await asyncio.to_thread(model.generate_content, prompt)
ai_explanation = response.text
except Exception as e:
ai_explanation = f"AI failed: {e}"
admin_id = os.getenv("ADMIN_ID")
if admin_id:
error_msg = f"๐Ÿšจ <b>Smart Error Report</b>\n\nโŒ <b>Error:</b> <code>{html.escape(str(context.error))}</code>\n\n๐Ÿค– <b>AI Analysis:</b>\n{ai_explanation}"
await context.bot.send_message(chat_id=int(admin_id), text=error_msg[:4000], parse_mode="HTML")
# --- 5. ู…ู†ุทู‚ ุงู„ุจูŠุงู†ุงุช ---
async def store_user(user: Optional[User]):
if not user: return
await users_col.update_one(
{"_id": user.id},
{"$set": {
"username": user.username,
"first_name": user.first_name,
"last_name": user.last_name,
"premium": getattr(user, "is_premium", False),
}},
upsert=True
)
# --- 6. ู…ุนุงู„ุฌุงุช ุงู„ุฑุณุงุฆู„ ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await store_user(update.effective_user)
buttons = [["๐Ÿ” Inspector"], ["โ“ Help", "๐Ÿ‘จโ€๐Ÿ’ป Contact Developer"]]
await update.message.reply_text(
f"Welcome to **{BOT_DISPLAY_NAME}**",
parse_mode="Markdown",
reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True)
)
async def inspector_message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
msg = update.effective_message
uid = update.effective_user.id
if not msg or not context.bot_data.get("inspector_mode", {}).get(uid):
return
await store_user(update.effective_user)
status_msg = None
if any([msg.photo, msg.video, msg.document, msg.sticker]):
status_msg = await msg.reply_text("โณ **Processing Metadata...**", parse_mode="Markdown")
try:
if msg.forward_origin:
fwd = msg.forward_origin
if hasattr(fwd, 'sender_user') and fwd.sender_user:
u = fwd.sender_user
await store_user(u)
info = f"๐Ÿ‘ค **User**\n**ID:** `{u.id}`\n**Name:** {clean_markdown(u.full_name)}\n**User:** @{clean_markdown(u.username)}"
elif hasattr(fwd, 'chat') and fwd.chat:
c = fwd.chat
info = f"๐Ÿ“ข **Channel**\n**ID:** `{c.id}`\n**Title:** {clean_markdown(c.title)}"
else:
info = "๐Ÿ•ต๏ธ **Hidden Source**"
await msg.reply_text(info, parse_mode="Markdown")
elif msg.photo:
p = msg.photo[-1]
await msg.reply_text(f"๐Ÿ“ท **Photo**\n**Res:** {p.width}x{p.height}\n**Size:** {format_size(p.file_size)}", parse_mode="Markdown")
elif msg.sticker:
await msg.reply_text(f"๐Ÿ™‚ **Sticker**\n**Set:** `{msg.sticker.set_name}`\n**ID:** `{msg.sticker.file_id}`", parse_mode="Markdown")
elif msg.text:
match = ID_REGEX.search(msg.text)
if match:
target_id = int(match.group(1))
data = await users_col.find_one({"_id": target_id})
if data:
res = f"๐Ÿ†” **DB Match**\n**ID:** `{target_id}`\n**Name:** {clean_markdown(data.get('first_name'))}"
else:
res = f"๐Ÿ†” **ID Detected:** `{target_id}`\n*(Not in DB)*"
await msg.reply_text(res, parse_mode="Markdown")
finally:
if status_msg: await status_msg.delete()
async def keyboard_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text
uid = update.effective_user.id
context.bot_data.setdefault("inspector_mode", {})
if text == "๐Ÿ” Inspector":
context.bot_data["inspector_mode"][uid] = True
await update.message.reply_text("๐Ÿ” **Mode: ON**", reply_markup=ReplyKeyboardMarkup([["๐Ÿ”™ Back"]], resize_keyboard=True))
elif text == "๐Ÿ”™ Back":
context.bot_data["inspector_mode"][uid] = False
await update.message.reply_text("โœ… **Mode: OFF**", reply_markup=ReplyKeyboardMarkup([["๐Ÿ” Inspector"], ["โ“ Help", "๐Ÿ‘จโ€๐Ÿ’ป Contact Developer"]], resize_keyboard=True))
elif text == "๐Ÿ‘จโ€๐Ÿ’ป Contact Developer":
await update.message.reply_text("๐Ÿค– **Dev:** @CyberZone_Admin")
# --- 7. ุงู„ุชุดุบูŠู„ ุงู„ุฑุฆูŠุณูŠ ---
def main():
keep_alive()
token = os.getenv("BOT_TOKEN")
if not token: return
app = ApplicationBuilder().token(token).build()
app.add_error_handler(error_handler)
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & filters.Regex(r"^(๐Ÿ” Inspector|๐Ÿ”™ Back|โ“ Help|๐Ÿ‘จโ€๐Ÿ’ป Contact Developer)$"), keyboard_handler))
app.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, inspector_message_handler))
print("๐Ÿš€ Bot is running on Hugging Face...")
app.run_polling(drop_pending_updates=True)
if __name__ == "__main__":
main()