-
-
Notifications
You must be signed in to change notification settings - Fork 528
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
10 changed files
with
176 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
#!/usr/bin/env python3 | ||
# coding: utf-8 | ||
|
||
# ytdlbot - premium.py | ||
# 2023-12-20 17:53 | ||
|
||
import json | ||
import logging | ||
import pathlib | ||
import tempfile | ||
from unittest.mock import MagicMock | ||
|
||
import yt_dlp | ||
from pyrogram import Client, filters, types | ||
|
||
from config import APP_HASH, APP_ID, PYRO_WORKERS, TOKEN | ||
from limit import Payment | ||
from utils import apply_log_formatter | ||
|
||
apply_log_formatter() | ||
app = Client("premium", APP_ID, APP_HASH, workers=PYRO_WORKERS) | ||
|
||
BOT_ID = int(TOKEN.split(":")[0]) | ||
|
||
|
||
@app.on_message(filters.user(BOT_ID) & filters.incoming) | ||
async def hello(client: Client, message: types.Message): | ||
text = message.text | ||
try: | ||
data = json.loads(text) | ||
except json.decoder.JSONDecodeError: | ||
return | ||
url = data["url"] | ||
user_id = data["user_id"] | ||
|
||
tempdir = tempfile.TemporaryDirectory(prefix="ytdl-") | ||
output = pathlib.Path(tempdir.name, "%(title).70s.%(ext)s").as_posix() | ||
ydl_opts = {"restrictfilenames": False, "quiet": True, "outtmpl": output} | ||
formats = [ | ||
# webm , vp9 and av01 are not streamable on telegram, so we'll extract only mp4 | ||
"bestvideo[ext=mp4][vcodec!*=av01][vcodec!*=vp09]+bestaudio[ext=m4a]/bestvideo+bestaudio", | ||
"bestvideo[vcodec^=avc]+bestaudio[acodec^=mp4a]/best[vcodec^=avc]/best", | ||
None, | ||
] | ||
|
||
for f in formats: | ||
ydl_opts["format"] = f | ||
logging.info("Downloading BIG FILE for %s with format %s", url, f) | ||
try: | ||
with yt_dlp.YoutubeDL(ydl_opts) as ydl: | ||
ydl.download([url]) | ||
break | ||
except Exception: | ||
logging.error("Download failed for %s. Try other options...", url) | ||
|
||
payment = Payment() | ||
settings = payment.get_user_settings(user_id) | ||
video_path = next(pathlib.Path(tempdir.name).glob("*")) | ||
if settings[2] == "video" or isinstance(settings[2], MagicMock): | ||
logging.info("Sending as video") | ||
await client.send_video( | ||
BOT_ID, | ||
video_path.as_posix(), | ||
caption="Powered by ytdlbot", | ||
supports_streaming=True, | ||
file_name=f"{user_id}.mp4", | ||
) | ||
elif settings[2] == "audio": | ||
logging.info("Sending as audio") | ||
await client.send_audio( | ||
BOT_ID, | ||
video_path.as_posix(), | ||
caption="Powered by ytdlbot ", | ||
file_name=f"{user_id}.mp3", | ||
) | ||
elif settings[2] == "document": | ||
logging.info("Sending as document") | ||
await client.send_document( | ||
BOT_ID, | ||
video_path.as_posix(), | ||
caption="Powered by ytdlbot", | ||
file_name=f"{user_id}.mp4", | ||
) | ||
else: | ||
logging.error("Send type is not video or audio") | ||
|
||
tempdir.cleanup() | ||
|
||
|
||
if __name__ == "__main__": | ||
app.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,6 +8,7 @@ | |
__author__ = "Benny <[email protected]>" | ||
|
||
import asyncio | ||
import json | ||
import logging | ||
import os | ||
import pathlib | ||
|
@@ -39,18 +40,19 @@ | |
ENABLE_CELERY, | ||
ENABLE_VIP, | ||
OWNER, | ||
PREMIUM_USER, | ||
RATE_LIMIT, | ||
RCLONE_PATH, | ||
TMPFILE_PATH, | ||
WORKERS, | ||
FileTooBig, | ||
) | ||
from constant import BotText | ||
from database import Redis | ||
from downloader import edit_text, tqdm_progress, upload_hook, ytdl_download | ||
from limit import Payment | ||
from utils import ( | ||
apply_log_formatter, | ||
auto_restart, | ||
customize_logger, | ||
get_metadata, | ||
get_revision, | ||
|
@@ -81,7 +83,16 @@ def retrieve_message(chat_id: int, message_id: int) -> types.Message | Any: | |
def ytdl_download_task(chat_id: int, message_id: int, url: str): | ||
logging.info("YouTube celery tasks started for %s", url) | ||
bot_msg = retrieve_message(chat_id, message_id) | ||
ytdl_normal_download(bot, bot_msg, url) | ||
try: | ||
ytdl_normal_download(bot, bot_msg, url) | ||
except FileTooBig as e: | ||
# if you can go there, that means you have premium users set up | ||
logging.warning("Seeking for help from premium user...") | ||
bot_msg.edit_text(f"{e}\n\nPlease wait, I will try to send it as premium user") | ||
data = {"url": url, "user_id": bot_msg.chat.id} | ||
bot.send_message(PREMIUM_USER, json.dumps(data), disable_notification=True, disable_web_page_preview=True) | ||
except Exception: | ||
bot_msg.edit_text(f"Download failed!❌\n\n`{traceback.format_exc()[-2000:]}`", disable_web_page_preview=True) | ||
logging.info("YouTube celery tasks ended.") | ||
|
||
|
||
|
@@ -140,12 +151,19 @@ def ytdl_download_entrance(client: Client, bot_msg: types.Message, url: str, mod | |
redis.update_metrics("cache_miss") | ||
mode = mode or payment.get_user_settings(chat_id)[-1] | ||
if ENABLE_CELERY and mode in [None, "Celery"]: | ||
# in celery mode, producer has lost control of this task. | ||
ytdl_download_task.delay(chat_id, bot_msg.id, url) | ||
else: | ||
ytdl_normal_download(client, bot_msg, url) | ||
except FileTooBig as e: | ||
logging.warning("Seeking for help from premium user...") | ||
bot_msg.edit_text(f"{e}\n\nPlease wait, I will try to send it as premium user") | ||
# this is only for normal node. Celery node will need to do it in celery tasks | ||
data = {"url": url, "user_id": bot_msg.chat.id} | ||
client.send_message(PREMIUM_USER, json.dumps(data), disable_notification=True, disable_web_page_preview=True) | ||
except Exception as e: | ||
logging.error("Failed to download %s, error: %s", url, e) | ||
bot_msg.edit_text(f"Download failed!❌\n\n`{traceback.format_exc()[0:4000]}`", disable_web_page_preview=True) | ||
bot_msg.edit_text(f"Download failed!❌\n\n`{traceback.format_exc()[-2000:]}`", disable_web_page_preview=True) | ||
|
||
|
||
def direct_download_entrance(client: Client, bot_msg: typing.Union[types.Message, typing.Coroutine], url: str): | ||
|
@@ -484,7 +502,7 @@ def run_celery(): | |
threading.Thread(target=run_celery, daemon=True).start() | ||
|
||
scheduler = BackgroundScheduler(timezone="Europe/London") | ||
scheduler.add_job(auto_restart, "interval", seconds=900) | ||
# scheduler.add_job(auto_restart, "interval", seconds=900) | ||
scheduler.start() | ||
|
||
idle() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters