Spaces:
Running on Zero
Running on Zero
Download TechVJ/start.py from Agnivesh10M/src: direct link, hf CLI and curl.
- Browser
- Download file 50.5 kB
-
https://huggingface.co/spaces/Agnivesh10M/src/resolve/main/TechVJ/start.py
- Command line
-
hf download hf://spaces/Agnivesh10M/src/TechVJ/start.py
-
curl -L -o start.py https://huggingface.co/spaces/Agnivesh10M/src/resolve/main/TechVJ/start.py
50.5 kB
import os
import asyncio
import time
import math
import re
import subprocess
from pyrogram import Client, filters, enums
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram.errors import FloodWait, RPCError
from config import API_ID, API_HASH, ADMINS, CHANNEL_ID, WAITING_TIME
from db import db
try:
from TechVJ.TechVJ.fast_download import fast_download_file
except ImportError:
try:
from TechVJ.fast_download import fast_download_file
except ImportError:
from fast_download import fast_download_file
class batch_temp(object):
IS_BATCH = {}
CLONE_DATA = {}
LAST_SAVED_ID = {}
def humanbytes(size):
if not size:
return "0 B"
power = 1024
t_n = 0
power_labels = {0: ' ', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
while size > power:
size /= power
t_n += 1
return f"{round(size, 2)} {power_labels[t_n]}B"
def time_formatter(seconds: int) -> str:
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = ((str(days) + "d, ") if days else "") + \
((str(hours) + "h, ") if hours else "") + \
((str(minutes) + "m, ") if minutes else "") + \
((str(seconds) + "s") if seconds else "")
return tmp if tmp else "0s"
async def progress_bar(current, total, ud_type, message, start, fname="", current_idx=1, total_count=1, user_id=None):
if user_id and batch_temp.IS_BATCH.get(user_id):
raise asyncio.CancelledError("Task cancelled by user.")
now = time.time()
diff = max(1e-3, now - start)
if round(diff % 2.0) == 0 or current == total:
percentage = current * 100 / total if total > 0 else 0
speed = current / diff if diff > 0 else 0
elapsed_time = round(diff)
eta = round((total - current) / speed) if speed > 0 else 0
bar_length = 10
filled_length = int(bar_length * current // total) if total > 0 else 0
bar = '▰' * filled_length + '▱' * (bar_length - filled_length)
fname_text = f"📁 **फ़ाइल:** `{fname[:30]}...`\n" if fname else ""
remaining = max(0, total_count - current_idx)
status_text = (
f"**{ud_type}**\n"
f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
f"{fname_text}"
f"[{bar}] {percentage:.1f}%\n"
f"⚡ **स्पीड:** {humanbytes(speed)}/s\n"
f"📦 **डन:** {humanbytes(current)} / {humanbytes(total)}\n"
f"⏱️ **ETA:** {time_formatter(eta)} | **समय:** {time_formatter(elapsed_time)}"
)
try:
await message.edit_text(status_text)
except Exception:
pass
def generate_auto_thumb(video_path: str, thumb_path: str):
try:
cmd = [
"ffmpeg", "-ss", "00:00:02", "-i", video_path,
"-vframes", "1", "-q:v", "2", thumb_path, "-y"
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if os.path.exists(thumb_path):
return thumb_path
except Exception:
pass
return None
def strip_all_urls(text: str) -> str:
if not text:
return ""
text = re.sub(r'\[([^\]]+)\]\((https?://[^\)]+|t\.me/[^\)]+)\)', r'\1', text)
text = re.sub(r'https?://\S+|www\.\S+', '', text)
text = re.sub(r't\.me/\S+', '', text)
text = re.sub(r'\n{3,}', '\n\n', text).strip()
return text
# ==================== सामान्य व सूचना कमांड्स ====================
@Client.on_message(filters.command("start") & filters.private)
async def start_msg_handler(client: Client, message: Message):
user_id = message.from_user.id
name = message.from_user.first_name
db.add_user(user_id, name)
start_text = (
f"👋 **नमस्ते {name}!**\n\n"
"🚀 **SRC Content Cloner & Forwarder Bot** में आपका स्वागत है।\n"
"इस बॉट के माध्यम से आप किसी भी पब्लिक, प्राइवेट चैनल, ग्रुप, टॉपिक या बॉट से फ़ाइलें सीधे अपने चैनल/ग्रुप में क्लोन कर सकते हैं।\n\n"
"📌 **मुख्य फीचर्स:**\n"
"• सुपरफास्ट डाउनलोडिंग व अपलोडिंग\n"
"• टॉपिक (Forum Topics) सपोर्ट\n"
"• कैप्शन रिप्लेसमेंट, लिंक्स रिमूवर व हाइपरलिंक टूल\n"
"• ऑटो थंबनेल व रेज़्यूम सपोर्ट\n\n"
"👉 शुरू करने के लिए **/clone** लिखें या नीचे दिए गए बटन्स का उपयोग करें।"
)
buttons = InlineKeyboardMarkup([
[InlineKeyboardButton("📖 उपयोग कैसे करें (Guide)", callback_data="nav_howtouse"),
InlineKeyboardButton("💎 VIP प्लान्स", callback_data="nav_plans")],
[InlineKeyboardButton("📢 चैनल में अपलोड हेल्प", callback_data="nav_channelhelp"),
InlineKeyboardButton("⚡ स्पीड गाइड", callback_data="nav_speedhelp")],
[InlineKeyboardButton("👤 मेरा VIP स्टेटस", callback_data="nav_myplan"),
InlineKeyboardButton("🌐 भाषा (Language)", callback_data="nav_lang")]
])
await message.reply_text(start_text, reply_markup=buttons)
@Client.on_message(filters.command("id"))
async def get_id(client: Client, message: Message):
chat_id = message.chat.id
user_id = message.from_user.id if message.from_user else (message.sender_chat.id if message.sender_chat else "Unknown")
thread_id = getattr(message, "message_thread_id", None)
response = f"📍 **चैट/ग्रुप ID:** `{chat_id}`\n👤 **आपकी ID:** `{user_id}`"
if thread_id:
response += f"\n🧵 **टॉपिक/थ्रेड ID:** `{thread_id}`"
if message.reply_to_message:
rep = message.reply_to_message
rep_user = rep.from_user.id if rep.from_user else (rep.sender_chat.id if rep.sender_chat else "Anonymous")
response += f"\n\n↩️ **रिप्लाई यूजर ID:** `{rep_user}`"
if rep.forward_from_chat:
response += f"\n📢 **फॉरवर्ड चैट ID:** `{rep.forward_from_chat.id}`"
await message.reply_text(response)
@Client.on_message(filters.command(["plans"]) & filters.private)
async def plans_handler(client: Client, message: Message):
plans = db.get_all_plans()
text = (
"💎 **उपलब्ध VIP प्लान्स और कीमतें:**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"🔹 **1 दिन (Trial):** ₹{plans.get('1day', '20')}\n"
f"🔹 **5 दिन:** ₹{plans.get('5days', '50')}\n"
f"🔹 **15 दिन:** ₹{plans.get('15days', '120')}\n"
f"🔹 **30 दिन (महीना):** ₹{plans.get('30days', '199')}\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"💳 पेमेंट करने के लिए **/pay** या **/buy** कमांड भेजें।"
)
await message.reply_text(text)
@Client.on_message(filters.command(["myplan", "info"]) & filters.private)
async def myplan_handler(client: Client, message: Message):
user_id = message.from_user.id
is_vip = db.is_user_vip(user_id, ADMINS)
user_data = db.get_user(user_id)
if user_id in ADMINS:
return await message.reply_text("👑 **आप बॉट के एडमिन हैं!** आपके पास आजीवन असीमित VIP एक्सेस है।")
if is_vip and user_data and user_data.get("plan_expiry"):
exp = str(user_data["plan_expiry"])[:19].replace("T", " ")
await message.reply_text(f"✅ **आप एक एक्टिव VIP मेंबर हैं!**\n\n⏳ **वैधता (Expiry):** `{exp} UTC`")
else:
await message.reply_text("❌ **आपके पास वर्तमान में कोई एक्टिव VIP प्लान नहीं है।**\n\nप्लान देखने के लिए /plans और खरीदने के लिए /pay भेजें।")
@Client.on_message(filters.command(["pay", "buy", "payment"]) & filters.private)
async def pay_handler(client: Client, message: Message):
pay_text = (
"💳 **VIP सब्सक्रिप्शन पेमेंट निर्देश:**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"1. नीचे दिए गए UPI QR कोड या UPI ID पर भुगतान करें:\n"
"👉 UPI ID: `sachin4sharma1210@sbi` (या एडमिन से संपर्क करें)\n\n"
"2. भुगतान पूरा होने के बाद उसका **स्क्रीनशॉट (Screenshot)** और अपनी **User ID** एडमिन को भेजें।\n\n"
"👨💻 **एडमिन संपर्क:** @Sachin4Sharma1210\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"वेरिफिकेशन के 5-10 मिनट के अंदर आपका VIP प्लान एक्टिव कर दिया जाएगा।"
)
await message.reply_text(pay_text)
@Client.on_message(filters.command(["howtouse", "help"]) & filters.private)
async def howtouse_handler(client: Client, message: Message):
help_text = (
"📖 **बॉट का उपयोग कैसे करें? (Quick Guide)**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"1️⃣ सबसे पहले **/login** कमांड भेजकर अपना टेलीग्राम अकाउंट बॉट से कनेक्ट करें।\n"
"2️⃣ इसके बाद **/clone** कमांड भेजें।\n"
"3️⃣ जहाँ से कंटेंट कॉपी करना है, उसकी **पहली लिंक (Start Link)** भेजें।\n"
"4️⃣ इसके बाद **अंतिम लिंक (End Link)** भेजें (अगर एक ही मैसेज चाहिए तो `/single` लिखें)।\n"
"5️⃣ जिस चैनल में अपलोड करना है, उसका लिंक/आईडी भेजें (सीधे बॉट में पाने के लिए `/skip` लिखें)।\n"
"6️⃣ कस्टमाइज़ेशन मेन्यू खुलेगा, जहाँ आप नया कैप्शन, वर्ड रिप्लेसमेंट, लिंक्स रिमूवर या थंबनेल सेट करके **🚀 Confirm & Start** दबाएँ।"
)
await message.reply_text(help_text)
@Client.on_message(filters.command(["channelhelp"]) & filters.private)
async def channelhelp_handler(client: Client, message: Message):
text = (
"📢 **चैनल/ग्रुप में अपलोडिंग सेटअप गाइड:**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"यदि आप फाइल्स को सीधे अपने किसी चैनल या ग्रुप में भेजना चाहते हैं, तो:\n\n"
"1. अपने चैनल/ग्रुप में **बॉट** और **अपने उस अकाउंट (जिससे लॉगिन किया है)** दोनों को **Admin** बनाएँ।\n"
"2. एडमिन बनाते समय **'Post Messages'** की अनुमति अवश्य दें।\n"
"3. स्टेप 3 में चैनल की ID (जैसे: `-1001234567890`) या पब्लिक यूज़रनेम (जैसे: `@mychannel`) भेजें।"
)
await message.reply_text(text)
@Client.on_message(filters.command(["speedhelp", "slowspeed"]) & filters.private)
async def speedhelp_handler(client: Client, message: Message):
text = (
"⚡ **स्पीड और परफॉरमेंस से जुड़ी जानकारी:**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"• बॉट मल्टी-थ्रेडेड और फ़ास्ट ट्रांसमिशन मोड पर काम करता है।\n"
"• टेलीग्राम सर्वर के नियमों के अनुसार बड़ी फाइल्स ट्रांसफर करते समय बीच में 2-3 सेकंड का सेफ टाइमआउट आवश्यक होता है ताकि आपका अकाउंट बैन या म्यूट न हो।\n"
"• यदि स्पीड धीमी लगे, तो कृपया सुनिश्चित करें कि जिस सोर्स चैनल से कंटेंट आ रहा है, उसका सर्वर लोड कम हो।"
)
await message.reply_text(text)
@Client.on_message(filters.command(["lang", "language"]) & filters.private)
async def lang_handler(client: Client, message: Message):
markup = InlineKeyboardMarkup([
[InlineKeyboardButton("🇮🇳 हिन्दी (Hindi)", callback_data="setlang_hi"),
InlineKeyboardButton("🇬🇧 English", callback_data="setlang_en")]
])
await message.reply_text("🌐 **कृपया बॉट की भाषा चुनें / Choose Language:**", reply_markup=markup)
# ==================== एडमिन कमांड्स ====================
@Client.on_message(filters.command("users") & filters.private)
async def users_admin_handler(client: Client, message: Message):
user_id = message.from_user.id
if user_id not in ADMINS:
return
users = db.get_all_users()
vip_count = 0
for u in users:
if u.get("plan_expiry"):
vip_count += 1
await message.reply_text(f"📊 **बॉट आँकड़े (Admin Panel):**\n\n👥 कुल रजिस्टर्ड यूजर्स: `{len(users)}`\n💎 एक्टिव VIP यूजर्स: `{vip_count}`")
@Client.on_message(filters.command("setprice") & filters.private)
async def setprice_handler(client: Client, message: Message):
user_id = message.from_user.id
if user_id not in ADMINS:
return
args = message.text.split()
if len(args) != 3:
return await message.reply_text("⚠️ **उपयोग:** `/setprice <plan_key> <price>`\n(Keys: `1day`, `5days`, `15days`, `30days`)")
key, price = args[1], args[2]
db.set_plan_price(key, price)
await message.reply_text(f"✅ प्लान `{key}` की कीमत सफलतापूर्वक ₹`{price}` सेट कर दी गई है।")
@Client.on_message(filters.command("broadcast") & filters.private)
async def broadcast_handler(client: Client, message: Message):
user_id = message.from_user.id
if user_id not in ADMINS:
return
if not message.reply_to_message:
return await message.reply_text("⚠️ कृपया जिस मैसेज को ब्रॉडकास्ट करना है, उसे रिप्लाई करते हुए `/broadcast` लिखें।")
users = db.get_all_users()
msg = message.reply_to_message
status = await message.reply_text(f"📢 ब्रॉडकास्ट शुरू हो रहा है (कुल यूजर्स: {len(users)})...")
done = 0
failed = 0
for u in users:
uid = u.get("user_id")
try:
await msg.copy(chat_id=uid)
done += 1
await asyncio.sleep(0.05)
except Exception:
failed += 1
await status.edit_text(f"✅ **ब्रॉडकास्ट संपन्न!**\n\nसफल: `{done}`\nअसफल/ब्लॉक: `{failed}`")
# ==================== टास्क नियंत्रण व क्लोनिंग ====================
@Client.on_message(filters.command(["cancel"]))
async def send_cancel(client: Client, message: Message):
user_id = message.from_user.id
batch_temp.IS_BATCH[user_id] = True
await message.reply_text("🛑 **टास्क तुरंत रोक दिया गया है।** यदि इसे वापस वहीं से चलाना हो तो `/resume` भेजें।")
def parse_telegram_link(link: str):
link = link.strip().replace("?single", "")
# 1. प्राइवेट फोरम टॉपिक लिंक: t.me/c/1234567/5/100
c_topic = re.search(r"t\.me/c/(\d+)/(\d+)/(\d+)", link)
if c_topic:
return int("-100" + c_topic.group(1)), int(c_topic.group(3)), int(c_topic.group(2))
# 2. पब्लिक फोरम टॉपिक लिंक: t.me/channelname/5/100
p_topic = re.search(r"t\.me/([^/]+)/(\d+)/(\d+)", link)
if p_topic and p_topic.group(1) not in ["c", "b"]:
return p_topic.group(1), int(p_topic.group(3)), int(p_topic.group(2))
# 3. प्राइवेट सामान्य लिंक: t.me/c/1234567/100
c_match = re.search(r"t\.me/c/(\d+)/(\d+)", link)
if c_match:
return int("-100" + c_match.group(1)), int(c_match.group(2)), None
# 4. बॉट लिंक: t.me/b/username/100
b_match = re.search(r"t\.me/b/([^/]+)/(\d+)", link)
if b_match:
return b_match.group(1), int(b_match.group(2)), None
# 5. पब्लिक सामान्य लिंक: t.me/username/100
p_match = re.search(r"t\.me/([^/]+)/(\d+)", link)
if p_match:
return p_match.group(1), int(p_match.group(2)), None
return None, None, None
@Client.on_message(filters.command(["resume"]) & filters.private)
async def resume_command(client: Client, message: Message):
user_id = message.from_user.id
if not db.is_user_vip(user_id, ADMINS):
return await message.reply_text("🔒 आपका VIP एक्सेस सक्रिय नहीं है।")
task = batch_temp.CLONE_DATA.get(user_id)
last_id = batch_temp.LAST_SAVED_ID.get(user_id)
if not task or last_id is None:
return await message.reply_text("⚠️ कोई रुका हुआ पिछला टास्क नहीं मिला। नया टास्क शुरू करने के लिए `/clone` करें।")
if last_id >= task["end_id"]:
return await message.reply_text("✅ पिछला टास्क पहले ही पूरा हो चुका था।")
task["start_id"] = last_id + 1
total_remaining = (task["end_id"] - task["start_id"]) + 1
await message.reply_text(f"🔄 **टास्क रिज्यूम किया जा रहा है...** (ID `{task['start_id']}` से `{task['end_id']}` तक, शेष: {total_remaining})")
await start_clone_task(client, user_id)
@Client.on_message(filters.command(["clone", "clon"]) & filters.private)
async def clone_command(client: Client, message: Message):
user_id = message.from_user.id
if not db.is_user_vip(user_id, ADMINS):
return await message.reply_text(
"🔒 **यह फीचर केवल एक्टिव VIP मेंबर्स के लिए है!**\n\nप्लान देखने के लिए /plans और पेमेंट के लिए /pay भेजें।"
)
if batch_temp.IS_BATCH.get(user_id) == False:
return await message.reply_text("⚠️ आपका एक टास्क पहले से चल रहा है। इंतज़ार करें या `/cancel` करें।")
user_session = db.get_session(user_id)
if not user_session:
return await message.reply_text("🔑 पहले **/login** करें ताकि आपके अकाउंट से फाइल्स ट्रांसफर हो सकें।")
guide_text = (
"📖 **कंटेंट क्लोनिंग निर्देश:**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"👉 **स्टेप 1:** जहाँ से कॉपी करना है, उसकी **पहली लिंक (Start Link)** भेजें:\n"
"(पब्लिक, प्राइवेट, बॉट लिंक या टॉपिक लिंक मान्य हैं)\n"
"(रद्द करने के लिए /cancel लिखें)"
)
first_msg = await client.ask(user_id, guide_text, filters=filters.text, timeout=300)
if first_msg.text == "/cancel":
return await first_msg.reply("❌ प्रोसेस रद्द कर दिया गया।")
start_link = first_msg.text.strip()
s_chat, s_id, s_topic = parse_telegram_link(start_link)
if not s_id:
return await first_msg.reply("❌ अमान्य टेलीग्राम लिंक! दोबारा /clone करें।")
last_msg = await client.ask(
user_id,
"👉 **स्टेप 2:** अब **अंतिम लिंक (End Link)** भेजें:\n(सिंगल पोस्ट के लिए `/single` लिखें)",
filters=filters.text,
timeout=300
)
if last_msg.text == "/cancel":
return await last_msg.reply("❌ प्रोसेस रद्द कर दिया गया।")
if last_msg.text.strip().lower() == "/single":
e_chat, e_id, e_topic = s_chat, s_id, s_topic
else:
end_link = last_msg.text.strip()
e_chat, e_id, e_topic = parse_telegram_link(end_link)
if not e_id:
return await last_msg.reply("❌ अमान्य अंतिम लिंक! दोबारा /clone करें।")
dest_msg = await client.ask(
user_id,
"👉 **स्टेप 3:** जहाँ अपलोड करवाना है, उस **चैनल/ग्रुप का लिंक या ID** भेजें:\n"
"(सीधे इसी बॉट में पाने के लिए `/skip` लिखें)",
filters=filters.text,
timeout=300
)
if dest_msg.text == "/cancel":
return await dest_msg.reply("❌ प्रोसेस रद्द कर दिया गया।")
dest_val = dest_msg.text.strip()
is_direct_bot = False
target_chat = None
target_topic_id = None
if dest_val.lower() == "/skip":
target_chat = user_id
is_direct_bot = True
batch_temp.CLONE_DATA[user_id] = {
"source_chat": s_chat,
"start_id": min(s_id, e_id),
"end_id": max(s_id, e_id),
"target_chat": target_chat,
"target_topic_id": None,
"is_direct_bot": is_direct_bot,
"custom_caption": None,
"extra_caption": None,
"replace_find": None,
"replace_with": None,
"strip_links": False,
"hyperlink_word": None,
"hyperlink_url": None,
"thumb_path": None
}
batch_temp.LAST_SAVED_ID[user_id] = min(s_id, e_id) - 1
return await show_customization_menu(client, user_id)
if ":" in dest_val:
parts = dest_val.split(":")
dest_val = parts[0]
try:
target_topic_id = int(parts[1])
except ValueError:
target_topic_id = None
try:
target_chat = int(dest_val)
except ValueError:
target_chat = dest_val.replace("https://t.me/", "@")
batch_temp.CLONE_DATA[user_id] = {
"source_chat": s_chat,
"start_id": min(s_id, e_id),
"end_id": max(s_id, e_id),
"target_chat": target_chat,
"target_topic_id": target_topic_id,
"is_direct_bot": is_direct_bot,
"custom_caption": None,
"extra_caption": None,
"replace_find": None,
"replace_with": None,
"strip_links": False,
"hyperlink_word": None,
"hyperlink_url": None,
"thumb_path": None
}
batch_temp.LAST_SAVED_ID[user_id] = min(s_id, e_id) - 1
topic_markup = InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ हाँ (Yes)", callback_data="ask_topic_yes"),
InlineKeyboardButton("❌ नहीं (No)", callback_data="ask_topic_no")
]
])
await client.send_message(
user_id,
"🧵 **क्या आप इसे किसी विशेष टॉपिक (Forum Topic) में अपलोड करवाना चाहते हैं?**",
reply_markup=topic_markup
)
async def show_customization_menu(client: Client, user_id: int):
data = batch_temp.CLONE_DATA.get(user_id, {})
cap_status = "कस्टम सेट है ✅" if data.get("custom_caption") else "ओरिजिनल"
ext_status = "सेट है ✅" if data.get("extra_caption") else "कोई नहीं"
thm_status = "सेट है ✅" if data.get("thumb_path") else "डिफ़ॉल्ट"
strip_status = "हटाएँगे 🗑️" if data.get("strip_links") else "सुरक्षित रखेंगे"
rep_status = f"`{data.get('replace_find')}` ➔ `{data.get('replace_with')}`" if data.get("replace_find") else "कोई नहीं"
link_attach_status = f"[{data.get('hyperlink_word')}]({data.get('hyperlink_url')})" if data.get("hyperlink_word") else "कोई नहीं"
dest_display = "सीधे बॉट चैट (Direct Bot)" if data.get("is_direct_bot") else f"`{data.get('target_chat')}`"
if data.get("target_topic_id"):
dest_display += f" (टॉपिक ID: `{data.get('target_topic_id')}`)"
total_msgs = (data.get('end_id', 0) - data.get('start_id', 0)) + 1
panel_text = (
"⚙️ **कंटेंट कस्टमाइज़ेशन सेटिंग्स:**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"📝 नया कैप्शन: `{cap_status}`\n"
f"🔄 रिप्लेस: {rep_status}\n"
f"🚫 लिंक्स हटाना: `{strip_status}`\n"
f"📎 हाइपरलिंक जोड़ना: {link_attach_status}\n"
f"➕ अतिरिक्त कैप्शन: `{ext_status}`\n"
f"🖼️ थंबनेल: `{thm_status}`\n"
f"🎯 टारगेट: {dest_display}\n"
f"📊 रेंज: `{data.get('start_id')}` से `{data.get('end_id')}` (कुल {total_msgs} मैसेज)\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"कस्टमाइज़ करें या तुरंत प्रोसेस के लिए **🚀 Confirm & Start** दबाएँ:"
)
buttons = InlineKeyboardMarkup([
[InlineKeyboardButton("📝 Edit Full Caption", callback_data="set_caption"),
InlineKeyboardButton("🔄 Replace in Caption", callback_data="set_replace")],
[InlineKeyboardButton("🚫 Remove All Links", callback_data="toggle_strip_links"),
InlineKeyboardButton("📎 Attach Hyperlink", callback_data="set_hyperlink")],
[InlineKeyboardButton("➕ Add Extra Caption", callback_data="set_extra"),
InlineKeyboardButton("🖼️ Set Thumbnail", callback_data="set_thumb")],
[InlineKeyboardButton("🗑️ Clear Settings", callback_data="clear_settings"),
InlineKeyboardButton("🚀 Confirm & Start", callback_data="confirm_start")]
])
await client.send_message(user_id, panel_text, reply_markup=buttons)
# ==================== कॉलबैक हैंडलर ====================
@Client.on_callback_query()
async def callback_handler(client: Client, query: CallbackQuery):
user_id = query.from_user.id
data = query.data
if data == "nav_howtouse":
return await howtouse_handler(client, query.message)
elif data == "nav_plans":
return await plans_handler(client, query.message)
elif data == "nav_channelhelp":
return await channelhelp_handler(client, query.message)
elif data == "nav_speedhelp":
return await speedhelp_handler(client, query.message)
elif data == "nav_myplan":
return await myplan_handler(client, query.message)
elif data == "nav_lang":
return await lang_handler(client, query.message)
elif data.startswith("setlang_"):
lang_code = data.split("_")[1]
db.set_lang(user_id, lang_code)
lang_name = "हिन्दी" if lang_code == "hi" else "English"
return await query.message.edit_text(f"✅ भाषा बदलकर **{lang_name}** कर दी गई है!")
if user_id not in batch_temp.CLONE_DATA:
return await query.answer("⚠️ सेशन एक्सपायर हो गया, दोबारा /clone करें।", show_alert=True)
if data == "ask_topic_yes":
await query.message.delete()
t_msg = await client.ask(
user_id,
"👉 कृपया उस **Topic ID (थ्रेड ID)** को दर्ज करें:\n(उदाहरण: `45`)",
filters=filters.text,
timeout=180
)
if t_msg.text != "/cancel":
try:
batch_temp.CLONE_DATA[user_id]["target_topic_id"] = int(t_msg.text.strip())
except ValueError:
await t_msg.reply_text("⚠️ अमान्य संख्या! टॉपिक आईडी छोड़ दी गई।")
await show_customization_menu(client, user_id)
elif data == "ask_topic_no":
await query.message.delete()
await show_customization_menu(client, user_id)
elif data == "set_caption":
await query.message.delete()
msg = await client.ask(user_id, "✍️ **नया कस्टम कैप्शन भेजें** (हाइपरलिंक मान्य हैं):", filters=filters.text, timeout=180)
batch_temp.CLONE_DATA[user_id]["custom_caption"] = msg.text.markdown
await show_customization_menu(client, user_id)
elif data == "set_replace":
await query.message.delete()
find_msg = await client.ask(user_id, "🔍 क्या खोजना/हटाना चाहते हैं? वह शब्द/टेक्स्ट भेजें:", filters=filters.text, timeout=180)
if find_msg.text == "/cancel":
return await show_customization_menu(client, user_id)
with_msg = await client.ask(user_id, f"✏️ `{find_msg.text}` की जगह क्या लगाना चाहते हैं? (हटाने/खाली रखने के लिए `/empty`):", filters=filters.text, timeout=180)
if with_msg.text == "/cancel":
return await show_customization_menu(client, user_id)
batch_temp.CLONE_DATA[user_id]["replace_find"] = find_msg.text
batch_temp.CLONE_DATA[user_id]["replace_with"] = "" if with_msg.text.strip() == "/empty" else with_msg.text.markdown
await show_customization_menu(client, user_id)
elif data == "toggle_strip_links":
curr = batch_temp.CLONE_DATA[user_id].get("strip_links", False)
batch_temp.CLONE_DATA[user_id]["strip_links"] = not curr
await query.answer("लिंक हटाने का विकल्प अपडेट हुआ!")
await query.message.delete()
await show_customization_menu(client, user_id)
elif data == "set_hyperlink":
await query.message.delete()
w_msg = await client.ask(user_id, "✍️ कैप्शन के किस **शब्द (Word/Text)** पर लिंक लगानी है?", filters=filters.text, timeout=180)
if w_msg.text == "/cancel":
return await show_customization_menu(client, user_id)
u_msg = await client.ask(user_id, f"🔗 `{w_msg.text}` के लिए **URL (वेबसाइट/चैनल लिंक)** भेजें:", filters=filters.text, timeout=180)
if u_msg.text == "/cancel":
return await show_customization_menu(client, user_id)
batch_temp.CLONE_DATA[user_id]["hyperlink_word"] = w_msg.text.strip()
batch_temp.CLONE_DATA[user_id]["hyperlink_url"] = u_msg.text.strip()
await show_customization_menu(client, user_id)
elif data == "set_extra":
await query.message.delete()
msg = await client.ask(user_id, "✍️ **अतिरिक्त कैप्शन भेजें** (हाइपरलिंक मान्य हैं):", filters=filters.text, timeout=180)
batch_temp.CLONE_DATA[user_id]["extra_caption"] = msg.text.markdown
await show_customization_menu(client, user_id)
elif data == "set_thumb":
await query.message.delete()
msg = await client.ask(user_id, "🖼️ **थंबनेल के लिए फ़ोटो भेजें:**", filters=filters.photo, timeout=180)
user_thumb_dir = os.path.join("thumbs", str(user_id))
os.makedirs(user_thumb_dir, exist_ok=True)
thumb_file = os.path.join(user_thumb_dir, "thumb.jpg")
await client.download_media(msg.photo, file_name=thumb_file)
batch_temp.CLONE_DATA[user_id]["thumb_path"] = thumb_file
await msg.reply_text("✅ आपका थंबनेल सुरक्षित सेव कर लिया गया!")
await show_customization_menu(client, user_id)
elif data == "clear_settings":
batch_temp.CLONE_DATA[user_id]["custom_caption"] = None
batch_temp.CLONE_DATA[user_id]["extra_caption"] = None
batch_temp.CLONE_DATA[user_id]["replace_find"] = None
batch_temp.CLONE_DATA[user_id]["replace_with"] = None
batch_temp.CLONE_DATA[user_id]["strip_links"] = False
batch_temp.CLONE_DATA[user_id]["hyperlink_word"] = None
batch_temp.CLONE_DATA[user_id]["hyperlink_url"] = None
tpath = batch_temp.CLONE_DATA[user_id].get("thumb_path")
if tpath and os.path.exists(tpath):
os.remove(tpath)
batch_temp.CLONE_DATA[user_id]["thumb_path"] = None
await query.answer("सेटिंग्स रीसेट हो गईं।")
await query.message.delete()
await show_customization_menu(client, user_id)
elif data == "confirm_start":
await query.message.delete()
await start_clone_task(client, user_id)
# ==================== कोर इंजन और मीडिया प्रोसेसिंग ====================
async def start_clone_task(client: Client, user_id: int):
task = batch_temp.CLONE_DATA.get(user_id)
if not task:
return await client.send_message(user_id, "❌ कोई सक्रिय टास्क नहीं मिला।")
source_chat = task["source_chat"]
start_id = task["start_id"]
end_id = task["end_id"]
target_chat = task["target_chat"]
target_topic_id = task.get("target_topic_id")
user_session = db.get_session(user_id)
user_api_id = db.get_api_id(user_id)
user_api_hash = db.get_api_hash(user_id)
total_count = (end_id - start_id) + 1
status_msg = await client.send_message(
user_id,
f"🚀 **कंटेंट ट्रांसफर शुरू हो रहा है...**\n📊 **कुल फाइल्स/मैसेज:** `{total_count}`"
)
acc = Client(
f"user_session_{user_id}",
session_string=user_session,
api_hash=user_api_hash,
api_id=user_api_id,
in_memory=True,
workers=8
)
try:
await asyncio.wait_for(acc.start(), timeout=20.0)
except asyncio.TimeoutError:
return await status_msg.edit_text("❌ टेलीग्राम सेशन टाइमआउट हो गया। कृपया दोबारा /clone करें।")
except Exception as e:
return await status_msg.edit_text(f"❌ सेशन कनेक्ट एरर (कृपया दोबारा /login करें): `{e}`")
batch_temp.IS_BATCH[user_id] = False
success = 0
not_found = 0
retrying = 0
total_bytes = 0
start_time = time.time()
current_idx = 0
for msgid in range(start_id, end_id + 1):
current_idx += 1
if batch_temp.IS_BATCH.get(user_id):
await status_msg.edit_text("🛑 **टास्क पूरी तरह रोक दिया गया है।**")
break
if not db.is_user_vip(user_id, ADMINS):
batch_temp.IS_BATCH[user_id] = True
await status_msg.edit_text("🚫 **आपका VIP एक्सेस समाप्त या हटा दिया गया है।**")
break
attempts = 0
while attempts < 3:
if batch_temp.IS_BATCH.get(user_id):
break
try:
# बड़ी 2GB तक की फाइल्स के लिए पर्याप्त समय सीमा (1800 सेकंड / 30 मिनट)
ok, sz = await asyncio.wait_for(
process_media(
client, acc, user_id, source_chat, msgid,
target_chat, target_topic_id, task, status_msg,
current_idx, total_count
),
timeout=1800.0
)
if ok:
success += 1
total_bytes += sz
batch_temp.LAST_SAVED_ID[user_id] = msgid
else:
not_found += 1
break
except asyncio.CancelledError:
break
except FloodWait as fw:
await status_msg.edit_text(f"⏳ **Rate-limit:** {fw.value} सेकंड इंतज़ार कर रहे हैं...")
await asyncio.sleep(fw.value + 1)
attempts += 1
except asyncio.TimeoutError:
attempts += 1
await asyncio.sleep(2)
except Exception as e:
print(f"Error on msg {msgid}: {e}")
retrying += 1
break
if batch_temp.IS_BATCH.get(user_id):
await status_msg.edit_text("🛑 **टास्क पूरी तरह रोक दिया गया है।**")
break
await asyncio.sleep(WAITING_TIME)
try:
await acc.stop()
except Exception:
pass
batch_temp.IS_BATCH[user_id] = True
tpath = task.get("thumb_path")
if tpath and os.path.exists(tpath):
os.remove(tpath)
elapsed_time = max(1, int(time.time() - start_time))
avg_speed = f"{humanbytes(total_bytes / elapsed_time)}/s"
if not batch_temp.IS_BATCH.get(user_id, False):
summary_card = (
"🏁 **Transfer Finished**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"📊 Total Messages: {total_count}\n"
f"✅ Success: {success}\n"
f"🗑️ Empty/Skipped: {not_found}\n"
f"🔁 Retrying: {retrying}\n"
f"📦 Total Size: {humanbytes(total_bytes)}\n"
f"⚡ Avg Speed: {avg_speed}\n"
f"⏱️ Time: {time_formatter(elapsed_time)}\n"
"━━━━━━━━━━━━━━━━━━━━"
)
try:
await status_msg.edit_text(summary_card)
except Exception:
pass
def get_file_name_from_msg(msg: Message) -> str:
name = None
if msg.document and msg.document.file_name:
name = msg.document.file_name
elif msg.video and msg.video.file_name:
name = msg.video.file_name
elif msg.video:
name = f"video_{msg.id}.mp4"
elif msg.audio and msg.audio.file_name:
name = msg.audio.file_name
elif msg.audio:
name = f"audio_{msg.id}.mp3"
elif msg.photo:
name = f"photo_{msg.id}.jpg"
else:
name = f"file_{msg.id}.bin"
clean_name = re.sub(r"^\d+_", "", name)
return clean_name if clean_name else name
def format_caption_text(raw_text: str, task: dict) -> str:
if not raw_text:
raw_text = ""
final_text = raw_text
if task.get("custom_caption"):
final_text = task["custom_caption"]
else:
if task.get("strip_links"):
final_text = strip_all_urls(final_text)
if task.get("replace_find"):
find_w = task["replace_find"]
with_w = task.get("replace_with") or ""
if find_w in final_text:
final_text = final_text.replace(find_w, with_w)
if task.get("hyperlink_word") and task.get("hyperlink_url"):
target_word = task["hyperlink_word"]
target_url = task["hyperlink_url"]
if target_word in final_text:
final_text = final_text.replace(target_word, f"[{target_word}]({target_url})", 1)
if task.get("extra_caption"):
if final_text.strip():
final_text = f"{final_text}\n\n{task['extra_caption']}"
else:
final_text = task["extra_caption"]
return final_text
async def process_media(client: Client, acc: Client, user_id: int, source_chat, msgid: int, target_chat, target_topic_id, task: dict, status_msg: Message, current_idx: int, total_count: int):
if batch_temp.IS_BATCH.get(user_id):
raise asyncio.CancelledError()
msg = None
try:
msg = await asyncio.wait_for(acc.get_messages(source_chat, msgid), timeout=25.0)
except Exception:
try:
msg = await asyncio.wait_for(client.get_messages(source_chat, msgid), timeout=25.0)
except Exception:
return False, 0
if not msg or msg.empty or msg.service:
return False, 0
raw_caption = msg.caption.markdown if msg.caption else ""
final_caption = format_caption_text(raw_caption, task)
is_direct_bot = task.get("is_direct_bot", False)
sender_client = client if is_direct_bot else acc
topic_kwargs = {"message_thread_id": target_topic_id} if target_topic_id and not is_direct_bot else {}
# सादा टेक्स्ट मैसेज
if msg.text:
text_to_send = format_caption_text(msg.text.markdown, task)
await sender_client.send_message(target_chat, text_to_send, parse_mode=enums.ParseMode.MARKDOWN, **topic_kwargs)
return True, len(text_to_send.encode('utf-8'))
file_name = get_file_name_from_msg(msg)
user_down_dir = os.path.join("downloads", str(user_id))
os.makedirs(user_down_dir, exist_ok=True)
down_path = os.path.join(user_down_dir, file_name)
remaining = max(0, total_count - current_idx)
# 1. अगर फ़ाइल पहले से पूरी डाउनलोड है, तो दोबारा डाउनलोड करने की ज़रूरत नहीं
file_path = None
if os.path.exists(down_path) and os.path.getsize(down_path) > 1024:
file_path = down_path
else:
down_start = time.time()
await status_msg.edit_text(
f"📥 **Downloading ID:** `{msgid}`\n"
f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
f"📁 **फ़ाइल:** `{file_name}`..."
)
try:
if msg.photo:
file_path = await acc.download_media(msg, file_name=down_path)
else:
try:
file_path = await fast_download_file(
acc,
msg,
out_path=down_path,
progress_func=progress_bar,
progress_args=("📥 Downloading ID: " + str(msgid), status_msg, down_start, file_name, current_idx, total_count, user_id)
)
except Exception:
file_path = await acc.download_media(
msg,
file_name=down_path,
progress=progress_bar,
progress_args=("📥 Downloading ID: " + str(msgid), status_msg, down_start, file_name, current_idx, total_count, user_id)
)
except asyncio.CancelledError:
if os.path.exists(down_path):
try:
os.remove(down_path)
except Exception:
pass
raise asyncio.CancelledError()
if batch_temp.IS_BATCH.get(user_id):
if file_path and os.path.exists(file_path):
os.remove(file_path)
raise asyncio.CancelledError()
if not file_path or not os.path.exists(file_path):
return False, 0
size = os.path.getsize(file_path)
up_start = time.time()
await status_msg.edit_text(
f"📤 **Uploading ID:** `{msgid}`\n"
f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
f"📁 **फ़ाइल:** `{file_name}`..."
)
thumb_to_use = task.get("thumb_path")
created_temp_thumb = None
if not thumb_to_use and msg.video:
auto_thumb_path = os.path.join(user_down_dir, f"thumb_{msgid}.jpg")
created_temp_thumb = generate_auto_thumb(file_path, auto_thumb_path)
thumb_to_use = created_temp_thumb
try:
if msg.photo:
await sender_client.send_photo(
target_chat, file_path, caption=final_caption, parse_mode=enums.ParseMode.MARKDOWN, **topic_kwargs
)
elif msg.video:
# बड़ी वीडियो के लिए अपलोड प्रयास
for up_retry in range(3):
try:
await sender_client.send_video(
target_chat,
video=file_path,
thumb=thumb_to_use,
caption=final_caption,
parse_mode=enums.ParseMode.MARKDOWN,
duration=getattr(msg.video, "duration", 0) or 0,
width=getattr(msg.video, "width", 0) or 0,
height=getattr(msg.video, "height", 0) or 0,
progress=progress_bar,
progress_args=(f"📤 Uploading ID: {msgid}", status_msg, up_start, file_name, current_idx, total_count, user_id),
**topic_kwargs
)
break
except FloodWait as f:
await asyncio.sleep(f.value + 1)
except Exception as ex:
if up_retry == 2:
raise ex
await asyncio.sleep(3)
elif msg.audio:
await sender_client.send_audio(
target_chat,
audio=file_path,
thumb=thumb_to_use,
caption=final_caption,
parse_mode=enums.ParseMode.MARKDOWN,
duration=getattr(msg.audio, "duration", 0) or 0,
progress=progress_bar,
progress_args=(f"📤 Uploading ID: {msgid}", status_msg, up_start, file_name, current_idx, total_count, user_id),
**topic_kwargs
)
else:
for up_retry in range(3):
try:
await sender_client.send_document(
target_chat,
document=file_path,
thumb=thumb_to_use,
caption=final_caption,
parse_mode=enums.ParseMode.MARKDOWN,
progress=progress_bar,
progress_args=(f"📤 Uploading ID: {msgid}", status_msg, up_start, file_name, current_idx, total_count, user_id),
**topic_kwargs
)
break
except FloodWait as f:
await asyncio.sleep(f.value + 1)
except Exception as ex:
if up_retry == 2:
raise ex
await asyncio.sleep(3)
except asyncio.CancelledError:
if os.path.exists(file_path):
try:
os.remove(file_path)
except Exception:
pass
raise asyncio.CancelledError()
except Exception as e:
print(f"Upload error on msg {msgid}: {e}")
return False, 0
finally:
# केवल तभी फ़ाइल डिलीट होगी जब वह सुरक्षित सेंड हो जाए या पूरी तरह कैंसल हो
if os.path.exists(file_path):
try:
os.remove(file_path)
except Exception:
pass
if created_temp_thumb and os.path.exists(created_temp_thumb):
try:
os.remove(created_temp_thumb)
except Exception:
pass
return True, size
import os
import asyncio
import time
import math
import re
import subprocess
from pyrogram import Client, filters, enums
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram.errors import FloodWait, RPCError
from config import API_ID, API_HASH, ADMINS, CHANNEL_ID, WAITING_TIME
from db import db
try:
from TechVJ.TechVJ.fast_download import fast_download_file
except ImportError:
try:
from TechVJ.fast_download import fast_download_file
except ImportError:
from fast_download import fast_download_file
class batch_temp(object):
IS_BATCH = {}
CLONE_DATA = {}
LAST_SAVED_ID = {}
def humanbytes(size):
if not size:
return "0 B"
power = 1024
t_n = 0
power_labels = {0: ' ', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
while size > power:
size /= power
t_n += 1
return f"{round(size, 2)} {power_labels[t_n]}B"
def time_formatter(seconds: int) -> str:
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = ((str(days) + "d, ") if days else "") + \
((str(hours) + "h, ") if hours else "") + \
((str(minutes) + "m, ") if minutes else "") + \
((str(seconds) + "s") if seconds else "")
return tmp if tmp else "0s"
async def progress_bar(current, total, ud_type, message, start, fname="", current_idx=1, total_count=1, user_id=None):
if user_id and batch_temp.IS_BATCH.get(user_id):
raise asyncio.CancelledError("Task cancelled by user.")
now = time.time()
diff = max(1e-3, now - start)
if round(diff % 2.0) == 0 or current == total:
percentage = current * 100 / total if total > 0 else 0
speed = current / diff if diff > 0 else 0
elapsed_time = round(diff)
eta = round((total - current) / speed) if speed > 0 else 0
bar_length = 10
filled_length = int(bar_length * current // total) if total > 0 else 0
bar = '▰' * filled_length + '▱' * (bar_length - filled_length)
fname_text = f"📁 **फ़ाइल:** `{fname[:30]}...`\n" if fname else ""
remaining = max(0, total_count - current_idx)
status_text = (
f"**{ud_type}**\n"
f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
f"{fname_text}"
f"[{bar}] {percentage:.1f}%\n"
f"⚡ **स्पीड:** {humanbytes(speed)}/s\n"
f"📦 **डन:** {humanbytes(current)} / {humanbytes(total)}\n"
f"⏱️ **ETA:** {time_formatter(eta)} | **समय:** {time_formatter(elapsed_time)}"
)
try:
await message.edit_text(status_text)
except Exception:
pass
def generate_auto_thumb(video_path: str, thumb_path: str):
try:
cmd = [
"ffmpeg", "-ss", "00:00:02", "-i", video_path,
"-vframes", "1", "-q:v", "2", thumb_path, "-y"
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if os.path.exists(thumb_path):
return thumb_path
except Exception:
pass
return None
def strip_all_urls(text: str) -> str:
if not text:
return ""
text = re.sub(r'\[([^\]]+)\]\((https?://[^\)]+|t\.me/[^\)]+)\)', r'\1', text)
text = re.sub(r'https?://\S+|www\.\S+', '', text)
text = re.sub(r't\.me/\S+', '', text)
text = re.sub(r'\n{3,}', '\n\n', text).strip()
return text