├── Procfile
├── heroku.yml
├── Dockerfile
├── requirements.txt
├── app.py
├── .github
└── ISSUE_TEMPLATE
│ ├── feature_request.md
│ └── bug_report.md
├── utils
├── custom_filters.py
├── encrypt.py
└── func.py
├── shared_client.py
├── main.py
├── plugins
├── pay.py
├── premium.py
├── stats.py
├── start.py
├── settings.py
├── login.py
├── ytdl.py
└── batch.py
├── config.py
├── app.json
├── templates
└── welcome.html
├── README.md
└── LICENSE
/Procfile:
--------------------------------------------------------------------------------
1 | worker: python main.py
--------------------------------------------------------------------------------
/heroku.yml:
--------------------------------------------------------------------------------
1 | build:
2 | docker:
3 | worker: Dockerfile
4 | run:
5 | worker: python3 main.py
6 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.10-slim
2 | RUN apt-get update && apt-get install -y git curl ffmpeg python3-pip wget bash && apt-get clean && rm -rf /var/lib/apt/lists/*
3 | WORKDIR /app
4 | COPY requirements.txt .
5 |
6 | RUN pip3 install wheel
7 | RUN pip3 install --no-cache-dir -U -r requirements.txt
8 | COPY . .
9 | EXPOSE 5000
10 |
11 | CMD flask run -h 0.0.0.0 -p 5000 & python3 main.py
12 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | telethon
2 | python-dotenv
3 | psutil
4 | opencv-python-headless
5 | devgagantools
6 | aiofiles
7 | # ggnpyro
8 | https://www.dl.dropboxusercontent.com/scl/fi/e0fo6fcjn8kmr5r0x6wvg/myownpyro.zip?rlkey=d1znpwckss4ullz0sg7e1qjjg&st=kmbh7wdv&dl=0
9 | aiohttp
10 | telethon-tgcrypto
11 | motor
12 | pymongo
13 | pytz
14 | Pillow
15 | tgcrypto
16 | flask
17 | werkzeug==2.2.2
18 | mutagen
19 | yt-dlp
20 | requests
21 | cryptography
22 |
--------------------------------------------------------------------------------
/app.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | import os
6 | from flask import Flask, render_template
7 |
8 | app = Flask(__name__)
9 |
10 | @app.route("/")
11 | def welcome():
12 | # Render the welcome page with animated "Team SPY" text
13 | return render_template("welcome.html")
14 |
15 | if __name__ == "__main__":
16 | # Default to port 5000 if PORT is not set in the environment
17 | port = int(os.environ.get("PORT", 5000))
18 | app.run(host="0.0.0.0", port=port)
19 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/utils/custom_filters.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from pyrogram import filters
6 |
7 | user_steps = {}
8 |
9 | def login_filter_func(_, __, message):
10 | user_id = message.from_user.id
11 | return user_id in user_steps
12 |
13 | login_in_progress = filters.create(login_filter_func)
14 |
15 | def set_user_step(user_id, step=None):
16 | if step:
17 | user_steps[user_id] = step
18 | else:
19 | user_steps.pop(user_id, None)
20 |
21 |
22 | def get_user_step(user_id):
23 | return user_steps.get(user_id)
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/shared_client.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from telethon import TelegramClient
6 | from config import API_ID, API_HASH, BOT_TOKEN, STRING
7 | from pyrogram import Client
8 | import sys
9 |
10 | client = TelegramClient("telethonbot", API_ID, API_HASH)
11 | app = Client("pyrogrambot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
12 | userbot = Client("4gbbot", api_id=API_ID, api_hash=API_HASH, session_string=STRING)
13 |
14 | async def start_client():
15 | if not client.is_connected():
16 | await client.start(bot_token=BOT_TOKEN)
17 | print("SpyLib started...")
18 | if STRING:
19 | try:
20 | await userbot.start()
21 | print("Userbot started...")
22 | except Exception as e:
23 | print(f"Hey honey!! check your premium string session, it may be invalid of expire {e}")
24 | sys.exit(1)
25 | await app.start()
26 | print("Pyro App Started...")
27 | return client, app, userbot
28 |
29 |
--------------------------------------------------------------------------------
/utils/encrypt.py:
--------------------------------------------------------------------------------
1 | # crypto_ops.py
2 | from cryptography.hazmat.primitives import hashes as hsh
3 | from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC as PBK
4 | from cryptography.hazmat.primitives.ciphers import Cipher as Cp, algorithms as alg, modes as md
5 | import base64 as b64
6 | import os as osy
7 | from config import MASTER_KEY as M1, IV_KEY as I1
8 |
9 | def dyk(pwd=M1, slt=I1, l=16):
10 | pw = pwd.encode()
11 | sl = slt.encode()
12 | kdf = PBK(
13 | algorithm=hsh.SHA256(),
14 | length=l,
15 | salt=sl,
16 | iterations=100000,
17 | )
18 | return kdf.derive(pw)
19 |
20 | def ecs(s):
21 | k = dyk()
22 | n = osy.urandom(12)
23 | cp = Cp(alg.AES(k), md.GCM(n))
24 | enc = cp.encryptor()
25 | p = s.encode()
26 | ct = enc.update(p) + enc.finalize()
27 | tg = enc.tag
28 | encd = b64.b64encode(n + tg + ct).decode()
29 | return encd
30 |
31 | def dcs(ed):
32 | k = dyk()
33 | dat = b64.b64decode(ed.encode())
34 | n = dat[:12]
35 | tg = dat[12:28]
36 | ct = dat[28:]
37 | cp = Cp(alg.AES(k), md.GCM(n, tg))
38 | dec = cp.decryptor()
39 | res = dec.update(ct) + dec.finalize()
40 | return res.decode()
41 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | import asyncio
6 | from shared_client import start_client
7 | import importlib
8 | import os
9 | import sys
10 |
11 | async def load_and_run_plugins():
12 | await start_client()
13 | plugin_dir = "plugins"
14 | plugins = [f[:-3] for f in os.listdir(plugin_dir) if f.endswith(".py") and f != "__init__.py"]
15 |
16 | for plugin in plugins:
17 | module = importlib.import_module(f"plugins.{plugin}")
18 | if hasattr(module, f"run_{plugin}_plugin"):
19 | print(f"Running {plugin} plugin...")
20 | await getattr(module, f"run_{plugin}_plugin")()
21 |
22 | async def main():
23 | await load_and_run_plugins()
24 | while True:
25 | await asyncio.sleep(1)
26 |
27 | if __name__ == "__main__":
28 | loop = asyncio.get_event_loop()
29 | print("Starting clients ...")
30 | try:
31 | loop.run_until_complete(main())
32 | except KeyboardInterrupt:
33 | print("Shutting down...")
34 | except Exception as e:
35 | print(e)
36 | sys.exit(1)
37 | finally:
38 | try:
39 | loop.close()
40 | except Exception:
41 | pass
42 |
--------------------------------------------------------------------------------
/plugins/pay.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from pyrogram import filters as f
6 | from shared_client import app
7 | from pyrogram.types import InlineKeyboardButton as B, InlineKeyboardMarkup as M, LabeledPrice as P, PreCheckoutQuery as Q
8 | from datetime import timedelta as T
9 | from utils.func import add_premium_user as apu
10 | from config import P0
11 |
12 | @app.on_message(f.command("pay") & f.private)
13 | async def p(c, m):
14 | kb = M([
15 | [
16 | B(f"⭐ {P0['d']['l']} - {P0['d']['s']} Star", callback_data="p_d")
17 | ],
18 | [
19 | B(f"⭐ {P0['w']['l']} - {P0['w']['s']} Stars", callback_data="p_w")
20 | ],
21 | [
22 | B(f"⭐ {P0['m']['l']} - {P0['m']['s']} Stars", callback_data="p_m")
23 | ]
24 | ])
25 |
26 | txt = (
27 | "💎 **Choose your premium plan:**\n\n"
28 | f"📅 **{P0['d']['l']}** — {P0['d']['s']} Star\n"
29 | f"🗓️ **{P0['w']['l']}** — {P0['w']['s']} Stars\n"
30 | f"📆 **{P0['m']['l']}** — {P0['m']['s']} Stars\n\n"
31 | "Select a plan below to continue ⤵️"
32 | )
33 | await m.reply_text(txt, reply_markup=kb)
34 |
35 | @app.on_callback_query(f.regex("^p_"))
36 | async def i(c, q):
37 | pl = q.data.split("_")[1]
38 | pi = P0[pl]
39 | try:
40 | await c.send_invoice(
41 | chat_id=q.from_user.id,
42 | title=f"Premium {pi['l']}",
43 | description=f"{pi['du']} {pi['u']} subscription",
44 | payload=f"{pl}_{q.from_user.id}",
45 | currency="XTR",
46 | prices=[P(label=f"Premium {pi['l']}", amount=pi['s'])]
47 | )
48 | await q.answer("Invoice sent 💫")
49 | except Exception as e:
50 | await q.answer(f"Err: {e}", show_alert=True)
51 |
52 | @app.on_pre_checkout_query()
53 | async def pc(c, q: Q):
54 | await q.answer(ok=True)
55 |
56 | @app.on_message(f.successful_payment)
57 | async def sp(c, m):
58 | p = m.successful_payment
59 | u = m.from_user.id
60 | pl = p.invoice_payload.split("_")[0]
61 | pi = P0[pl]
62 | ok, r = await apu(u, pi['du'], pi['u'])
63 | if ok:
64 | e = r + T(hours=5, minutes=30)
65 | d = e.strftime('%d-%b-%Y %I:%M:%S %p')
66 | await m.reply_text(
67 | f"✅ **Paid!**\n\n"
68 | f"💎 Premium {pi['l']} active!\n"
69 | f"⭐ {p.total_amount}\n"
70 | f"⏰ Till: {d} IST\n"
71 | f"🔖 Txn: `{p.telegram_payment_charge_id}`"
72 | )
73 | for o in OWNER_ID:
74 | await c.send_message(f"User {u} just purchased the premium, txn id is {p.telegram_payment_charge_id}.")
75 | else:
76 | await m.reply_text(
77 | f"⚠️ Paid but premium failed.\nTxn `{p.telegram_payment_charge_id}`"
78 | )
79 | for o in OWNER_ID:
80 | await c.send_message(o,
81 | f"⚠️ Issue!\nUser {u}\nPlan {pi['l']}\nTxn {p.telegram_payment_charge_id}\nErr {r}"
82 | )
83 |
84 |
85 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | import os
6 | from dotenv import load_dotenv
7 | load_dotenv()
8 |
9 | # ════════════════════════════════════════════════════════════════════════════════
10 | # ░ CONFIGURATION SETTINGS
11 | # ════════════════════════════════════════════════════════════════════════════════
12 |
13 | # VPS --- FILL COOKIES 🍪 in """ ... """
14 | INST_COOKIES = """
15 | # write up here insta cookies
16 | """
17 |
18 | YTUB_COOKIES = """
19 | # write here yt cookies
20 | """
21 |
22 | # ─── BOT / DATABASE CONFIG ──────────────────────────────────────────────────────
23 | API_ID = os.getenv("API_ID", "")
24 | API_HASH = os.getenv("API_HASH", "")
25 | BOT_TOKEN = os.getenv("BOT_TOKEN", "")
26 | MONGO_DB = os.getenv("MONGO_DB", "")
27 | DB_NAME = os.getenv("DB_NAME", "telegram_downloader")
28 |
29 | # ─── OWNER / CONTROL SETTINGS ───────────────────────────────────────────────────
30 | OWNER_ID = list(map(int, os.getenv("OWNER_ID", "").split())) # space-separated list
31 | STRING = os.getenv("STRING", None) # optional session string
32 | LOG_GROUP = int(os.getenv("LOG_GROUP", "-1001234456"))
33 | FORCE_SUB = int(os.getenv("FORCE_SUB", "-10012345567"))
34 |
35 | # ─── SECURITY KEYS ──────────────────────────────────────────────────────────────
36 | MASTER_KEY = os.getenv("MASTER_KEY", "gK8HzLfT9QpViJcYeB5wRa3DmN7P2xUq") # session encryption
37 | IV_KEY = os.getenv("IV_KEY", "s7Yx5CpVmE3F") # decryption key
38 |
39 | # ─── COOKIES HANDLING ───────────────────────────────────────────────────────────
40 | YT_COOKIES = os.getenv("YT_COOKIES", YTUB_COOKIES)
41 | INSTA_COOKIES = os.getenv("INSTA_COOKIES", INST_COOKIES)
42 |
43 | # ─── USAGE LIMITS ───────────────────────────────────────────────────────────────
44 | FREEMIUM_LIMIT = int(os.getenv("FREEMIUM_LIMIT", "0"))
45 | PREMIUM_LIMIT = int(os.getenv("PREMIUM_LIMIT", "500"))
46 |
47 | # ─── UI / LINKS ─────────────────────────────────────────────────────────────────
48 | JOIN_LINK = os.getenv("JOIN_LINK", "https://t.me/team_spy_pro")
49 | ADMIN_CONTACT = os.getenv("ADMIN_CONTACT", "https://t.me/username_of_admin")
50 |
51 | # ════════════════════════════════════════════════════════════════════════════════
52 | # ░ PREMIUM PLANS CONFIGURATION
53 | # ════════════════════════════════════════════════════════════════════════════════
54 |
55 | P0 = {
56 | "d": {
57 | "s": int(os.getenv("PLAN_D_S", 1)),
58 | "du": int(os.getenv("PLAN_D_DU", 1)),
59 | "u": os.getenv("PLAN_D_U", "days"),
60 | "l": os.getenv("PLAN_D_L", "Daily"),
61 | },
62 | "w": {
63 | "s": int(os.getenv("PLAN_W_S", 3)),
64 | "du": int(os.getenv("PLAN_W_DU", 1)),
65 | "u": os.getenv("PLAN_W_U", "weeks"),
66 | "l": os.getenv("PLAN_W_L", "Weekly"),
67 | },
68 | "m": {
69 | "s": int(os.getenv("PLAN_M_S", 5)),
70 | "du": int(os.getenv("PLAN_M_DU", 1)),
71 | "u": os.getenv("PLAN_M_U", "month"),
72 | "l": os.getenv("PLAN_M_L", "Monthly"),
73 | },
74 | }
75 |
76 | # ════════════════════════════════════════════════════════════════════════════════
77 | # ░ DEVGAGAN
78 | # ════════════════════════════════════════════════════════════════════════════════
79 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Save Restricted Content Bot v3",
3 | "description": "Save Restricted Content Bot by Team SPY",
4 | "logo": "https://lh3.googleusercontent.com/-HPcn7AqepNg/AAAAAAAAAAI/AAAAAAAAAAA/ALKGfknb1BkQiq-8_KUVOYcNAJ4swKivDQ/photo.jpg",
5 | "keywords": ["python3", "telegram", "MusicBot", "telegram-bot", "pyrogram"],
6 | "repository": "https://github.com/devgaganin/save_restricted-content-telegram-bot-repo",
7 | "success_url": "https://devgagan.in",
8 | "env": {
9 | "API_ID": {
10 | "description": "Get this value from https://my.telegram.org",
11 | "value": "",
12 | "required": true
13 | },
14 | "API_HASH": {
15 | "description": "Get this value from https://my.telegram.org",
16 | "value": "",
17 | "required": true
18 | },
19 | "BOT_TOKEN": {
20 | "description": "Bot token from @BotFather",
21 | "value": "",
22 | "required": true
23 | },
24 | "MONGO_DB": {
25 | "description": "MongoDB connection URL (https://cloud.mongodb.com)",
26 | "value": "",
27 | "required": true
28 | },
29 | "OWNER_ID": {
30 | "description": "User ID(s) to be set as bot owner(s), separated by space (e.g., 1234 5678)",
31 | "value": "",
32 | "required": true
33 | },
34 | "DB_NAME": {
35 | "description": "Database name for MongoDB (default: telegram_downloader)",
36 | "value": "telegram_downloader",
37 | "required": false
38 | },
39 | "STRING": {
40 | "description": "Optional session string for logged-in user sessions",
41 | "value": "",
42 | "required": false
43 | },
44 | "FORCE_SUB": {
45 | "description": "Channel ID (with -100 prefix) for forced subscription",
46 | "value": "-10012345567",
47 | "required": true
48 | },
49 | "LOG_GROUP": {
50 | "description": "Log channel/group ID (with -100 prefix) where the bot will send logs",
51 | "value": "-1001234456",
52 | "required": true
53 | },
54 | "MASTER_KEY": {
55 | "description": "Master key used for session encryption",
56 | "value": "gK8HzLfT9QpViJcYeB5wRa3DmN7P2xUq",
57 | "required": false
58 | },
59 | "IV_KEY": {
60 | "description": "Initialization vector key for decryption",
61 | "value": "s7Yx5CpVmE3F",
62 | "required": false
63 | },
64 | "YT_COOKIES": {
65 | "description": "Cookies for YouTube downloads (in Netscape format)",
66 | "value": "",
67 | "required": false
68 | },
69 | "INSTA_COOKIES": {
70 | "description": "Cookies for Instagram downloads (in Netscape format)",
71 | "value": "",
72 | "required": false
73 | },
74 | "FREEMIUM_LIMIT": {
75 | "description": "Limit for freemium users (in MB or desired unit)",
76 | "value": "0",
77 | "required": false
78 | },
79 | "PREMIUM_LIMIT": {
80 | "description": "Limit for premium users (in MB or desired unit)",
81 | "value": "500",
82 | "required": false
83 | },
84 | "ADMIN_CONTACT": {
85 | "description": "type admin contact link",
86 | "value": "https://t.me/kingofpatal",
87 | "required": true
88 | },
89 | "JOIN_LINK": {
90 | "description": "type join channel link which comes on /start",
91 | "value": "https://t.me/team_spy_pro",
92 | "required": true
93 | }
94 | },
95 | "buildpacks": [
96 | { "url": "heroku/python" },
97 | { "url": "https://github.com/heroku/heroku-buildpack-activestorage-preview" }
98 | ],
99 | "stack": "container"
100 | }
101 |
--------------------------------------------------------------------------------
/plugins/premium.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 Gagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from shared_client import client as bot_client, app
6 | from telethon import events
7 | from datetime import timedelta
8 | from config import OWNER_ID
9 | from utils.func import add_premium_user, is_private_chat
10 | from pyrogram import filters
11 | from pyrogram.types import InlineKeyboardButton as IK, InlineKeyboardMarkup as IKM
12 | from config import OWNER_ID, JOIN_LINK as JL , ADMIN_CONTACT as AC
13 | import base64 as spy
14 | from utils.func import a1, a2, a3, a4, a5, a7, a8, a9, a10, a11
15 | from plugins.start import subscribe
16 |
17 |
18 | @bot_client.on(events.NewMessage(pattern='/add'))
19 | async def add_premium_handler(event):
20 | if not await is_private_chat(event):
21 | await event.respond(
22 | 'This command can only be used in private chats for security reasons.'
23 | )
24 | return
25 | """Handle /add command to add premium users (owner only)"""
26 | user_id = event.sender_id
27 | if user_id not in OWNER_ID:
28 | await event.respond('This command is restricted to the bot owner.')
29 | return
30 | text = event.message.text.strip()
31 | parts = text.split(' ')
32 | if len(parts) != 4:
33 | await event.respond(
34 | """Invalid format. Use: /add user_id duration_value duration_unit
35 | Example: /add 123456 1 week"""
36 | )
37 | return
38 | try:
39 | target_user_id = int(parts[1])
40 | duration_value = int(parts[2])
41 | duration_unit = parts[3].lower()
42 | valid_units = ['min', 'hours', 'days', 'weeks', 'month', 'year',
43 | 'decades']
44 | if duration_unit not in valid_units:
45 | await event.respond(
46 | f"Invalid duration unit. Choose from: {', '.join(valid_units)}"
47 | )
48 | return
49 | success, result = await add_premium_user(target_user_id,
50 | duration_value, duration_unit)
51 | if success:
52 | expiry_utc = result
53 | expiry_ist = expiry_utc + timedelta(hours=5, minutes=30)
54 | formatted_expiry = expiry_ist.strftime('%d-%b-%Y %I:%M:%S %p')
55 | await event.respond(
56 | f"""✅ User {target_user_id} added as premium member
57 | Subscription valid until: {formatted_expiry} (IST)"""
58 | )
59 | await bot_client.send_message(target_user_id,
60 | f"""✅ Your have been added as premium member
61 | **Validity upto**: {formatted_expiry} (IST)"""
62 | )
63 | else:
64 | await event.respond(f'❌ Failed to add premium user: {result}')
65 | except ValueError:
66 | await event.respond(
67 | 'Invalid user ID or duration value. Both must be integers.')
68 | except Exception as e:
69 | await event.respond(f'Error: {str(e)}')
70 |
71 |
72 | attr1 = spy.b64encode("photo".encode()).decode()
73 | attr2 = spy.b64encode("file_id".encode()).decode()
74 |
75 | @app.on_message(filters.command(spy.b64decode(a5.encode()).decode()))
76 | async def start_handler(client, message):
77 | subscription_status = await subscribe(client, message)
78 | if subscription_status == 1:
79 | return
80 |
81 | b1 = spy.b64decode(a1).decode()
82 | b2 = int(spy.b64decode(a2).decode())
83 | b3 = spy.b64decode(a3).decode()
84 | b4 = spy.b64decode(a4).decode()
85 | b6 = spy.b64decode(a7).decode()
86 | b7 = spy.b64decode(a8).decode()
87 | b8 = spy.b64decode(a9).decode()
88 | b9 = spy.b64decode(a10).decode()
89 | b10 = spy.b64decode(a11).decode()
90 |
91 | tm = await getattr(app, b3)(b1, b2)
92 |
93 | pb = getattr(tm, spy.b64decode(attr1.encode()).decode())
94 | fd = getattr(pb, spy.b64decode(attr2.encode()).decode())
95 |
96 | kb = IKM([
97 | [IK(b7, url=JL)],
98 | [IK(b8, url=AC)]
99 | ])
100 |
101 | await getattr(message, b4)(
102 | fd,
103 | caption=b6,
104 | reply_markup=kb
105 | )
--------------------------------------------------------------------------------
/templates/welcome.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Team SPY - Bot is Live
7 |
123 |
124 |
125 |
126 |
127 |
Team SPY
128 |
⚡ Bot is Live ⚡
129 |
130 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/plugins/stats.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from datetime import timedelta, datetime
6 | from shared_client import client as bot_client
7 | from telethon import events
8 | from utils.func import get_premium_details, is_private_chat, get_display_name, get_user_data, premium_users_collection, is_premium_user
9 | from config import OWNER_ID
10 | import logging
11 | logging.basicConfig(format=
12 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
13 | logger = logging.getLogger('teamspy')
14 |
15 |
16 | @bot_client.on(events.NewMessage(pattern='/status'))
17 | async def status_handler(event):
18 | if not await is_private_chat(event):
19 | await event.respond("This command can only be used in private chats for security reasons.")
20 | return
21 |
22 | """Handle /status command to check user session and bot status"""
23 | user_id = event.sender_id
24 | user_data = await get_user_data(user_id)
25 |
26 | session_active = False
27 | bot_active = False
28 |
29 | if user_data and "session_string" in user_data:
30 | session_active = True
31 |
32 | # Check if user has a custom bot
33 | if user_data and "bot_token" in user_data:
34 | bot_active = True
35 |
36 | # Add premium status check
37 | premium_status = "❌ Not a premium member"
38 | premium_details = await get_premium_details(user_id)
39 | if premium_details:
40 | # Convert to IST timezone
41 | expiry_utc = premium_details["subscription_end"]
42 | expiry_ist = expiry_utc + timedelta(hours=5, minutes=30)
43 | formatted_expiry = expiry_ist.strftime("%d-%b-%Y %I:%M:%S %p")
44 | premium_status = f"✅ Premium until {formatted_expiry} (IST)"
45 |
46 | await event.respond(
47 | "**Your current status:**\n\n"
48 | f"**Login Status:** {'✅ Active' if session_active else '❌ Inactive'}\n"
49 | f"**Premium:** {premium_status}"
50 | )
51 |
52 | @bot_client.on(events.NewMessage(pattern='/transfer'))
53 | async def transfer_premium_handler(event):
54 | if not await is_private_chat(event):
55 | await event.respond(
56 | 'This command can only be used in private chats for security reasons.'
57 | )
58 | return
59 | user_id = event.sender_id
60 | sender = await event.get_sender()
61 | sender_name = get_display_name(sender)
62 | if not await is_premium_user(user_id):
63 | await event.respond(
64 | "❌ You don't have a premium subscription to transfer.")
65 | return
66 | args = event.text.split()
67 | if len(args) != 2:
68 | await event.respond(
69 | 'Usage: /transfer user_id\nExample: /transfer 123456789')
70 | return
71 | try:
72 | target_user_id = int(args[1])
73 | except ValueError:
74 | await event.respond(
75 | '❌ Invalid user ID. Please provide a valid numeric user ID.')
76 | return
77 | if target_user_id == user_id:
78 | await event.respond('❌ You cannot transfer premium to yourself.')
79 | return
80 | if await is_premium_user(target_user_id):
81 | await event.respond(
82 | '❌ The target user already has a premium subscription.')
83 | return
84 | try:
85 | premium_details = await get_premium_details(user_id)
86 | if not premium_details:
87 | await event.respond('❌ Error retrieving your premium details.')
88 | return
89 | target_name = 'Unknown'
90 | try:
91 | target_entity = await bot_client.get_entity(target_user_id)
92 | target_name = get_display_name(target_entity)
93 | except Exception as e:
94 | logger.warning(f'Could not get target user name: {e}')
95 | now = datetime.now()
96 | expiry_date = premium_details['subscription_end']
97 | await premium_users_collection.update_one({'user_id':
98 | target_user_id}, {'$set': {'user_id': target_user_id,
99 | 'subscription_start': now, 'subscription_end': expiry_date,
100 | 'expireAt': expiry_date, 'transferred_from': user_id,
101 | 'transferred_from_name': sender_name}}, upsert=True)
102 | await premium_users_collection.delete_one({'user_id': user_id})
103 | expiry_ist = expiry_date + timedelta(hours=5, minutes=30)
104 | formatted_expiry = expiry_ist.strftime('%d-%b-%Y %I:%M:%S %p')
105 | await event.respond(
106 | f'✅ Premium subscription successfully transferred to {target_name} ({target_user_id}). Your premium access has been removed.'
107 | )
108 | try:
109 | await bot_client.send_message(target_user_id,
110 | f'🎁 You have received a premium subscription transfer from {sender_name} ({user_id}). Your premium is valid until {formatted_expiry} (IST).'
111 | )
112 | except Exception as e:
113 | logger.error(f'Could not notify target user {target_user_id}: {e}')
114 | try:
115 | owner_id = int(OWNER_ID) if isinstance(OWNER_ID, str
116 | ) else OWNER_ID[0] if isinstance(OWNER_ID, list) else OWNER_ID
117 | await bot_client.send_message(owner_id,
118 | f'♻️ Premium Transfer: {sender_name} ({user_id}) has transferred their premium to {target_name} ({target_user_id}). Expiry: {formatted_expiry}'
119 | )
120 | except Exception as e:
121 | logger.error(f'Could not notify owner about premium transfer: {e}')
122 | return
123 | except Exception as e:
124 | logger.error(
125 | f'Error transferring premium from {user_id} to {target_user_id}: {e}'
126 | )
127 | await event.respond(f'❌ Error transferring premium: {str(e)}')
128 | return
129 | @bot_client.on(events.NewMessage(pattern='/rem'))
130 | async def remove_premium_handler(event):
131 | user_id = event.sender_id
132 | if not await is_private_chat(event):
133 | return
134 | if user_id not in OWNER_ID:
135 | return
136 | args = event.text.split()
137 | if len(args) != 2:
138 | await event.respond('Usage: /rem user_id\nExample: /rem 123456789')
139 | return
140 | try:
141 | target_user_id = int(args[1])
142 | except ValueError:
143 | await event.respond(
144 | '❌ Invalid user ID. Please provide a valid numeric user ID.')
145 | return
146 | if not await is_premium_user(target_user_id):
147 | await event.respond(
148 | f'❌ User {target_user_id} does not have a premium subscription.')
149 | return
150 | try:
151 | target_name = 'Unknown'
152 | try:
153 | target_entity = await bot_client.get_entity(target_user_id)
154 | target_name = get_display_name(target_entity)
155 | except Exception as e:
156 | logger.warning(f'Could not get target user name: {e}')
157 | result = await premium_users_collection.delete_one({'user_id':
158 | target_user_id})
159 | if result.deleted_count > 0:
160 | await event.respond(
161 | f'✅ Premium subscription successfully removed from {target_name} ({target_user_id}).'
162 | )
163 | try:
164 | await bot_client.send_message(target_user_id,
165 | '⚠️ Your premium subscription has been removed by the administrator.'
166 | )
167 | except Exception as e:
168 | logger.error(
169 | f'Could not notify user {target_user_id} about premium removal: {e}'
170 | )
171 | else:
172 | await event.respond(
173 | f'❌ Failed to remove premium from user {target_user_id}.')
174 | return
175 | except Exception as e:
176 | logger.error(f'Error removing premium from {target_user_id}: {e}')
177 | await event.respond(f'❌ Error removing premium: {str(e)}')
178 | return
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Save Restricted Content Bot v3
3 |
4 |
5 | The Save Restricted Content Bot is a stable Telegram bot developed by devgagan and TEAM SPY. It enables users to retrieve restricted messages from Telegram channels and groups, offering features such as custom thumbnail support and the ability to upload files up to 4GB. Additionally, the bot supports downloading videos from platforms like YouTube, Instagram, and Facebook, along with over 100 other sites
6 |
7 | [Telegram](https://t.me/save_restricted_content_bots) | [See Recent Updates](https://github.com/devgaganin/Save-Restricted-Content-Bot-V2/tree/v3#updates)
8 |
9 | ### Star the repo it motivate us to update new features
10 | Please do start and max fork thanks
11 |
12 | ## 📚 About This Branch
13 | - This branch is based on `Pyrogram V2` offering enhanced stability and a forced login feature. User are not forced to login in bot for public channels but for public groups and private channel they have to do login.
14 | - for detailed features scroll down to features section
15 |
16 | ---
17 |
18 | ## 🔧 Features
19 | - Extract content from both public and private channels/groups.
20 | - Custom bot functionality added use `/setbot`
21 | - 128 bit encryption for data saving use @v3saverbot on telegram to generate `MASTER_KEY`, `IV_KEY`
22 | - Rename and forward content to other channels or users.
23 | - extract restricted content from other bots how to use format link like `https://botusername(without @)/message_id(get it from plus messenger)`
24 | - `/login` method along with `session` based login
25 | - Custom captions and thumbnails.
26 | - Auto-remove default video thumbnails.
27 | - Delete or replace words in filenames and captions.
28 | - Auto-pin messages if enabled.
29 | - download yt/insta/Twitter/fb ect normal ytdlp supported sites that supports best format
30 | - Login via phone number.
31 | - **Supports 4GB file uploads**: The bot can handle large file uploads, up to 4GB in size.
32 | - file splitter if not premium string
33 | - **Enhanced Timer**: Distinct timers for free and paid users to limit usage and improve service.
34 | - **Improved Looping**: Optimized looping for processing multiple files or links, reducing delays and enhancing performance.
35 | - **Premium Access**: Premium users enjoy faster processing speeds and priority queue management.
36 | - ~~ads setup shorlink ads token system~~
37 | - ~~fast uploader via `SpyLib` using Telethon modules and `mautrix bridge repo`~~
38 | - Directly upload to `topic` in any topic enabled group
39 | - real time download and uplaod progress, support chats, text , audio, video , video note sticker everything
40 |
41 |
42 | ## ⚡ Commands
43 |
44 | - **`start`**: 🚀 Start the bot.
45 | - **`batch`**: 🫠 Extract in bulk.
46 | - **`login`**: 🔑 Get into the bot.
47 | - **`single`**: Process single link.
48 | - **`setbot`**: add your custome bot.
49 | - **`logout`**: 🚪 Get out of the bot.
50 | - **`adl`**: 👻 Download audio from 30+ sites.
51 | - **`dl`**: 💀 Download videos from 30+ sites.
52 | - **`transfer`**: 💘 Gift premium to others.
53 | - **`status`**: ⌛ Get your plan details.
54 | - **`add`**: ➕ Add user to premium.
55 | - **`rem`**: ➖ Remove user from premium.
56 | - **`rembot`**: remove your custome bot.
57 | - **`session`**: 🧵 Generate Pyrogramv2 session.
58 | - **`settings`**: ⚙️ Personalize settings.
59 | - **`stats`**: 📊 Get stats of the bot.
60 | - **`plan`**: 🗓️ Check our premium plans.
61 | - **`terms`**: 🥺 Terms and conditions.
62 | - **`help`**: ❓ Help if you're new.
63 | - **`cancel`**: 🚫 Cancel batch process.
64 |
65 |
66 | ## ⚙️ Required Variables
67 |
68 |
69 | Click to view required variables
70 |
71 | To run the bot, you'll need to configure a few sensitive variables. Here's how to set them up securely:
72 |
73 | - **`API_ID`**: Your API ID from [telegram.org](https://my.telegram.org/auth).
74 | - **`API_HASH`**: Your API Hash from [telegram.org](https://my.telegram.org/auth).
75 | - **`BOT_TOKEN`**: Get your bot token from [@BotFather](https://t.me/botfather).
76 | - **`OWNER_ID`**: Use [@missrose_bot](https://t.me/missrose_bot) to get your user ID by sending `/info`.
77 | - **`CHANNEL_ID`**: The ID of the channel for forced subscription.
78 | - **`LOG_GROUP`**: A group or channel where the bot logs messages. Forward a message to [@userinfobot](https://t.me/userinfobot) to get your channel/group ID.
79 | - **`MONGO_DB`**: A MongoDB URL for storing session data (recommended for security).
80 |
81 | ### Additional Configuration Options:
82 | - **`STRING`**: (Optional) Add your **premium account session string** here to allow 4GB file uploads. This is **optional** and can be left empty if not used.
83 | - **`FREEMIUM_LIMIT`**: Default is `0`. Set this to any value you want to allow free users to extract content. If set to `0`, free users will not have access to any extraction features.
84 | - **`PREMIUM_LIMIT`**: Default is `500`. This is the batch limit for premium users. You can customize this to allow premium users to process more links/files in one batch.
85 | - **`YT_COOKIES`**: Yt cookies for downloading yt videos
86 | - **`INSTA_COOKIES`**: If you want to enable instagram downloading fill cookiesn
87 |
88 | **How to get cookies ??** : use mozila firfox if on android or use chrome on desktop and download extension get this cookie or any Netscape Cookies (HTTP Cookies) extractor and use that
89 |
90 | ### Monetization (Optional):
91 | - **`WEBSITE_URL`**: (Optional) This is the domain for your monetization short link service. Provide the shortener's domain name, for example: `upshrink.com`. Do **not** include `www` or `https://`. The default link shortener is already set.
92 | - **`AD_API`**: (Optional) The API key from your link shortener service (e.g., **Upshrink**, **AdFly**, etc.) to monetize links. Enter the API provided by your shortener.
93 |
94 | > **Important:** Always keep your credentials secure! Never hard-code them in the repository. Use environment variables or a `.env` file.
95 |
96 |
97 |
98 | ---
99 |
100 | ## 🚀 Deployment Guide
101 |
102 |
103 | Deploy on VPS
104 |
105 | 1. Fork the repo.
106 | 2. Update `config.py` with your values.
107 | 3. Run the following:
108 | ```bash
109 | sudo apt update
110 | sudo apt install ffmpeg git python3-pip
111 | git clone your_repo_link
112 | cd your_repo_name
113 | pip3 install -r requirements.txt
114 | python3 main.py
115 | ```
116 |
117 | - To run the bot in the background:
118 | ```bash
119 | screen -S gagan
120 | python3 main.py
121 | ```
122 | - Detach: `Ctrl + A`, then `Ctrl + D`
123 | - To stop: `screen -r gagan` and `screen -S gagan -X quit`
124 |
125 |
126 |
127 |
128 | Deploy on Heroku
129 |
130 | 1. Fork and Star the repo.
131 | 2. Click [](https://www.heroku.com/deploy).
132 | 3. Enter required variables and click deploy ✅.
133 |
134 |
135 |
136 |
137 | Deploy on Render
138 |
139 | 1. Fork and star the repo.
140 | 2. Edit `config.py` or set environment variables on Render.
141 | 3. Go to [render.com](https://render.com), sign up/log in.
142 | 4. Create a new web service, select the free plan.
143 | 5. Connect your GitHub repo and deploy ✅.
144 |
145 |
146 |
147 |
148 | Deploy on Koyeb
149 |
150 | 1. Fork and star the repo.
151 | 2. Edit `config.py` or set environment variables on Koyeb.
152 | 3. Create a new service, select `Dockerfile` as build type.
153 | 4. Connect your GitHub repo and deploy ✅.
154 |
155 |
156 |
157 | ---
158 | ### ⚠️ Must Do: Secure Your Sensitive Variables
159 |
160 | **Do not expose sensitive variables (e.g., `API_ID`, `API_HASH`, `BOT_TOKEN`) on GitHub. Use environment variables to keep them secure.**
161 |
162 | ### Configuring Variables Securely:
163 |
164 | - **On VPS or Local Machine:**
165 | - Use a text editor to edit `config.py`:
166 | ```bash
167 | nano config.py
168 | ```
169 | - Alternatively, export as environment variables:
170 | ```bash
171 | export API_ID=your_api_id
172 | export API_HASH=your_api_hash
173 | export BOT_TOKEN=your_bot_token
174 | ```
175 |
176 | - **For Cloud Platforms (Heroku, Railway, etc.):**
177 | - Set environment variables directly in your platform’s dashboard.
178 |
179 | - **Using `.env` File:**
180 | - Create a `.env` file and add your credentials:
181 | ```
182 | API_ID=your_api_id
183 | API_HASH=your_api_hash
184 | BOT_TOKEN=your_bot_token
185 | ```
186 | - Make sure to add `.env` to `.gitignore` to prevent it from being pushed to GitHub.
187 |
188 | **Why This is Important?**
189 | Your credentials can be stolen if pushed to a public repository. Always keep them secure by using environment variables or local configuration files.
190 |
191 | ---
192 |
193 | ## 🛠️ Terms of Use
194 |
195 | Visit the [Terms of Use](https://github.com/devgaganin/Save-Restricted-Content-Bot-Repo/blob/master/TERMS_OF_USE.md) page to review and accept the guidelines.
196 | ## Important Note
197 |
198 | **Note**: Changing the terms and commands doesn't magically make you a developer. Real development involves understanding the code, writing new functionalities, and debugging issues, not just renaming things. If only it were that easy!
199 |
200 |
201 |
202 | Developed with ❤️ by Gagan
203 |
204 |
205 |
--------------------------------------------------------------------------------
/plugins/start.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from shared_client import app
6 | from pyrogram import filters
7 | from pyrogram.errors import UserNotParticipant
8 | from pyrogram.types import BotCommand, InlineKeyboardButton, InlineKeyboardMarkup
9 | from config import LOG_GROUP, OWNER_ID, FORCE_SUB
10 |
11 | async def subscribe(app, message):
12 | if FORCE_SUB:
13 | try:
14 | user = await app.get_chat_member(FORCE_SUB, message.from_user.id)
15 | if str(user.status) == "ChatMemberStatus.BANNED":
16 | await message.reply_text("You are Banned. Contact -- Team SPY")
17 | return 1
18 | except UserNotParticipant:
19 | link = await app.export_chat_invite_link(FORCE_SUB)
20 | caption = f"Join our channel to use the bot"
21 | await message.reply_photo(photo="https://graph.org/file/d44f024a08ded19452152.jpg",caption=caption, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Join Now...", url=f"{link}")]]))
22 | return 1
23 | except Exception as ggn:
24 | await message.reply_text(f"Something Went Wrong. Contact admins... with following message {ggn}")
25 | return 1
26 |
27 | @app.on_message(filters.command("set"))
28 | async def set(_, message):
29 | if message.from_user.id not in OWNER_ID:
30 | await message.reply("You are not authorized to use this command.")
31 | return
32 |
33 | await app.set_bot_commands([
34 | BotCommand("start", "🚀 Start the bot"),
35 | BotCommand("batch", "🫠 Extract in bulk"),
36 | BotCommand("login", "🔑 Get into the bot"),
37 | BotCommand("setbot", "🧸 Add your bot for handling files"),
38 | BotCommand("logout", "🚪 Get out of the bot"),
39 | BotCommand("adl", "👻 Download audio from 30+ sites"),
40 | BotCommand("dl", "💀 Download videos from 30+ sites"),
41 | BotCommand("status", "⟳ Refresh Payment status"),
42 | BotCommand("transfer", "💘 Gift premium to others"),
43 | BotCommand("add", "➕ Add user to premium"),
44 | BotCommand("rem", "➖ Remove from premium"),
45 | BotCommand("rembot", "🤨 Remove your custom bot"),
46 | BotCommand("settings", "⚙️ Personalize things"),
47 | BotCommand("plan", "🗓️ Check our premium plans"),
48 | BotCommand("terms", "🥺 Terms and conditions"),
49 | BotCommand("help", "❓ If you're a noob, still!"),
50 | BotCommand("cancel", "🚫 Cancel login/batch/settings process"),
51 | BotCommand("stop", "🚫 Cancel batch process")
52 | ])
53 |
54 | await message.reply("✅ Commands configured successfully!")
55 |
56 |
57 |
58 |
59 | help_pages = [
60 | (
61 | "📝 **Bot Commands Overview (1/2)**:\n\n"
62 | "1. **/add userID**\n"
63 | "> Add user to premium (Owner only)\n\n"
64 | "2. **/rem userID**\n"
65 | "> Remove user from premium (Owner only)\n\n"
66 | "3. **/transfer userID**\n"
67 | "> Transfer premium to your beloved major purpose for resellers (Premium members only)\n\n"
68 | "4. **/get**\n"
69 | "> Get all user IDs (Owner only)\n\n"
70 | "5. **/lock**\n"
71 | "> Lock channel from extraction (Owner only)\n\n"
72 | "6. **/dl link**\n"
73 | "> Download videos (Not available in v3 if you are using)\n\n"
74 | "7. **/adl link**\n"
75 | "> Download audio (Not available in v3 if you are using)\n\n"
76 | "8. **/login**\n"
77 | "> Log into the bot for private channel access\n\n"
78 | "9. **/batch**\n"
79 | "> Bulk extraction for posts (After login)\n\n"
80 | ),
81 | (
82 | "📝 **Bot Commands Overview (2/2)**:\n\n"
83 | "10. **/logout**\n"
84 | "> Logout from the bot\n\n"
85 | "11. **/stats**\n"
86 | "> Get bot stats\n\n"
87 | "12. **/plan**\n"
88 | "> Check premium plans\n\n"
89 | "13. **/speedtest**\n"
90 | "> Test the server speed (not available in v3)\n\n"
91 | "14. **/terms**\n"
92 | "> Terms and conditions\n\n"
93 | "15. **/cancel**\n"
94 | "> Cancel ongoing batch process\n\n"
95 | "16. **/myplan**\n"
96 | "> Get details about your plans\n\n"
97 | "17. **/session**\n"
98 | "> Generate Pyrogram V2 session\n\n"
99 | "18. **/settings**\n"
100 | "> 1. SETCHATID : To directly upload in channel or group or user's dm use it with -100[chatID]\n"
101 | "> 2. SETRENAME : To add custom rename tag or username of your channels\n"
102 | "> 3. CAPTION : To add custom caption\n"
103 | "> 4. REPLACEWORDS : Can be used for words in deleted set via REMOVE WORDS\n"
104 | "> 5. RESET : To set the things back to default\n\n"
105 | "> You can set CUSTOM THUMBNAIL, PDF WATERMARK, VIDEO WATERMARK, SESSION-based login, etc. from settings\n\n"
106 | "**__Powered by Team SPY__**"
107 | )
108 | ]
109 |
110 |
111 | async def send_or_edit_help_page(_, message, page_number):
112 | if page_number < 0 or page_number >= len(help_pages):
113 | return
114 |
115 |
116 | prev_button = InlineKeyboardButton("◀️ Previous", callback_data=f"help_prev_{page_number}")
117 | next_button = InlineKeyboardButton("Next ▶️", callback_data=f"help_next_{page_number}")
118 |
119 |
120 | buttons = []
121 | if page_number > 0:
122 | buttons.append(prev_button)
123 | if page_number < len(help_pages) - 1:
124 | buttons.append(next_button)
125 |
126 |
127 | keyboard = InlineKeyboardMarkup([buttons])
128 |
129 |
130 | await message.delete()
131 |
132 |
133 | await message.reply(
134 | help_pages[page_number],
135 | reply_markup=keyboard
136 | )
137 |
138 |
139 | @app.on_message(filters.command("help"))
140 | async def help(client, message):
141 | join = await subscribe(client, message)
142 | if join == 1:
143 | return
144 |
145 | await send_or_edit_help_page(client, message, 0)
146 |
147 |
148 | @app.on_callback_query(filters.regex(r"help_(prev|next)_(\d+)"))
149 | async def on_help_navigation(client, callback_query):
150 | action, page_number = callback_query.data.split("_")[1], int(callback_query.data.split("_")[2])
151 |
152 | if action == "prev":
153 | page_number -= 1
154 | elif action == "next":
155 | page_number += 1
156 |
157 | await send_or_edit_help_page(client, callback_query.message, page_number)
158 |
159 | await callback_query.answer()
160 |
161 |
162 | @app.on_message(filters.command("terms") & filters.private)
163 | async def terms(client, message):
164 | terms_text = (
165 | "> 📜 **Terms and Conditions** 📜\n\n"
166 | "✨ We are not responsible for user deeds, and we do not promote copyrighted content. If any user engages in such activities, it is solely their responsibility.\n"
167 | "✨ Upon purchase, we do not guarantee the uptime, downtime, or the validity of the plan. __Authorization and banning of users are at our discretion; we reserve the right to ban or authorize users at any time.__\n"
168 | "✨ Payment to us **__does not guarantee__** authorization for the /batch command. All decisions regarding authorization are made at our discretion and mood.\n"
169 | )
170 |
171 | buttons = InlineKeyboardMarkup(
172 | [
173 | [InlineKeyboardButton("📋 See Plans", callback_data="see_plan")],
174 | [InlineKeyboardButton("💬 Contact Now", url="https://t.me/kingofpatal")],
175 | ]
176 | )
177 | await message.reply_text(terms_text, reply_markup=buttons)
178 |
179 |
180 | @app.on_message(filters.command("plan") & filters.private)
181 | async def plan(client, message):
182 | plan_text = (
183 | "> 💰 **Premium Price**:\n\n Starting from $2 or 200 INR accepted via **__Amazon Gift Card__** (terms and conditions apply).\n"
184 | "📥 **Download Limit**: Users can download up to 100,000 files in a single batch command.\n"
185 | "🛑 **Batch**: You will get two modes /bulk and /batch.\n"
186 | " - Users are advised to wait for the process to automatically cancel before proceeding with any downloads or uploads.\n\n"
187 | "📜 **Terms and Conditions**: For further details and complete terms and conditions, please send /terms.\n"
188 | )
189 |
190 | buttons = InlineKeyboardMarkup(
191 | [
192 | [InlineKeyboardButton("📜 See Terms", callback_data="see_terms")],
193 | [InlineKeyboardButton("💬 Contact Now", url="https://t.me/kingofpatal")],
194 | ]
195 | )
196 | await message.reply_text(plan_text, reply_markup=buttons)
197 |
198 |
199 | @app.on_callback_query(filters.regex("see_plan"))
200 | async def see_plan(client, callback_query):
201 | plan_text = (
202 | "> 💰**Premium Price**\n\n Starting from $2 or 200 INR accepted via **__Amazon Gift Card__** (terms and conditions apply).\n"
203 | "📥 **Download Limit**: Users can download up to 100,000 files in a single batch command.\n"
204 | "🛑 **Batch**: You will get two modes /bulk and /batch.\n"
205 | " - Users are advised to wait for the process to automatically cancel before proceeding with any downloads or uploads.\n\n"
206 | "📜 **Terms and Conditions**: For further details and complete terms and conditions, please send /terms or click See Terms👇\n"
207 | )
208 |
209 | buttons = InlineKeyboardMarkup(
210 | [
211 | [InlineKeyboardButton("📜 See Terms", callback_data="see_terms")],
212 | [InlineKeyboardButton("💬 Contact Now", url="https://t.me/kingofpatal")],
213 | ]
214 | )
215 | await callback_query.message.edit_text(plan_text, reply_markup=buttons)
216 |
217 |
218 | @app.on_callback_query(filters.regex("see_terms"))
219 | async def see_terms(client, callback_query):
220 | terms_text = (
221 | "> 📜 **Terms and Conditions** 📜\n\n"
222 | "✨ We are not responsible for user deeds, and we do not promote copyrighted content. If any user engages in such activities, it is solely their responsibility.\n"
223 | "✨ Upon purchase, we do not guarantee the uptime, downtime, or the validity of the plan. __Authorization and banning of users are at our discretion; we reserve the right to ban or authorize users at any time.__\n"
224 | "✨ Payment to us **__does not guarantee__** authorization for the /batch command. All decisions regarding authorization are made at our discretion and mood.\n"
225 | )
226 |
227 | buttons = InlineKeyboardMarkup(
228 | [
229 | [InlineKeyboardButton("📋 See Plans", callback_data="see_plan")],
230 | [InlineKeyboardButton("💬 Contact Now", url="https://t.me/kingofpatal")],
231 | ]
232 | )
233 | await callback_query.message.edit_text(terms_text, reply_markup=buttons)
234 |
235 |
236 |
--------------------------------------------------------------------------------
/plugins/settings.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from telethon import events, Button
6 | import re
7 | import os
8 | import asyncio
9 | import string
10 | import random
11 | from shared_client import client as gf
12 | from config import OWNER_ID
13 | from utils.func import get_user_data_key, save_user_data, users_collection
14 |
15 | VIDEO_EXTENSIONS = {
16 | 'mp4', 'mkv', 'avi', 'mov', 'wmv', 'flv', 'webm',
17 | 'mpeg', 'mpg', '3gp'
18 | }
19 | SET_PIC = 'settings.jpg'
20 | MESS = 'Customize settings for your files...'
21 |
22 | active_conversations = {}
23 |
24 | @gf.on(events.NewMessage(incoming=True, pattern='/settings'))
25 | async def settings_command(event):
26 | user_id = event.sender_id
27 | await send_settings_message(event.chat_id, user_id)
28 |
29 | async def send_settings_message(chat_id, user_id):
30 | buttons = [
31 | [
32 | Button.inline('📝 Set Chat ID', b'setchat'),
33 | Button.inline('🏷️ Set Rename Tag', b'setrename')
34 | ],
35 | [
36 | Button.inline('📋 Set Caption', b'setcaption'),
37 | Button.inline('🔄 Replace Words', b'setreplacement')
38 | ],
39 | [
40 | Button.inline('🗑️ Remove Words', b'delete'),
41 | Button.inline('🔄 Reset Settings', b'reset')
42 | ],
43 | [
44 | Button.inline('🔑 Session Login', b'addsession'),
45 | Button.inline('🚪 Logout', b'logout')
46 | ],
47 | [
48 | Button.inline('🖼️ Set Thumbnail', b'setthumb'),
49 | Button.inline('❌ Remove Thumbnail', b'remthumb')
50 | ],
51 | [
52 | Button.url('🆘 Report Errors', 'https://t.me/team_spy_pro')
53 | ]
54 | ]
55 | await gf.send_message(chat_id, MESS, buttons=buttons)
56 |
57 | @gf.on(events.CallbackQuery)
58 | async def callback_query_handler(event):
59 | user_id = event.sender_id
60 |
61 | callback_actions = {
62 | b'setchat': {
63 | 'type': 'setchat',
64 | 'message': """Send me the ID of that chat(with -100 prefix):
65 | __👉 **Note:** if you are using custom bot then your bot should be admin that chat if not then this bot should be admin.__
66 | 👉 __If you want to upload in topic group and in specific topic then pass chat id as **-100CHANNELID/TOPIC_ID** for example: **-1004783898/12**__"""
67 | },
68 | b'setrename': {
69 | 'type': 'setrename',
70 | 'message': 'Send me the rename tag:'
71 | },
72 | b'setcaption': {
73 | 'type': 'setcaption',
74 | 'message': 'Send me the caption:'
75 | },
76 | b'setreplacement': {
77 | 'type': 'setreplacement',
78 | 'message': "Send me the replacement words in the format: 'WORD(s)' 'REPLACEWORD'"
79 | },
80 | b'addsession': {
81 | 'type': 'addsession',
82 | 'message': 'Send Pyrogram V2 session string:'
83 | },
84 | b'delete': {
85 | 'type': 'deleteword',
86 | 'message': 'Send words separated by space to delete them from caption/filename...'
87 | },
88 | b'setthumb': {
89 | 'type': 'setthumb',
90 | 'message': 'Please send the photo you want to set as the thumbnail.'
91 | }
92 | }
93 |
94 | if event.data in callback_actions:
95 | action = callback_actions[event.data]
96 | await start_conversation(event, user_id, action['type'], action['message'])
97 | elif event.data == b'logout':
98 | result = await users_collection.update_one(
99 | {'user_id': user_id},
100 | {'$unset': {'session_string': ''}}
101 | )
102 | if result.modified_count > 0:
103 | await event.respond('Logged out and deleted session successfully.')
104 | else:
105 | await event.respond('You are not logged in.')
106 | elif event.data == b'reset':
107 | try:
108 | await users_collection.update_one(
109 | {'user_id': user_id},
110 | {'$unset': {
111 | 'delete_words': '',
112 | 'replacement_words': '',
113 | 'rename_tag': '',
114 | 'caption': '',
115 | 'chat_id': ''
116 | }}
117 | )
118 | thumbnail_path = f'{user_id}.jpg'
119 | if os.path.exists(thumbnail_path):
120 | os.remove(thumbnail_path)
121 | await event.respond('✅ All settings reset successfully. To logout, click /logout')
122 | except Exception as e:
123 | await event.respond(f'Error resetting settings: {e}')
124 | elif event.data == b'remthumb':
125 | try:
126 | os.remove(f'{user_id}.jpg')
127 | await event.respond('Thumbnail removed successfully!')
128 | except FileNotFoundError:
129 | await event.respond('No thumbnail found to remove.')
130 |
131 | async def start_conversation(event, user_id, conv_type, prompt_message):
132 | if user_id in active_conversations:
133 | await event.respond('Previous conversation cancelled. Starting new one.')
134 |
135 | msg = await event.respond(f'{prompt_message}\n\n(Send /cancel to cancel this operation)')
136 | active_conversations[user_id] = {'type': conv_type, 'message_id': msg.id}
137 |
138 | @gf.on(events.NewMessage(pattern='/cancel'))
139 | async def cancel_conversation(event):
140 | user_id = event.sender_id
141 | if user_id in active_conversations:
142 | await event.respond('Cancelled enjoy baby...')
143 | del active_conversations[user_id]
144 |
145 | @gf.on(events.NewMessage())
146 | async def handle_conversation_input(event):
147 | user_id = event.sender_id
148 | if user_id not in active_conversations or event.message.text.startswith('/'):
149 | return
150 |
151 | conv_type = active_conversations[user_id]['type']
152 |
153 | handlers = {
154 | 'setchat': handle_setchat,
155 | 'setrename': handle_setrename,
156 | 'setcaption': handle_setcaption,
157 | 'setreplacement': handle_setreplacement,
158 | 'addsession': handle_addsession,
159 | 'deleteword': handle_deleteword,
160 | 'setthumb': handle_setthumb
161 | }
162 |
163 | if conv_type in handlers:
164 | await handlers[conv_type](event, user_id)
165 |
166 | if user_id in active_conversations:
167 | del active_conversations[user_id]
168 |
169 | async def handle_setchat(event, user_id):
170 | try:
171 | chat_id = event.text.strip()
172 | await save_user_data(user_id, 'chat_id', chat_id)
173 | await event.respond('✅ Chat ID set successfully!')
174 | except Exception as e:
175 | await event.respond(f'❌ Error setting chat ID: {e}')
176 |
177 | async def handle_setrename(event, user_id):
178 | rename_tag = event.text.strip()
179 | await save_user_data(user_id, 'rename_tag', rename_tag)
180 | await event.respond(f'✅ Rename tag set to: {rename_tag}')
181 |
182 | async def handle_setcaption(event, user_id):
183 | caption = event.text
184 | await save_user_data(user_id, 'caption', caption)
185 | await event.respond(f'✅ Caption set successfully!')
186 |
187 | async def handle_setreplacement(event, user_id):
188 | match = re.match("'(.+)' '(.+)'", event.text)
189 | if not match:
190 | await event.respond("❌ Invalid format. Usage: 'WORD(s)' 'REPLACEWORD'")
191 | else:
192 | word, replace_word = match.groups()
193 | delete_words = await get_user_data_key(user_id, 'delete_words', [])
194 | if word in delete_words:
195 | await event.respond(f"❌ The word '{word}' is in the delete list and cannot be replaced.")
196 | else:
197 | replacements = await get_user_data_key(user_id, 'replacement_words', {})
198 | replacements[word] = replace_word
199 | await save_user_data(user_id, 'replacement_words', replacements)
200 | await event.respond(f"✅ Replacement saved: '{word}' will be replaced with '{replace_word}'")
201 |
202 | async def handle_addsession(event, user_id):
203 | session_string = event.text.strip()
204 | await save_user_data(user_id, 'session_string', session_string)
205 | await event.respond('✅ Session string added successfully!')
206 |
207 | async def handle_deleteword(event, user_id):
208 | words_to_delete = event.message.text.split()
209 | delete_words = await get_user_data_key(user_id, 'delete_words', [])
210 | delete_words = list(set(delete_words + words_to_delete))
211 | await save_user_data(user_id, 'delete_words', delete_words)
212 | await event.respond(f"✅ Words added to delete list: {', '.join(words_to_delete)}")
213 |
214 | async def handle_setthumb(event, user_id):
215 | if event.photo:
216 | temp_path = await event.download_media()
217 | try:
218 | thumb_path = f'{user_id}.jpg'
219 | if os.path.exists(thumb_path):
220 | os.remove(thumb_path)
221 | os.rename(temp_path, thumb_path)
222 | await event.respond('✅ Thumbnail saved successfully!')
223 | except Exception as e:
224 | await event.respond(f'❌ Error saving thumbnail: {e}')
225 | else:
226 | await event.respond('❌ Please send a photo. Operation cancelled.')
227 |
228 | def generate_random_name(length=7):
229 | characters = string.ascii_letters + string.digits
230 | return ''.join(random.choice(characters) for _ in range(length))
231 |
232 |
233 | async def rename_file(file, sender, edit):
234 | try:
235 | delete_words = await get_user_data_key(sender, 'delete_words', [])
236 | custom_rename_tag = await get_user_data_key(sender, 'rename_tag', '')
237 | replacements = await get_user_data_key(sender, 'replacement_words', {})
238 |
239 | last_dot_index = str(file).rfind('.')
240 | if last_dot_index != -1 and last_dot_index != 0:
241 | ggn_ext = str(file)[last_dot_index + 1:]
242 | if ggn_ext.isalpha() and len(ggn_ext) <= 9:
243 | if ggn_ext.lower() in VIDEO_EXTENSIONS:
244 | original_file_name = str(file)[:last_dot_index]
245 | file_extension = 'mp4'
246 | else:
247 | original_file_name = str(file)[:last_dot_index]
248 | file_extension = ggn_ext
249 | else:
250 | original_file_name = str(file)[:last_dot_index]
251 | file_extension = 'mp4'
252 | else:
253 | original_file_name = str(file)
254 | file_extension = 'mp4'
255 |
256 | for word in delete_words:
257 | original_file_name = original_file_name.replace(word, '')
258 |
259 | for word, replace_word in replacements.items():
260 | original_file_name = original_file_name.replace(word, replace_word)
261 |
262 | new_file_name = f'{original_file_name} {custom_rename_tag}.{file_extension}'
263 |
264 | os.rename(file, new_file_name)
265 | return new_file_name
266 | except Exception as e:
267 | print(f"Rename error: {e}")
268 | return file
269 |
270 |
--------------------------------------------------------------------------------
/utils/func.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | import concurrent.futures
6 | import time
7 | import os
8 | import re
9 | import cv2
10 | import logging
11 | import asyncio
12 | from datetime import datetime, timedelta
13 | from motor.motor_asyncio import AsyncIOMotorClient
14 | from config import MONGO_DB as MONGO_URI, DB_NAME
15 |
16 | logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
17 | logger = logging.getLogger(__name__)
18 |
19 | PUBLIC_LINK_PATTERN = re.compile(r'(https?://)?(t\.me|telegram\.me)/([^/]+)(/(\d+))?')
20 | PRIVATE_LINK_PATTERN = re.compile(r'(https?://)?(t\.me|telegram\.me)/c/(\d+)(/(\d+))?')
21 | VIDEO_EXTENSIONS = {"mp4", "mkv", "avi", "mov", "wmv", "flv", "webm", "mpeg", "mpg", "3gp"}
22 |
23 | mongo_client = AsyncIOMotorClient(MONGO_URI)
24 | db = mongo_client[DB_NAME]
25 | users_collection = db["users"]
26 | premium_users_collection = db["premium_users"]
27 | statistics_collection = db["statistics"]
28 | codedb = db["redeem_code"]
29 |
30 | # ------- < start > Session Encoder don't change -------
31 |
32 | a1 = "c2F2ZV9yZXN0cmljdGVkX2NvbnRlbnRfYm90cw=="
33 | a2 = "Nzk2"
34 | a3 = "Z2V0X21lc3NhZ2Vz"
35 | a4 = "cmVwbHlfcGhvdG8="
36 | a5 = "c3RhcnQ="
37 | attr1 = "cGhvdG8="
38 | attr2 = "ZmlsZV9pZA=="
39 | a7 = "SGkg8J+RiyBXZWxjb21lLCBXYW5uYSBpbnRyby4uLj8gCgrinLPvuI8gSSBjYW4gc2F2ZSBwb3N0cyBmcm9tIGNoYW5uZWxzIG9yIGdyb3VwcyB3aGVyZSBmb3J3YXJkaW5nIGlzIG9mZi4gSSBjYW4gZG93bmxvYWQgdmlkZW9zL2F1ZGlvIGZyb20gWVQsIElOU1RBLCAuLi4gc29jaWFsIHBsYXRmb3JtcwrinLPvuI8gU2ltcGx5IHNlbmQgdGhlIHBvc3QgbGluayBvZiBhIHB1YmxpYyBjaGFubmVsLiBGb3IgcHJpdmF0ZSBjaGFubmVscywgZG8gL2xvZ2luLiBTZW5kIC9oZWxwIHRvIGtub3cgbW9yZS4="
40 | a8 = "Sm9pbiBDaGFubmVs"
41 | a9 = "R2V0IFByZW1pdW0="
42 | a10 = "aHR0cHM6Ly90Lm1lL3RlYW1fc3B5X3Bybw=="
43 | a11 = "aHR0cHM6Ly90Lm1lL2tpbmdvZnBhdGFs"
44 |
45 | # ------- < end > Session Encoder don't change --------
46 |
47 | def is_private_link(link):
48 | return bool(PRIVATE_LINK_PATTERN.match(link))
49 |
50 |
51 | def thumbnail(sender):
52 | return f'{sender}.jpg' if os.path.exists(f'{sender}.jpg') else None
53 |
54 |
55 | def hhmmss(seconds):
56 | return time.strftime('%H:%M:%S', time.gmtime(seconds))
57 |
58 |
59 | def E(L):
60 | private_match = re.match(r'https://t\.me/c/(\d+)/(?:\d+/)?(\d+)', L)
61 | public_match = re.match(r'https://t\.me/([^/]+)/(?:\d+/)?(\d+)', L)
62 |
63 | if private_match:
64 | return f'-100{private_match.group(1)}', int(private_match.group(2)), 'private'
65 | elif public_match:
66 | return public_match.group(1), int(public_match.group(2)), 'public'
67 |
68 | return None, None, None
69 |
70 |
71 | def get_display_name(user):
72 | if user.first_name and user.last_name:
73 | return f"{user.first_name} {user.last_name}"
74 | elif user.first_name:
75 | return user.first_name
76 | elif user.last_name:
77 | return user.last_name
78 | elif user.username:
79 | return user.username
80 | else:
81 | return "Unknown User"
82 |
83 |
84 | def sanitize_filename(filename):
85 | return re.sub(r'[<>:"/\\|?*]', '_', filename)
86 |
87 |
88 | def get_dummy_filename(info):
89 | file_type = info.get("type", "file")
90 | extension = {
91 | "video": "mp4",
92 | "photo": "jpg",
93 | "document": "pdf",
94 | "audio": "mp3"
95 | }.get(file_type, "bin")
96 |
97 | return f"downloaded_file_{int(time.time())}.{extension}"
98 |
99 |
100 | async def is_private_chat(event):
101 | return event.is_private
102 |
103 |
104 | async def save_user_data(user_id, key, value):
105 | await users_collection.update_one(
106 | {"user_id": user_id},
107 | {"$set": {key: value}},
108 | upsert=True
109 | )
110 | # print(users_collection)
111 |
112 |
113 | async def get_user_data_key(user_id, key, default=None):
114 | user_data = await users_collection.find_one({"user_id": int(user_id)})
115 | # print(f"Fetching key '{key}' for user {user_id}: {user_data}")
116 | return user_data.get(key, default) if user_data else default
117 |
118 |
119 | async def get_user_data(user_id):
120 | try:
121 | user_data = await users_collection.find_one({"user_id": user_id})
122 | return user_data
123 | except Exception as e:
124 | # logger.error(f"Error retrieving user data for {user_id}: {e}")
125 | return None
126 |
127 |
128 | async def save_user_session(user_id, session_string):
129 | try:
130 | await users_collection.update_one(
131 | {"user_id": user_id},
132 | {"$set": {
133 | "session_string": session_string,
134 | "updated_at": datetime.now()
135 | }},
136 | upsert=True
137 | )
138 | logger.info(f"Saved session for user {user_id}")
139 | return True
140 | except Exception as e:
141 | logger.error(f"Error saving session for user {user_id}: {e}")
142 | return False
143 |
144 |
145 | async def remove_user_session(user_id):
146 | try:
147 | await users_collection.update_one(
148 | {"user_id": user_id},
149 | {"$unset": {"session_string": ""}}
150 | )
151 | logger.info(f"Removed session for user {user_id}")
152 | return True
153 | except Exception as e:
154 | logger.error(f"Error removing session for user {user_id}: {e}")
155 | return False
156 |
157 |
158 | async def save_user_bot(user_id, bot_token):
159 | try:
160 | await users_collection.update_one(
161 | {"user_id": user_id},
162 | {"$set": {
163 | "bot_token": bot_token,
164 | "updated_at": datetime.now()
165 | }},
166 | upsert=True
167 | )
168 | logger.info(f"Saved bot token for user {user_id}")
169 | return True
170 | except Exception as e:
171 | logger.error(f"Error saving bot token for user {user_id}: {e}")
172 | return False
173 |
174 |
175 | async def remove_user_bot(user_id):
176 | try:
177 | await users_collection.update_one(
178 | {"user_id": user_id},
179 | {"$unset": {"bot_token": ""}}
180 | )
181 | logger.info(f"Removed bot token for user {user_id}")
182 | return True
183 | except Exception as e:
184 | logger.error(f"Error removing bot token for user {user_id}: {e}")
185 | return False
186 |
187 |
188 | async def process_text_with_rules(user_id, text):
189 | if not text:
190 | return ""
191 |
192 | try:
193 | replacements = await get_user_data_key(user_id, "replacement_words", {})
194 | delete_words = await get_user_data_key(user_id, "delete_words", [])
195 |
196 | processed_text = text
197 | for word, replacement in replacements.items():
198 | processed_text = processed_text.replace(word, replacement)
199 |
200 | if delete_words:
201 | words = processed_text.split()
202 | filtered_words = [w for w in words if w not in delete_words]
203 | processed_text = " ".join(filtered_words)
204 |
205 | return processed_text
206 | except Exception as e:
207 | logger.error(f"Error processing text with rules: {e}")
208 | return text
209 |
210 |
211 | async def screenshot(video: str, duration: int, sender: str) -> str | None:
212 | existing_screenshot = f"{sender}.jpg"
213 | if os.path.exists(existing_screenshot):
214 | return existing_screenshot
215 |
216 | time_stamp = hhmmss(duration // 2)
217 | output_file = datetime.now().isoformat("_", "seconds") + ".jpg"
218 |
219 | cmd = [
220 | "ffmpeg",
221 | "-ss", time_stamp,
222 | "-i", video,
223 | "-frames:v", "1",
224 | output_file,
225 | "-y"
226 | ]
227 |
228 | process = await asyncio.create_subprocess_exec(
229 | *cmd,
230 | stdout=asyncio.subprocess.PIPE,
231 | stderr=asyncio.subprocess.PIPE
232 | )
233 |
234 | stdout, stderr = await process.communicate()
235 |
236 | if os.path.isfile(output_file):
237 | return output_file
238 | else:
239 | print(f"FFmpeg Error: {stderr.decode().strip()}")
240 | return None
241 |
242 |
243 | async def get_video_metadata(file_path):
244 | default_values = {'width': 1, 'height': 1, 'duration': 1}
245 | loop = asyncio.get_event_loop()
246 | executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
247 |
248 | try:
249 | def _extract_metadata():
250 | try:
251 | vcap = cv2.VideoCapture(file_path)
252 | if not vcap.isOpened():
253 | return default_values
254 |
255 | width = round(vcap.get(cv2.CAP_PROP_FRAME_WIDTH))
256 | height = round(vcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
257 | fps = vcap.get(cv2.CAP_PROP_FPS)
258 | frame_count = vcap.get(cv2.CAP_PROP_FRAME_COUNT)
259 |
260 | if fps <= 0:
261 | return default_values
262 |
263 | duration = round(frame_count / fps)
264 | if duration <= 0:
265 | return default_values
266 |
267 | vcap.release()
268 | return {'width': width, 'height': height, 'duration': duration}
269 | except Exception as e:
270 | logger.error(f"Error in video_metadata: {e}")
271 | return default_values
272 |
273 | return await loop.run_in_executor(executor, _extract_metadata)
274 |
275 | except Exception as e:
276 | logger.error(f"Error in get_video_metadata: {e}")
277 | return default_values
278 |
279 |
280 | async def add_premium_user(user_id, duration_value, duration_unit):
281 | try:
282 | now = datetime.now()
283 | expiry_date = None
284 |
285 | if duration_unit == "min":
286 | expiry_date = now + timedelta(minutes=duration_value)
287 | elif duration_unit == "hours":
288 | expiry_date = now + timedelta(hours=duration_value)
289 | elif duration_unit == "days":
290 | expiry_date = now + timedelta(days=duration_value)
291 | elif duration_unit == "weeks":
292 | expiry_date = now + timedelta(weeks=duration_value)
293 | elif duration_unit == "month":
294 | expiry_date = now + timedelta(days=30 * duration_value)
295 | elif duration_unit == "year":
296 | expiry_date = now + timedelta(days=365 * duration_value)
297 | elif duration_unit == "decades":
298 | expiry_date = now + timedelta(days=3650 * duration_value)
299 | else:
300 | return False, "Invalid duration unit"
301 |
302 | await premium_users_collection.update_one(
303 | {"user_id": user_id},
304 | {"$set": {
305 | "user_id": user_id,
306 | "subscription_start": now,
307 | "subscription_end": expiry_date,
308 | "expireAt": expiry_date
309 | }},
310 | upsert=True
311 | )
312 |
313 | await premium_users_collection.create_index("expireAt", expireAfterSeconds=0)
314 |
315 | return True, expiry_date
316 | except Exception as e:
317 | logger.error(f"Error adding premium user {user_id}: {e}")
318 | return False, str(e)
319 |
320 |
321 | async def is_premium_user(user_id):
322 | try:
323 | user = await premium_users_collection.find_one({"user_id": user_id})
324 | if user and "subscription_end" in user:
325 | now = datetime.now()
326 | return now < user["subscription_end"]
327 | return False
328 | except Exception as e:
329 | logger.error(f"Error checking premium status for {user_id}: {e}")
330 | return False
331 |
332 |
333 | async def get_premium_details(user_id):
334 | try:
335 | user = await premium_users_collection.find_one({"user_id": user_id})
336 | if user and "subscription_end" in user:
337 | return user
338 | return None
339 | except Exception as e:
340 | logger.error(f"Error getting premium details for {user_id}: {e}")
341 | return None
342 |
--------------------------------------------------------------------------------
/plugins/login.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | from pyrogram import Client, filters
6 | from pyrogram.types import Message
7 | from pyrogram.errors import BadRequest, SessionPasswordNeeded, PhoneCodeInvalid, PhoneCodeExpired, MessageNotModified
8 | import logging
9 | import os
10 | from config import API_HASH, API_ID
11 | from shared_client import app as bot
12 | from utils.func import save_user_session, get_user_data, remove_user_session, save_user_bot, remove_user_bot
13 | from utils.encrypt import ecs, dcs
14 | from plugins.batch import UB, UC
15 | from utils.custom_filters import login_in_progress, set_user_step, get_user_step
16 | logging.basicConfig(level=logging.INFO)
17 | logger = logging.getLogger(__name__)
18 | model = "v3saver Team SPY"
19 |
20 | STEP_PHONE = 1
21 | STEP_CODE = 2
22 | STEP_PASSWORD = 3
23 | login_cache = {}
24 |
25 | @bot.on_message(filters.command('login'))
26 | async def login_command(client, message):
27 | user_id = message.from_user.id
28 | set_user_step(user_id, STEP_PHONE)
29 | login_cache.pop(user_id, None)
30 | await message.delete()
31 | status_msg = await message.reply(
32 | """Please send your phone number with country code
33 | Example: `+12345678900`"""
34 | )
35 | login_cache[user_id] = {'status_msg': status_msg}
36 |
37 |
38 | @bot.on_message(filters.command("setbot"))
39 | async def set_bot_token(C, m):
40 | user_id = m.from_user.id
41 | args = m.text.split(" ", 1)
42 | if user_id in UB:
43 | try:
44 | await UB[user_id].stop()
45 | if UB.get(user_id, None):
46 | del UB[user_id] # Remove from dictionary
47 |
48 | try:
49 | if os.path.exists(f"user_{user_id}.session"):
50 | os.remove(f"user_{user_id}.session")
51 | except Exception:
52 | pass
53 |
54 | print(f"Stopped and removed old bot for user {user_id}")
55 | except Exception as e:
56 | print(f"Error stopping old bot for user {user_id}: {e}")
57 | del UB[user_id] # Remove from dictionary
58 |
59 | if len(args) < 2:
60 | await m.reply_text("⚠️ Please provide a bot token. Usage: `/setbto token`", quote=True)
61 | return
62 |
63 | bot_token = args[1].strip()
64 | await save_user_bot(user_id, bot_token)
65 | await m.reply_text("✅ Bot token saved successfully.", quote=True)
66 |
67 |
68 | @bot.on_message(filters.command("rembot"))
69 | async def rem_bot_token(C, m):
70 | user_id = m.from_user.id
71 | if user_id in UB:
72 | try:
73 | await UB[user_id].stop()
74 |
75 | if UB.get(user_id, None):
76 | del UB[user_id] # Remove from dictionary # Remove from dictionary
77 | print(f"Stopped and removed old bot for user {user_id}")
78 | try:
79 | if os.path.exists(f"user_{user_id}.session"):
80 | os.remove(f"user_{user_id}.session")
81 | except Exception:
82 | pass
83 | except Exception as e:
84 | print(f"Error stopping old bot for user {user_id}: {e}")
85 | if UB.get(user_id, None):
86 | del UB[user_id] # Remove from dictionary # Remove from dictionary
87 | try:
88 | if os.path.exists(f"user_{user_id}.session"):
89 | os.remove(f"user_{user_id}.session")
90 | except Exception:
91 | pass
92 | await remove_user_bot(user_id)
93 | await m.reply_text("✅ Bot token removed successfully.", quote=True)
94 |
95 |
96 | @bot.on_message(login_in_progress & filters.text & filters.private & ~filters.command([
97 | 'start', 'batch', 'cancel', 'login', 'logout', 'stop', 'set', 'pay',
98 | 'redeem', 'gencode', 'generate', 'keyinfo', 'encrypt', 'decrypt', 'keys', 'setbot', 'rembot']))
99 | async def handle_login_steps(client, message):
100 | user_id = message.from_user.id
101 | text = message.text.strip()
102 | step = get_user_step(user_id)
103 | try:
104 | await message.delete()
105 | except Exception as e:
106 | logger.warning(f'Could not delete message: {e}')
107 | status_msg = login_cache[user_id].get('status_msg')
108 | if not status_msg:
109 | status_msg = await message.reply('Processing...')
110 | login_cache[user_id]['status_msg'] = status_msg
111 | try:
112 | if step == STEP_PHONE:
113 | if not text.startswith('+'):
114 | await edit_message_safely(status_msg,
115 | '❌ Please provide a valid phone number starting with +')
116 | return
117 | await edit_message_safely(status_msg,
118 | '🔄 Processing phone number...')
119 | temp_client = Client(f'temp_{user_id}', api_id=API_ID, api_hash
120 | =API_HASH, device_model=model, in_memory=True)
121 | try:
122 | await temp_client.connect()
123 | sent_code = await temp_client.send_code(text)
124 | login_cache[user_id]['phone'] = text
125 | login_cache[user_id]['phone_code_hash'
126 | ] = sent_code.phone_code_hash
127 | login_cache[user_id]['temp_client'] = temp_client
128 | set_user_step(user_id, STEP_CODE)
129 | await edit_message_safely(status_msg,
130 | """✅ Verification code sent to your Telegram account.
131 |
132 | Please enter the code you received like 1 2 3 4 5 (i.e seperated by space):"""
133 | )
134 | except BadRequest as e:
135 | await edit_message_safely(status_msg,
136 | f"""❌ Error: {str(e)}
137 | Please try again with /login.""")
138 | await temp_client.disconnect()
139 | set_user_step(user_id, None)
140 | elif step == STEP_CODE:
141 | code = text.replace(' ', '')
142 | phone = login_cache[user_id]['phone']
143 | phone_code_hash = login_cache[user_id]['phone_code_hash']
144 | temp_client = login_cache[user_id]['temp_client']
145 | try:
146 | await edit_message_safely(status_msg, '🔄 Verifying code...')
147 | await temp_client.sign_in(phone, phone_code_hash, code)
148 | session_string = await temp_client.export_session_string()
149 | encrypted_session = ecs(session_string)
150 | await save_user_session(user_id, encrypted_session)
151 | await temp_client.disconnect()
152 | temp_status_msg = login_cache[user_id]['status_msg']
153 | login_cache.pop(user_id, None)
154 | login_cache[user_id] = {'status_msg': temp_status_msg}
155 | await edit_message_safely(status_msg,
156 | """✅ Logged in successfully!!"""
157 | )
158 | set_user_step(user_id, None)
159 | except SessionPasswordNeeded:
160 | set_user_step(user_id, STEP_PASSWORD)
161 | await edit_message_safely(status_msg,
162 | """🔒 Two-step verification is enabled.
163 | Please enter your password:"""
164 | )
165 | except (PhoneCodeInvalid, PhoneCodeExpired) as e:
166 | await edit_message_safely(status_msg,
167 | f'❌ {str(e)}. Please try again with /login.')
168 | await temp_client.disconnect()
169 | login_cache.pop(user_id, None)
170 | set_user_step(user_id, None)
171 | elif step == STEP_PASSWORD:
172 | temp_client = login_cache[user_id]['temp_client']
173 | try:
174 | await edit_message_safely(status_msg, '🔄 Verifying password...'
175 | )
176 | await temp_client.check_password(text)
177 | session_string = await temp_client.export_session_string()
178 | encrypted_session = ecs(session_string)
179 | await save_user_session(user_id, encrypted_session)
180 | await temp_client.disconnect()
181 | temp_status_msg = login_cache[user_id]['status_msg']
182 | login_cache.pop(user_id, None)
183 | login_cache[user_id] = {'status_msg': temp_status_msg}
184 | await edit_message_safely(status_msg,
185 | """✅ Logged in successfully!!"""
186 | )
187 | set_user_step(user_id, None)
188 | except BadRequest as e:
189 | await edit_message_safely(status_msg,
190 | f"""❌ Incorrect password: {str(e)}
191 | Please try again:""")
192 | except Exception as e:
193 | logger.error(f'Error in login flow: {str(e)}')
194 | await edit_message_safely(status_msg,
195 | f"""❌ An error occurred: {str(e)}
196 | Please try again with /login.""")
197 | if user_id in login_cache and 'temp_client' in login_cache[user_id]:
198 | await login_cache[user_id]['temp_client'].disconnect()
199 | login_cache.pop(user_id, None)
200 | set_user_step(user_id, None)
201 | async def edit_message_safely(message, text):
202 | """Helper function to edit message and handle errors"""
203 | try:
204 | await message.edit(text)
205 | except MessageNotModified:
206 | pass
207 | except Exception as e:
208 | logger.error(f'Error editing message: {e}')
209 |
210 | @bot.on_message(filters.command('cancel'))
211 | async def cancel_command(client, message):
212 | user_id = message.from_user.id
213 | await message.delete()
214 | if get_user_step(user_id):
215 | status_msg = login_cache.get(user_id, {}).get('status_msg')
216 | if user_id in login_cache and 'temp_client' in login_cache[user_id]:
217 | await login_cache[user_id]['temp_client'].disconnect()
218 | login_cache.pop(user_id, None)
219 | set_user_step(user_id, None)
220 | if status_msg:
221 | await edit_message_safely(status_msg,
222 | '✅ Login process cancelled. Use /login to start again.')
223 | else:
224 | temp_msg = await message.reply(
225 | '✅ Login process cancelled. Use /login to start again.')
226 | await temp_msg.delete(5)
227 | else:
228 | temp_msg = await message.reply('No active login process to cancel.')
229 | await temp_msg.delete(5)
230 |
231 | @bot.on_message(filters.command('logout'))
232 | async def logout_command(client, message):
233 | user_id = message.from_user.id
234 | await message.delete()
235 | status_msg = await message.reply('🔄 Processing logout request...')
236 | try:
237 | session_data = await get_user_data(user_id)
238 |
239 | if not session_data or 'session_string' not in session_data:
240 | await edit_message_safely(status_msg,
241 | '❌ No active session found for your account.')
242 | return
243 | encss = session_data['session_string']
244 | session_string = dcs(encss)
245 | temp_client = Client(f'temp_logout_{user_id}', api_id=API_ID,
246 | api_hash=API_HASH, session_string=session_string)
247 | try:
248 | await temp_client.connect()
249 | await temp_client.log_out()
250 | await edit_message_safely(status_msg,
251 | '✅ Telegram session terminated successfully. Removing from database...'
252 | )
253 | except Exception as e:
254 | logger.error(f'Error terminating session: {str(e)}')
255 | await edit_message_safely(status_msg,
256 | f"""⚠️ Error terminating Telegram session: {str(e)}
257 | Still removing from database..."""
258 | )
259 | finally:
260 | await temp_client.disconnect()
261 | await remove_user_session(user_id)
262 | await edit_message_safely(status_msg,
263 | '✅ Logged out successfully!!')
264 | try:
265 | if os.path.exists(f"{user_id}_client.session"):
266 | os.remove(f"{user_id}_client.session")
267 | except Exception:
268 | pass
269 | if UC.get(user_id, None):
270 | del UC[user_id]
271 | except Exception as e:
272 | logger.error(f'Error in logout command: {str(e)}')
273 | try:
274 | await remove_user_session(user_id)
275 | except Exception:
276 | pass
277 | if UC.get(user_id, None):
278 | del UC[user_id]
279 | await edit_message_safely(status_msg,
280 | f'❌ An error occurred during logout: {str(e)}')
281 | try:
282 | if os.path.exists(f"{user_id}_client.session"):
283 | os.remove(f"{user_id}_client.session")
284 | except Exception:
285 | pass
286 |
--------------------------------------------------------------------------------
/plugins/ytdl.py:
--------------------------------------------------------------------------------
1 | # ---------------------------------------------------
2 | # File Name: ytdl.py (pure code)
3 | # Description: A Pyrogram bot for downloading yt and other sites videos from Telegram channels or groups
4 | # and uploading them back to Telegram.
5 | # Author: Gagan
6 | # GitHub: https://github.com/devgaganin/
7 | # Telegram: https://t.me/team_spy_pro
8 | # YouTube: https://youtube.com/@dev_gagan
9 | # Created: 2025-01-11
10 | # Last Modified: 2025-01-11
11 | # Version: 2.0.5
12 | # License: MIT License
13 | # ---------------------------------------------------
14 |
15 | import yt_dlp
16 | import os
17 | import tempfile
18 | import time
19 | import asyncio
20 | import random
21 | import string
22 | import requests
23 | import logging
24 | import time
25 | import math
26 | from shared_client import client, app
27 | from telethon import events
28 | from telethon.sync import TelegramClient
29 | from telethon.tl.types import DocumentAttributeVideo
30 | from utils.func import get_video_metadata, screenshot
31 | from telethon.tl.functions.messages import EditMessageRequest
32 | from devgagantools import fast_upload
33 | from concurrent.futures import ThreadPoolExecutor
34 | import aiohttp
35 | import logging
36 | import aiofiles
37 | from config import YT_COOKIES, INSTA_COOKIES
38 | from mutagen.id3 import ID3, TIT2, TPE1, COMM, APIC
39 | from mutagen.mp3 import MP3
40 |
41 | logger = logging.getLogger(__name__)
42 |
43 |
44 | thread_pool = ThreadPoolExecutor()
45 | ongoing_downloads = {}
46 |
47 | def d_thumbnail(thumbnail_url, save_path):
48 | try:
49 | response = requests.get(thumbnail_url, stream=True)
50 | response.raise_for_status()
51 | with open(save_path, 'wb') as f:
52 | for chunk in response.iter_content(chunk_size=8192):
53 | f.write(chunk)
54 | return save_path
55 | except requests.exceptions.RequestException as e:
56 | logger.error(f"Failed to download thumbnail: {e}")
57 | return None
58 |
59 |
60 | async def download_thumbnail_async(url, path):
61 | async with aiohttp.ClientSession() as session:
62 | async with session.get(url) as response:
63 | if response.status == 200:
64 | with open(path, 'wb') as f:
65 | f.write(await response.read())
66 |
67 |
68 | async def extract_audio_async(ydl_opts, url):
69 | def sync_extract():
70 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
71 | return ydl.extract_info(url, download=True)
72 | return await asyncio.get_event_loop().run_in_executor(thread_pool, sync_extract)
73 |
74 |
75 | def get_random_string(length=7):
76 | characters = string.ascii_letters + string.digits
77 | return ''.join(random.choice(characters) for _ in range(length))
78 |
79 |
80 | async def process_audio(client, event, url, cookies_env_var=None):
81 | cookies = None
82 | if cookies_env_var:
83 | cookies = cookies_env_var
84 |
85 | temp_cookie_path = None
86 | if cookies:
87 | with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as temp_cookie_file:
88 | temp_cookie_file.write(cookies)
89 | temp_cookie_path = temp_cookie_file.name
90 |
91 | start_time = time.time()
92 | random_filename = f"@team_spy_pro_{event.sender_id}"
93 | download_path = f"{random_filename}.mp3"
94 |
95 | ydl_opts = {
96 | 'format': 'bestaudio/best',
97 | 'outtmpl': f"{random_filename}.%(ext)s",
98 | 'cookiefile': temp_cookie_path,
99 | 'postprocessors': [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192'}],
100 | 'quiet': False,
101 | 'noplaylist': True,
102 | }
103 | prog = None
104 |
105 | progress_message = await event.reply("**__Starting audio extraction...__**")
106 |
107 | try:
108 |
109 | info_dict = await extract_audio_async(ydl_opts, url)
110 | title = info_dict.get('title', 'Extracted Audio')
111 |
112 | await progress_message.edit("**__Editing metadata...__**")
113 |
114 |
115 | if os.path.exists(download_path):
116 | def edit_metadata():
117 | audio_file = MP3(download_path, ID3=ID3)
118 | try:
119 | audio_file.add_tags()
120 | except Exception:
121 | pass
122 | audio_file.tags["TIT2"] = TIT2(encoding=3, text=title)
123 | audio_file.tags["TPE1"] = TPE1(encoding=3, text="Team SPY")
124 | audio_file.tags["COMM"] = COMM(encoding=3, lang="eng", desc="Comment", text="Processed by Team SPY")
125 |
126 | thumbnail_url = info_dict.get('thumbnail')
127 | if thumbnail_url:
128 | thumbnail_path = os.path.join(tempfile.gettempdir(), "thumb.jpg")
129 | asyncio.run(download_thumbnail_async(thumbnail_url, thumbnail_path))
130 | with open(thumbnail_path, 'rb') as img:
131 | audio_file.tags["APIC"] = APIC(
132 | encoding=3, mime='image/jpeg', type=3, desc='Cover', data=img.read()
133 | )
134 | os.remove(thumbnail_path)
135 | audio_file.save()
136 |
137 | await asyncio.to_thread(edit_metadata)
138 |
139 |
140 |
141 |
142 | chat_id = event.chat_id
143 | if os.path.exists(download_path):
144 | await progress_message.delete()
145 | prog = await client.send_message(chat_id, "**__Starting Upload...__**")
146 | uploaded = await fast_upload(
147 | client, download_path,
148 | reply=prog,
149 | name=None,
150 | progress_bar_function=lambda done, total: progress_callback(done, total, chat_id)
151 | )
152 | await client.send_file(chat_id, uploaded, caption=f"**{title}**\n\n**__Powered by Team SPY__**")
153 | if prog:
154 | await prog.delete()
155 | else:
156 | await event.reply("**__Audio file not found after extraction!__**")
157 |
158 | except Exception as e:
159 | logger.exception("Error during audio extraction or upload")
160 | await event.reply(f"**__An error occurred: {e}__**")
161 | finally:
162 | if os.path.exists(download_path):
163 | os.remove(download_path)
164 | if temp_cookie_path and os.path.exists(temp_cookie_path):
165 | os.remove(temp_cookie_path)
166 |
167 | @client.on(events.NewMessage(pattern="/adl"))
168 | async def handler(event):
169 | user_id = event.sender_id
170 | if user_id in ongoing_downloads:
171 | await event.reply("**You already have an ongoing download. Please wait until it completes!**")
172 | return
173 |
174 | if len(event.message.text.split()) < 2:
175 | await event.reply("**Usage:** `/adl `\n\nPlease provide a valid video link!")
176 | return
177 |
178 | url = event.message.text.split()[1]
179 | ongoing_downloads[user_id] = True
180 |
181 | try:
182 | if "instagram.com" in url:
183 | await process_audio(client, event, url, cookies_env_var="INSTA_COOKIES")
184 | elif "youtube.com" in url or "youtu.be" in url:
185 | await process_audio(client, event, url, cookies_env_var="YT_COOKIES")
186 | else:
187 | await process_audio(client, event, url)
188 | except Exception as e:
189 | await event.reply(f"**An error occurred:** `{e}`")
190 | finally:
191 | ongoing_downloads.pop(user_id, None)
192 |
193 |
194 | async def fetch_video_info(url, ydl_opts, progress_message, check_duration_and_size):
195 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
196 | info_dict = ydl.extract_info(url, download=False)
197 |
198 | if check_duration_and_size:
199 |
200 | duration = info_dict.get('duration', 0)
201 | if duration and duration > 3 * 3600:
202 | await progress_message.edit("**❌ __Video is longer than 3 hours. Download aborted...__**")
203 | return None
204 |
205 |
206 | estimated_size = info_dict.get('filesize_approx', 0)
207 | if estimated_size and estimated_size > 2 * 1024 * 1024 * 1024:
208 | await progress_message.edit("**🤞 __Video size is larger than 2GB. Aborting download.__**")
209 | return None
210 |
211 | return info_dict
212 |
213 | def download_video(url, ydl_opts):
214 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
215 | ydl.download([url])
216 |
217 |
218 | @client.on(events.NewMessage(pattern="/dl"))
219 | async def handler(event):
220 | user_id = event.sender_id
221 |
222 |
223 | if user_id in ongoing_downloads:
224 | await event.reply("**You already have an ongoing ytdlp download. Please wait until it completes!**")
225 | return
226 |
227 | if len(event.message.text.split()) < 2:
228 | await event.reply("**Usage:** `/dl `\n\nPlease provide a valid video link!")
229 | return
230 |
231 | url = event.message.text.split()[1]
232 |
233 |
234 | try:
235 | if "instagram.com" in url:
236 | await process_video(client, event, url, "INSTA_COOKIES", check_duration_and_size=False)
237 | elif "youtube.com" in url or "youtu.be" in url:
238 | await process_video(client, event, url, "YT_COOKIES", check_duration_and_size=True)
239 | else:
240 | await process_video(client, event, url, None, check_duration_and_size=False)
241 |
242 | except Exception as e:
243 | await event.reply(f"**An error occurred:** `{e}`")
244 | finally:
245 |
246 | ongoing_downloads.pop(user_id, None)
247 |
248 |
249 |
250 |
251 | user_progress = {}
252 |
253 | def progress_callback(done, total, user_id):
254 |
255 | if user_id not in user_progress:
256 | user_progress[user_id] = {
257 | 'previous_done': 0,
258 | 'previous_time': time.time()
259 | }
260 |
261 |
262 | user_data = user_progress[user_id]
263 |
264 |
265 | percent = (done / total) * 100
266 |
267 |
268 | completed_blocks = int(percent // 10)
269 | remaining_blocks = 10 - completed_blocks
270 | progress_bar = "♦" * completed_blocks + "◇" * remaining_blocks
271 |
272 |
273 | done_mb = done / (1024 * 1024)
274 | total_mb = total / (1024 * 1024)
275 |
276 |
277 | speed = done - user_data['previous_done']
278 | elapsed_time = time.time() - user_data['previous_time']
279 |
280 | if elapsed_time > 0:
281 | speed_bps = speed / elapsed_time
282 | speed_mbps = (speed_bps * 8) / (1024 * 1024)
283 | else:
284 | speed_mbps = 0
285 |
286 |
287 | if speed_bps > 0:
288 | remaining_time = (total - done) / speed_bps
289 | else:
290 | remaining_time = 0
291 |
292 |
293 | remaining_time_min = remaining_time / 60
294 |
295 |
296 | final = (
297 | f"╭──────────────────╮\n"
298 | f"│ **__Uploading...__** \n"
299 | f"├──────────\n"
300 | f"│ {progress_bar}\n\n"
301 | f"│ **__Progress:__** {percent:.2f}%\n"
302 | f"│ **__Done:__** {done_mb:.2f} MB / {total_mb:.2f} MB\n"
303 | f"│ **__Speed:__** {speed_mbps:.2f} Mbps\n"
304 | f"│ **__Time Remaining:__** {remaining_time_min:.2f} min\n"
305 | f"╰──────────────────╯\n\n"
306 | f"**__Powered by Team SPY__**"
307 | )
308 |
309 |
310 | user_data['previous_done'] = done
311 | user_data['previous_time'] = time.time()
312 |
313 | return final
314 |
315 | async def process_video(client, event, url, cookies_env_var, check_duration_and_size=False):
316 | start_time = time.time()
317 | logger.info(f"Received link: {url}")
318 |
319 | cookies = None
320 | if cookies_env_var:
321 | cookies = cookies_env_var
322 |
323 |
324 | random_filename = get_random_string() + ".mp4"
325 | download_path = os.path.abspath(random_filename)
326 | logger.info(f"Generated random download path: {download_path}")
327 |
328 |
329 | temp_cookie_path = None
330 | if cookies:
331 | with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as temp_cookie_file:
332 | temp_cookie_file.write(cookies)
333 | temp_cookie_path = temp_cookie_file.name
334 | logger.info(f"Created temporary cookie file at: {temp_cookie_path}")
335 |
336 |
337 | thumbnail_file = None
338 | metadata = {'width': None, 'height': None, 'duration': None, 'thumbnail': None}
339 |
340 |
341 | ydl_opts = {
342 | 'outtmpl': download_path,
343 | 'format': 'best',
344 | 'cookiefile': temp_cookie_path if temp_cookie_path else None,
345 | 'writethumbnail': True,
346 | 'verbose': True,
347 | }
348 | prog = None
349 | progress_message = await event.reply("**__Starting download...__**")
350 | logger.info("Starting the download process...")
351 | try:
352 | info_dict = await fetch_video_info(url, ydl_opts, progress_message, check_duration_and_size)
353 | if not info_dict:
354 | return
355 |
356 | await asyncio.to_thread(download_video, url, ydl_opts)
357 | title = info_dict.get('title', 'Powered by Team SPY')
358 | k = await get_video_metadata(download_path)
359 | W = k['width']
360 | H = k['height']
361 | D = k['duration']
362 | metadata['width'] = info_dict.get('width') or W
363 | metadata['height'] = info_dict.get('height') or H
364 | metadata['duration'] = int(info_dict.get('duration') or 0) or D
365 | thumbnail_url = info_dict.get('thumbnail', None)
366 | THUMB = None
367 |
368 |
369 | if thumbnail_url:
370 | thumbnail_file = os.path.join(tempfile.gettempdir(), get_random_string() + ".jpg")
371 | downloaded_thumb = d_thumbnail(thumbnail_url, thumbnail_file)
372 | if downloaded_thumb:
373 | logger.info(f"Thumbnail saved at: {downloaded_thumb}")
374 |
375 | if thumbnail_file:
376 | THUMB = thumbnail_file
377 | else:
378 | THUMB = await screenshot(download_path, metadata['duration'], event.sender_id)
379 |
380 | chat_id = event.chat_id
381 | SIZE = 2 * 1024 * 1024
382 | caption = f"{title}"
383 |
384 | if os.path.exists(download_path) and os.path.getsize(download_path) > SIZE:
385 | prog = await client.send_message(chat_id, "**__Starting Upload...__**")
386 | await split_and_upload_file(app, chat_id, download_path, caption)
387 | await prog.delete()
388 |
389 | if os.path.exists(download_path):
390 | await progress_message.delete()
391 | prog = await client.send_message(chat_id, "**__Starting Upload...__**")
392 | uploaded = await fast_upload(
393 | client, download_path,
394 | reply=prog,
395 | progress_bar_function=lambda done, total: progress_callback(done, total, chat_id)
396 | )
397 | await client.send_file(
398 | event.chat_id,
399 | uploaded,
400 | caption=f"**{title}**",
401 | attributes=[
402 | DocumentAttributeVideo(
403 | duration=metadata['duration'],
404 | w=metadata['width'],
405 | h=metadata['height'],
406 | supports_streaming=True
407 | )
408 | ],
409 | thumb=THUMB if THUMB else None
410 | )
411 | if prog:
412 | await prog.delete()
413 | else:
414 | await event.reply("**__File not found after download. Something went wrong!__**")
415 | except Exception as e:
416 | logger.exception("An error occurred during download or upload.")
417 | await event.reply(f"**__An error occurred: {e}__**")
418 | finally:
419 |
420 | if os.path.exists(download_path):
421 | os.remove(download_path)
422 | if temp_cookie_path and os.path.exists(temp_cookie_path):
423 | os.remove(temp_cookie_path)
424 | if thumbnail_file and os.path.exists(thumbnail_file):
425 | os.remove(thumbnail_file)
426 |
427 |
428 | async def split_and_upload_file(app, sender, file_path, caption):
429 | if not os.path.exists(file_path):
430 | await app.send_message(sender, "❌ File not found!")
431 | return
432 |
433 | file_size = os.path.getsize(file_path)
434 | start = await app.send_message(sender, f"ℹ️ File size: {file_size / (1024 * 1024):.2f} MB")
435 | PART_SIZE = 1.9 * 1024 * 1024 * 1024
436 |
437 | part_number = 0
438 | async with aiofiles.open(file_path, mode="rb") as f:
439 | while True:
440 | chunk = await f.read(PART_SIZE)
441 | if not chunk:
442 | break
443 |
444 | # Create part filename
445 | base_name, file_ext = os.path.splitext(file_path)
446 | part_file = f"{base_name}.part{str(part_number).zfill(3)}{file_ext}"
447 |
448 | # Write part to file
449 | async with aiofiles.open(part_file, mode="wb") as part_f:
450 | await part_f.write(chunk)
451 |
452 | # Uploading part
453 | edit = await app.send_message(sender, f"⬆️ Uploading part {part_number + 1}...")
454 | part_caption = f"{caption} \n\n**Part : {part_number + 1}**"
455 | await app.send_document(sender, document=part_file, caption=part_caption,
456 | progress=progress_bar,
457 | progress_args=("╭─────────────────────╮\n│ **__Pyro Uploader__**\n├─────────────────────", edit, time.time())
458 | )
459 | await edit.delete()
460 | os.remove(part_file)
461 |
462 | part_number += 1
463 |
464 | await start.delete()
465 | os.remove(file_path)
466 |
467 |
468 | PROGRESS_BAR = """
469 | │ **__Completed:__** {1}/{2}
470 | │ **__Bytes:__** {0}%
471 | │ **__Speed:__** {3}/s
472 | │ **__ETA:__** {4}
473 | ╰─────────────────────╯
474 | """
475 |
476 | async def get_seconds(time_string: str) -> int:
477 | """
478 | Converts a time string (e.g., '5min', '2hour') into seconds.
479 | """
480 | def extract_value_and_unit(ts: str):
481 | value = ''.join(filter(str.isdigit, ts))
482 | unit = ts[len(value):].strip()
483 | return int(value) if value else 0, unit
484 |
485 | value, unit = extract_value_and_unit(time_string)
486 | time_units = {
487 | 's': 1,
488 | 'min': 60,
489 | 'hour': 3600,
490 | 'day': 86400,
491 | 'month': 86400 * 30,
492 | 'year': 86400 * 365
493 | }
494 |
495 | return value * time_units.get(unit, 0)
496 |
497 | async def progress_bar(current: int, total: int, ud_type: str, message, start: float):
498 | """
499 | Updates the progress bar for an ongoing process.
500 | """
501 | now = time.time()
502 | diff = now - start
503 |
504 | if round(diff % 10) == 0 or current == total:
505 | percentage = (current * 100) / total
506 | speed = current / diff if diff else 0
507 | elapsed_time = round(diff * 1000)
508 | time_to_completion = round((total - current) / speed) * 1000 if speed else 0
509 | estimated_total_time = elapsed_time + time_to_completion
510 |
511 | elapsed_time_str = TimeFormatter(elapsed_time)
512 | estimated_total_time_str = TimeFormatter(estimated_total_time)
513 |
514 | progress = "".join(["♦" for _ in range(math.floor(percentage / 10))]) + \
515 | "".join(["◇" for _ in range(10 - math.floor(percentage / 10))])
516 |
517 | progress_text = progress + PROGRESS_BAR.format(
518 | round(percentage, 2),
519 | humanbytes(current),
520 | humanbytes(total),
521 | humanbytes(speed),
522 | estimated_total_time_str if estimated_total_time_str else "0 s"
523 | )
524 | try:
525 | await message.edit(text=f"{ud_type}\n│ {progress_text}")
526 | except:
527 | pass
528 |
529 | def humanbytes(size: int) -> str:
530 | """
531 | Converts bytes into a human-readable format.
532 | """
533 | if not size:
534 | return ""
535 |
536 | power = 2**10
537 | units = ['B', 'KB', 'MB', 'GB', 'TB']
538 | n = 0
539 | while size > power and n < len(units) - 1:
540 | size /= power
541 | n += 1
542 |
543 | return f"{round(size, 2)} {units[n]}"
544 |
545 | def TimeFormatter(milliseconds: int) -> str:
546 | """
547 | Formats milliseconds into a human-readable duration.
548 | """
549 | seconds, milliseconds = divmod(milliseconds, 1000)
550 | minutes, seconds = divmod(seconds, 60)
551 | hours, minutes = divmod(minutes, 60)
552 | days, hours = divmod(hours, 24)
553 |
554 | parts = []
555 | if days: parts.append(f"{days}d")
556 | if hours: parts.append(f"{hours}h")
557 | if minutes: parts.append(f"{minutes}m")
558 | if seconds: parts.append(f"{seconds}s")
559 | if milliseconds: parts.append(f"{milliseconds}ms")
560 |
561 | return ', '.join(parts)
562 |
563 | def convert(seconds: int) -> str:
564 | """
565 | Converts seconds into HH:MM:SS format.
566 | """
567 | hours, remainder = divmod(seconds, 3600)
568 | minutes, seconds = divmod(remainder, 60)
569 | return f"{hours}:{minutes:02d}:{seconds:02d}"
570 |
--------------------------------------------------------------------------------
/plugins/batch.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2025 devgagan : https://github.com/devgaganin.
2 | # Licensed under the GNU General Public License v3.0.
3 | # See LICENSE file in the repository root for full license text.
4 |
5 | import os, re, time, asyncio, json, asyncio
6 | from pyrogram import Client, filters
7 | from pyrogram.types import Message
8 | from pyrogram.errors import UserNotParticipant
9 | from config import API_ID, API_HASH, LOG_GROUP, STRING, FORCE_SUB, FREEMIUM_LIMIT, PREMIUM_LIMIT
10 | from utils.func import get_user_data, screenshot, thumbnail, get_video_metadata
11 | from utils.func import get_user_data_key, process_text_with_rules, is_premium_user, E
12 | from shared_client import app as X
13 | from plugins.settings import rename_file
14 | from plugins.start import subscribe as sub
15 | from utils.custom_filters import login_in_progress
16 | from utils.encrypt import dcs
17 | from typing import Dict, Any, Optional
18 |
19 |
20 | Y = None if not STRING else __import__('shared_client').userbot
21 | Z, P, UB, UC, emp = {}, {}, {}, {}, {}
22 |
23 | ACTIVE_USERS = {}
24 | ACTIVE_USERS_FILE = "active_users.json"
25 |
26 | # fixed directory file_name problems
27 | def sanitize(filename):
28 | return re.sub(r'[<>:"/\\|?*\']', '_', filename).strip(" .")[:255]
29 |
30 | def load_active_users():
31 | try:
32 | if os.path.exists(ACTIVE_USERS_FILE):
33 | with open(ACTIVE_USERS_FILE, 'r') as f:
34 | return json.load(f)
35 | return {}
36 | except Exception:
37 | return {}
38 |
39 | async def save_active_users_to_file():
40 | try:
41 | with open(ACTIVE_USERS_FILE, 'w') as f:
42 | json.dump(ACTIVE_USERS, f)
43 | except Exception as e:
44 | print(f"Error saving active users: {e}")
45 |
46 | async def add_active_batch(user_id: int, batch_info: Dict[str, Any]):
47 | ACTIVE_USERS[str(user_id)] = batch_info
48 | await save_active_users_to_file()
49 |
50 | def is_user_active(user_id: int) -> bool:
51 | return str(user_id) in ACTIVE_USERS
52 |
53 | async def update_batch_progress(user_id: int, current: int, success: int):
54 | if str(user_id) in ACTIVE_USERS:
55 | ACTIVE_USERS[str(user_id)]["current"] = current
56 | ACTIVE_USERS[str(user_id)]["success"] = success
57 | await save_active_users_to_file()
58 |
59 | async def request_batch_cancel(user_id: int):
60 | if str(user_id) in ACTIVE_USERS:
61 | ACTIVE_USERS[str(user_id)]["cancel_requested"] = True
62 | await save_active_users_to_file()
63 | return True
64 | return False
65 |
66 | def should_cancel(user_id: int) -> bool:
67 | user_str = str(user_id)
68 | return user_str in ACTIVE_USERS and ACTIVE_USERS[user_str].get("cancel_requested", False)
69 |
70 | async def remove_active_batch(user_id: int):
71 | if str(user_id) in ACTIVE_USERS:
72 | del ACTIVE_USERS[str(user_id)]
73 | await save_active_users_to_file()
74 |
75 | def get_batch_info(user_id: int) -> Optional[Dict[str, Any]]:
76 | return ACTIVE_USERS.get(str(user_id))
77 |
78 | ACTIVE_USERS = load_active_users()
79 |
80 | async def upd_dlg(c):
81 | try:
82 | async for _ in c.get_dialogs(limit=100): pass
83 | return True
84 | except Exception as e:
85 | print(f'Failed to update dialogs: {e}')
86 | return False
87 |
88 | # fixed the old group of 2021-2022 extraction 🌝 (buy krne ka fayda nhi ab old group) ✅
89 | async def get_msg(c, u, i, d, lt):
90 | try:
91 | if lt == 'public':
92 | try:
93 | if str(i).lower().endswith('bot'):
94 | emp[i] = False
95 | xm = await u.get_messages(i, d)
96 | emp[i] = getattr(xm, "empty", False)
97 | if not emp[i]:
98 | emp[i] = True
99 | print(f"Bot chat found successfully...")
100 | return xm
101 |
102 | if emp[i]:
103 | xm = await c.get_messages(i, d)
104 | print(f"fetched by {c.me.username}")
105 | emp[i] = getattr(xm, "empty", False)
106 | if emp[i]:
107 | print(f"Not fetched by {c.me.username}")
108 | try: await u.join_chat(i)
109 | except: pass
110 | xm = await u.get_messages((await u.get_chat(f"@{i}")).id, d)
111 |
112 | return xm
113 | except Exception as e:
114 | print(f'Error fetching public message: {e}')
115 | return None
116 | else:
117 | if u:
118 | try:
119 | async for _ in u.get_dialogs(limit=50): pass
120 |
121 | # Try with -100 prefix first
122 | if str(i).startswith('-100'):
123 | chat_id_100 = i
124 | # For - prefix, remove -100 and add just -
125 | base_id = str(i)[4:] # Remove -100
126 | chat_id_dash = f"-{base_id}"
127 | elif i.isdigit():
128 | chat_id_100 = f"-100{i}"
129 | chat_id_dash = f"-{i}"
130 | else:
131 | chat_id_100 = i
132 | chat_id_dash = i
133 |
134 | # Try -100 format first
135 | try:
136 | result = await u.get_messages(chat_id_100, d)
137 | if result and not getattr(result, "empty", False):
138 | return result
139 | except Exception:
140 | pass
141 |
142 | # Try - format second
143 | try:
144 | result = await u.get_messages(chat_id_dash, d)
145 | if result and not getattr(result, "empty", False):
146 | return result
147 | except Exception:
148 | pass
149 |
150 | # Final fallback - refresh dialogs and try original
151 | try:
152 | async for _ in u.get_dialogs(limit=200): pass
153 | result = await u.get_messages(i, d)
154 | if result and not getattr(result, "empty", False):
155 | return result
156 | except Exception:
157 | pass
158 |
159 | return None
160 |
161 | except Exception as e:
162 | print(f'Private channel error: {e}')
163 | return None
164 | return None
165 | except Exception as e:
166 | print(f'Error fetching message: {e}')
167 | return None
168 |
169 |
170 | async def get_ubot(uid):
171 | bt = await get_user_data_key(uid, "bot_token", None)
172 | if not bt: return None
173 | if uid in UB: return UB.get(uid)
174 | try:
175 | bot = Client(f"user_{uid}", bot_token=bt, api_id=API_ID, api_hash=API_HASH)
176 | await bot.start()
177 | UB[uid] = bot
178 | return bot
179 | except Exception as e:
180 | print(f"Error starting bot for user {uid}: {e}")
181 | return None
182 |
183 | async def get_uclient(uid):
184 | ud = await get_user_data(uid)
185 | ubot = UB.get(uid)
186 | cl = UC.get(uid)
187 | if cl: return cl
188 | if not ud: return ubot if ubot else None
189 | xxx = ud.get('session_string')
190 | if xxx:
191 | try:
192 | ss = dcs(xxx)
193 | gg = Client(f'{uid}_client', api_id=API_ID, api_hash=API_HASH, device_model="v3saver", session_string=ss)
194 | await gg.start()
195 | await upd_dlg(gg)
196 | UC[uid] = gg
197 | return gg
198 | except Exception as e:
199 | print(f'User client error: {e}')
200 | return ubot if ubot else Y
201 | return Y
202 |
203 | async def prog(c, t, C, h, m, st):
204 | global P
205 | p = c / t * 100
206 | interval = 10 if t >= 100 * 1024 * 1024 else 20 if t >= 50 * 1024 * 1024 else 30 if t >= 10 * 1024 * 1024 else 50
207 | step = int(p // interval) * interval
208 | if m not in P or P[m] != step or p >= 100:
209 | P[m] = step
210 | c_mb = c / (1024 * 1024)
211 | t_mb = t / (1024 * 1024)
212 | bar = '🟢' * int(p / 10) + '🔴' * (10 - int(p / 10))
213 | speed = c / (time.time() - st) / (1024 * 1024) if time.time() > st else 0
214 | eta = time.strftime('%M:%S', time.gmtime((t - c) / (speed * 1024 * 1024))) if speed > 0 else '00:00'
215 | await C.edit_message_text(h, m, f"__**Pyro Handler...**__\n\n{bar}\n\n⚡**__Completed__**: {c_mb:.2f} MB / {t_mb:.2f} MB\n📊 **__Done__**: {p:.2f}%\n🚀 **__Speed__**: {speed:.2f} MB/s\n⏳ **__ETA__**: {eta}\n\n**__Powered by Team SPY__**")
216 | if p >= 100: P.pop(m, None)
217 |
218 | async def send_direct(c, m, tcid, ft=None, rtmid=None):
219 | try:
220 | if m.video:
221 | await c.send_video(tcid, m.video.file_id, caption=ft, duration=m.video.duration, width=m.video.width, height=m.video.height, reply_to_message_id=rtmid)
222 | elif m.video_note:
223 | await c.send_video_note(tcid, m.video_note.file_id, reply_to_message_id=rtmid)
224 | elif m.voice:
225 | await c.send_voice(tcid, m.voice.file_id, reply_to_message_id=rtmid)
226 | elif m.sticker:
227 | await c.send_sticker(tcid, m.sticker.file_id, reply_to_message_id=rtmid)
228 | elif m.audio:
229 | await c.send_audio(tcid, m.audio.file_id, caption=ft, duration=m.audio.duration, performer=m.audio.performer, title=m.audio.title, reply_to_message_id=rtmid)
230 | elif m.photo:
231 | photo_id = m.photo.file_id if hasattr(m.photo, 'file_id') else m.photo[-1].file_id
232 | await c.send_photo(tcid, photo_id, caption=ft, reply_to_message_id=rtmid)
233 | elif m.document:
234 | await c.send_document(tcid, m.document.file_id, caption=ft, file_name=m.document.file_name, reply_to_message_id=rtmid)
235 | else:
236 | return False
237 | return True
238 | except Exception as e:
239 | print(f'Direct send error: {e}')
240 | return False
241 |
242 | async def process_msg(c, u, m, d, lt, uid, i):
243 | try:
244 | cfg_chat = await get_user_data_key(d, 'chat_id', None)
245 | tcid = d
246 | rtmid = None
247 | if cfg_chat:
248 | if '/' in cfg_chat:
249 | parts = cfg_chat.split('/', 1)
250 | tcid = int(parts[0])
251 | rtmid = int(parts[1]) if len(parts) > 1 else None
252 | else:
253 | tcid = int(cfg_chat)
254 |
255 | if m.media:
256 | orig_text = m.caption.markdown if m.caption else ''
257 | proc_text = await process_text_with_rules(d, orig_text)
258 | user_cap = await get_user_data_key(d, 'caption', '')
259 | ft = f'{proc_text}\n\n{user_cap}' if proc_text and user_cap else user_cap if user_cap else proc_text
260 |
261 | if lt == 'public' and not emp.get(i, False):
262 | await send_direct(c, m, tcid, ft, rtmid)
263 | return 'Sent directly.'
264 |
265 | st = time.time()
266 | p = await c.send_message(d, 'Downloading...')
267 |
268 | c_name = f"{time.time()}"
269 | if m.video:
270 | file_name = m.video.file_name
271 | if not file_name:
272 | file_name = f"{time.time()}.mp4"
273 | c_name = sanitize(file_name)
274 | elif m.audio:
275 | file_name = m.audio.file_name
276 | if not file_name:
277 | file_name = f"{time.time()}.mp3"
278 | c_name = sanitize(file_name)
279 | elif m.document:
280 | file_name = m.document.file_name
281 | if not file_name:
282 | file_name = f"{time.time()}"
283 | c_name = sanitize(file_name)
284 | elif m.photo:
285 | file_name = f"{time.time()}.jpg"
286 | c_name = sanitize(file_name)
287 |
288 | f = await u.download_media(m, file_name=c_name, progress=prog, progress_args=(c, d, p.id, st))
289 |
290 | if not f:
291 | await c.edit_message_text(d, p.id, 'Failed.')
292 | return 'Failed.'
293 |
294 | await c.edit_message_text(d, p.id, 'Renaming...')
295 | if (
296 | (m.video and m.video.file_name) or
297 | (m.audio and m.audio.file_name) or
298 | (m.document and m.document.file_name)
299 | ):
300 | f = await rename_file(f, d, p)
301 |
302 | fsize = os.path.getsize(f) / (1024 * 1024 * 1024)
303 | th = thumbnail(d)
304 |
305 | if fsize > 2 and Y:
306 | st = time.time()
307 | await c.edit_message_text(d, p.id, 'File is larger than 2GB. Using alternative method...')
308 | await upd_dlg(Y)
309 | mtd = await get_video_metadata(f)
310 | dur, h, w = mtd['duration'], mtd['width'], mtd['height']
311 | th = await screenshot(f, dur, d)
312 |
313 | send_funcs = {'video': Y.send_video, 'video_note': Y.send_video_note,
314 | 'voice': Y.send_voice, 'audio': Y.send_audio,
315 | 'photo': Y.send_photo, 'document': Y.send_document}
316 |
317 | for mtype, func in send_funcs.items():
318 | if f.endswith('.mp4'): mtype = 'video'
319 | if getattr(m, mtype, None):
320 | sent = await func(LOG_GROUP, f, thumb=th if mtype == 'video' else None,
321 | duration=dur if mtype == 'video' else None,
322 | height=h if mtype == 'video' else None,
323 | width=w if mtype == 'video' else None,
324 | caption=ft if m.caption and mtype not in ['video_note', 'voice'] else None,
325 | reply_to_message_id=rtmid, progress=prog, progress_args=(c, d, p.id, st))
326 | break
327 | else:
328 | sent = await Y.send_document(LOG_GROUP, f, thumb=th, caption=ft if m.caption else None,
329 | reply_to_message_id=rtmid, progress=prog, progress_args=(c, d, p.id, st))
330 |
331 | await c.copy_message(d, LOG_GROUP, sent.id)
332 | os.remove(f)
333 | await c.delete_messages(d, p.id)
334 |
335 | return 'Done (Large file).'
336 |
337 | await c.edit_message_text(d, p.id, 'Uploading...')
338 | st = time.time()
339 |
340 | try:
341 | video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp', '.ogv']
342 | audio_extensions = ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.opus', '.aiff', '.ac3']
343 | file_ext = os.path.splitext(f)[1].lower()
344 | if m.video or (m.document and file_ext in video_extensions):
345 | mtd = await get_video_metadata(f)
346 | dur, h, w = mtd['duration'], mtd['width'], mtd['height']
347 | th = await screenshot(f, dur, d)
348 | await c.send_video(tcid, video=f, caption=ft if m.caption else None,
349 | thumb=th, width=w, height=h, duration=dur,
350 | progress=prog, progress_args=(c, d, p.id, st),
351 | reply_to_message_id=rtmid)
352 | elif m.video_note:
353 | await c.send_video_note(tcid, video_note=f, progress=prog,
354 | progress_args=(c, d, p.id, st), reply_to_message_id=rtmid)
355 | elif m.voice:
356 | await c.send_voice(tcid, f, progress=prog, progress_args=(c, d, p.id, st),
357 | reply_to_message_id=rtmid)
358 | elif m.sticker:
359 | await c.send_sticker(tcid, m.sticker.file_id, reply_to_message_id=rtmid)
360 | elif m.audio or (m.document and file_ext in audio_extensions):
361 | await c.send_audio(tcid, audio=f, caption=ft if m.caption else None,
362 | thumb=th, progress=prog, progress_args=(c, d, p.id, st),
363 | reply_to_message_id=rtmid)
364 | elif m.photo:
365 | await c.send_photo(tcid, photo=f, caption=ft if m.caption else None,
366 | progress=prog, progress_args=(c, d, p.id, st),
367 | reply_to_message_id=rtmid)
368 | elif m.document:
369 | await c.send_document(tcid, document=f, caption=ft if m.caption else None,
370 | progress=prog, progress_args=(c, d, p.id, st),
371 | reply_to_message_id=rtmid)
372 | else:
373 | await c.send_document(tcid, document=f, caption=ft if m.caption else None,
374 | progress=prog, progress_args=(c, d, p.id, st),
375 | reply_to_message_id=rtmid)
376 | except Exception as e:
377 | await c.edit_message_text(d, p.id, f'Upload failed: {str(e)[:30]}')
378 | if os.path.exists(f): os.remove(f)
379 | return 'Failed.'
380 |
381 | os.remove(f)
382 | await c.delete_messages(d, p.id)
383 |
384 | return 'Done.'
385 |
386 | elif m.text:
387 | await c.send_message(tcid, text=m.text.markdown, reply_to_message_id=rtmid)
388 | return 'Sent.'
389 | except Exception as e:
390 | return f'Error: {str(e)[:50]}'
391 |
392 | @X.on_message(filters.command(['batch', 'single']))
393 | async def process_cmd(c, m):
394 | uid = m.from_user.id
395 | cmd = m.command[0]
396 |
397 | if FREEMIUM_LIMIT == 0 and not await is_premium_user(uid):
398 | await m.reply_text("This bot does not provide free servies, get subscription from OWNER")
399 | return
400 |
401 | if await sub(c, m) == 1: return
402 | pro = await m.reply_text('Doing some checks hold on...')
403 |
404 | if is_user_active(uid):
405 | await pro.edit('You have an active task. Use /stop to cancel it.')
406 | return
407 |
408 | ubot = await get_ubot(uid)
409 | if not ubot:
410 | await pro.edit('Add your bot with /setbot first')
411 | return
412 |
413 | Z[uid] = {'step': 'start' if cmd == 'batch' else 'start_single'}
414 | await pro.edit(f'Send {"start link..." if cmd == "batch" else "link you to process"}.')
415 |
416 | @X.on_message(filters.command(['cancel', 'stop']))
417 | async def cancel_cmd(c, m):
418 | uid = m.from_user.id
419 | if is_user_active(uid):
420 | if await request_batch_cancel(uid):
421 | await m.reply_text('Cancellation requested. The current batch will stop after the current download completes.')
422 | else:
423 | await m.reply_text('Failed to request cancellation. Please try again.')
424 | else:
425 | await m.reply_text('No active batch process found.')
426 |
427 | @X.on_message(filters.text & filters.private & ~login_in_progress & ~filters.command([
428 | 'start', 'batch', 'cancel', 'login', 'logout', 'stop', 'set',
429 | 'pay', 'redeem', 'gencode', 'single', 'generate', 'keyinfo', 'encrypt', 'decrypt', 'keys', 'setbot', 'rembot']))
430 | async def text_handler(c, m):
431 | uid = m.from_user.id
432 | if uid not in Z: return
433 | s = Z[uid].get('step')
434 | x = await get_ubot(uid)
435 | if not x:
436 | await message.reply("Add your bot /setbot `token`")
437 | return
438 |
439 | if s == 'start':
440 | L = m.text
441 | i, d, lt = E(L)
442 | if not i or not d:
443 | await m.reply_text('Invalid link format.')
444 | Z.pop(uid, None)
445 | return
446 | Z[uid].update({'step': 'count', 'cid': i, 'sid': d, 'lt': lt})
447 | await m.reply_text('How many messages?')
448 |
449 | elif s == 'start_single':
450 | L = m.text
451 | i, d, lt = E(L)
452 | if not i or not d:
453 | await m.reply_text('Invalid link format.')
454 | Z.pop(uid, None)
455 | return
456 |
457 | Z[uid].update({'step': 'process_single', 'cid': i, 'sid': d, 'lt': lt})
458 | i, s, lt = Z[uid]['cid'], Z[uid]['sid'], Z[uid]['lt']
459 | pt = await m.reply_text('Processing...')
460 |
461 | ubot = UB.get(uid)
462 | if not ubot:
463 | await pt.edit('Add bot with /setbot first')
464 | Z.pop(uid, None)
465 | return
466 |
467 | uc = await get_uclient(uid)
468 | if not uc:
469 | await pt.edit('Cannot proceed without user client.')
470 | Z.pop(uid, None)
471 | return
472 |
473 | if is_user_active(uid):
474 | await pt.edit('Active task exists. Use /stop first.')
475 | Z.pop(uid, None)
476 | return
477 |
478 | try:
479 | msg = await get_msg(ubot, uc, i, s, lt)
480 | if msg:
481 | res = await process_msg(ubot, uc, msg, str(m.chat.id), lt, uid, i)
482 | await pt.edit(f'1/1: {res}')
483 | else:
484 | await pt.edit('Message not found')
485 | except Exception as e:
486 | await pt.edit(f'Error: {str(e)[:50]}')
487 | finally:
488 | Z.pop(uid, None)
489 |
490 | elif s == 'count':
491 | if not m.text.isdigit():
492 | await m.reply_text('Enter valid number.')
493 | return
494 |
495 | count = int(m.text)
496 | maxlimit = PREMIUM_LIMIT if await is_premium_user(uid) else FREEMIUM_LIMIT
497 |
498 | if count > maxlimit:
499 | await m.reply_text(f'Maximum limit is {maxlimit}.')
500 | return
501 |
502 | Z[uid].update({'step': 'process', 'did': str(m.chat.id), 'num': count})
503 | i, s, n, lt = Z[uid]['cid'], Z[uid]['sid'], Z[uid]['num'], Z[uid]['lt']
504 | success = 0
505 |
506 | pt = await m.reply_text('Processing batch...')
507 | uc = await get_uclient(uid)
508 | ubot = UB.get(uid)
509 |
510 | if not uc or not ubot:
511 | await pt.edit('Missing client setup')
512 | Z.pop(uid, None)
513 | return
514 |
515 | if is_user_active(uid):
516 | await pt.edit('Active task exists')
517 | Z.pop(uid, None)
518 | return
519 |
520 | await add_active_batch(uid, {
521 | "total": n,
522 | "current": 0,
523 | "success": 0,
524 | "cancel_requested": False,
525 | "progress_message_id": pt.id
526 | })
527 |
528 | try:
529 | for j in range(n):
530 |
531 | if should_cancel(uid):
532 | await pt.edit(f'Cancelled at {j}/{n}. Success: {success}')
533 | break
534 |
535 | await update_batch_progress(uid, j, success)
536 |
537 | mid = int(s) + j
538 |
539 | try:
540 | msg = await get_msg(ubot, uc, i, mid, lt)
541 | if msg:
542 | res = await process_msg(ubot, uc, msg, str(m.chat.id), lt, uid, i)
543 | if 'Done' in res or 'Copied' in res or 'Sent' in res:
544 | success += 1
545 | else:
546 | pass
547 | except Exception as e:
548 | try: await pt.edit(f'{j+1}/{n}: Error - {str(e)[:30]}')
549 | except: pass
550 |
551 | await asyncio.sleep(10)
552 |
553 | if j+1 == n:
554 | await m.reply_text(f'Batch Completed ✅ Success: {success}/{n}')
555 |
556 | finally:
557 | await remove_active_batch(uid)
558 | Z.pop(uid, None)
559 |
560 |
561 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------