From 6d51e3e5c1a4fc71314ae0abb1899a041768fbf4 Mon Sep 17 00:00:00 2001 From: BennyThink Date: Sun, 29 Aug 2021 10:02:11 +0800 Subject: [PATCH] VIP mode controlled by env var --- config.py | 34 ++++++++++++++++++++++++++++++++++ constant.py | 24 +++++++++++++----------- downloader.py | 16 ++++++++++------ limit.py | 23 ++++++++++------------- ytdl.py | 50 ++++++++++++++++++++++++++++++-------------------- 5 files changed, 97 insertions(+), 50 deletions(-) create mode 100644 config.py diff --git a/config.py b/config.py new file mode 100644 index 0000000..8d9b06b --- /dev/null +++ b/config.py @@ -0,0 +1,34 @@ +#!/usr/local/bin/python3 +# coding: utf-8 + +# ytdlbot - config.py +# 8/28/21 15:01 +# + +__author__ = "Benny " + +import os + +QUOTA = 5 * 1024 * 1024 * 1024 # 5G +if os.uname().sysname == "Darwin": + QUOTA = 10 * 1024 * 1024 # 10M + +EX = 24 * 3600 +MULTIPLY = 5 # VIP1 is 5*5-25G, VIP2 is 50G +USD2CNY = 6 # $5 --> ¥30 + +ENABLE_VIP = False +AFD_LINK = os.getenv("AFD_LINK", "https://afdian.net/@BennyThink") +COFFEE_LINK = os.getenv("COFFEE_LINK", "https://www.buymeacoffee.com/bennythink") +COFFEE_TOKEN = os.getenv("COFFEE_TOKEN") +AFD_TOKEN = os.getenv("AFD_TOKEN") +AFD_USER_ID = os.getenv("AFD_USER_ID") + +OWNER = os.getenv("OWNER", "BennyThink") + +APP_ID: "int" = int(os.getenv("APP_ID", 111)) +APP_HASH = os.getenv("APP_HASH", "111") +TOKEN = os.getenv("TOKEN", "3703WLI") +REDIS = os.getenv("REDIS", "redis") + +WORKERS: "int" = int(os.getenv("WORKERS", 100)) diff --git a/constant.py b/constant.py index 967ef49..a7a9823 100644 --- a/constant.py +++ b/constant.py @@ -9,28 +9,26 @@ __author__ = "Benny " import time +from config import AFD_LINK, COFFEE_LINK, ENABLE_VIP, EX, MULTIPLY, USD2CNY from downloader import sizeof_fmt -from limit import EX, MULTIPLY, QUOTA, USD2CNY, VIP +from limit import QUOTA, VIP class BotText: start = "Welcome to YouTube Download bot. Type /help for more information." help = f""" -I'm sorry guys, the bot is consuming too many network traffic, so I addressed more strict limit. -If you have any troubles, you can talk to me and I'll see if I can ease the limitations for you. - 1. This bot should works at all times. If it stops responding, please wait a few minutes or let me know on Telegram or GitHub. 2. At this time of writing, this bot consumes hundreds of GigaBytes of network traffic per day. In order to avoid being abused, -every one can use this bot within {sizeof_fmt(QUOTA)} of quota for every {int(EX / 3600)} hours. +every one can use this bot within **{sizeof_fmt(QUOTA)} of quota for every {int(EX / 3600)} hours.** 3. You can optionally choose to become 'VIP' user if you need more traffic. Type /vip for more information. -4. Sourcecode for this bot will always stay open, here-> https://github.com/tgbot-collection/ytdlbot - """ +4. Source code for this bot will always stay open, here-> https://github.com/tgbot-collection/ytdlbot + """ if ENABLE_VIP else "Help text" about = "YouTube-DL by @BennyThink. Open source on GitHub: https://github.com/tgbot-collection/ytdlbot" @@ -47,7 +45,7 @@ For example, if you download a video of 1GB, your current quota will be 9GB inst 5. It's a open source project, you can always deploy your own bot. 6. For VIPs, please refer to /vip command - """ + """ if ENABLE_VIP else "Please contact the actual owner of this bot" vip = f""" **Terms:** @@ -63,17 +61,19 @@ For example, if you download a video of 1GB, your current quota will be 9GB inst Note: If you pay $9, you'll become VIP1 instead of VIP2. **Payment method:** -1. (afdian) Mainland China: https://afdian.net/@BennyThink -2. (buy me a coffee) Other countries or regions: https://www.buymeacoffee.com/bennythink +1. (afdian) Mainland China: {AFD_LINK} +2. (buy me a coffee) Other countries or regions: {COFFEE_LINK} __I live in a place where I don't have access to Telegram Payments. So...__ **After payment:** 1. afdian: with your order number `/vip 123456` 2. buy me a coffee: with your email `/vip someone@else.com` - """ + """ if ENABLE_VIP else "VIP is not enabled." vip_pay = "Processing your payments...If it's not responding after one minute, please contact @BennyThink." def remaining_quota_caption(self, chat_id): + if not ENABLE_VIP: + return "" used, total, ttl = self.return_remaining_quota(chat_id) refresh_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ttl + time.time())) caption = f"Remaining quota: **{sizeof_fmt(used)}/{sizeof_fmt(total)}**, " \ @@ -87,6 +87,8 @@ __I live in a place where I don't have access to Telegram Payments. So...__ @staticmethod def get_vip_greeting(chat_id): + if not ENABLE_VIP: + return "" v = VIP().check_vip(chat_id) if v: return f"Hello {v[1]}, VIP{v[-2]}☺️\n\n" diff --git a/downloader.py b/downloader.py index ec75062..c7d37cb 100644 --- a/downloader.py +++ b/downloader.py @@ -12,13 +12,13 @@ import os import pathlib import subprocess import time -import traceback import fakeredis import filetype import youtube_dl from youtube_dl import DownloadError +from config import ENABLE_VIP from limit import VIP, Redis r = fakeredis.FakeStrictRedis() @@ -54,9 +54,10 @@ def download_hook(d: dict, bot_msg): percent = d.get("_percent_str", "N/A") speed = d.get("_speed_str", "N/A") - result, err_msg = check_quota(total, bot_msg.chat.id) - if result is False: - raise ValueError(err_msg) + if ENABLE_VIP: + result, err_msg = check_quota(total, bot_msg.chat.id) + if result is False: + raise ValueError(err_msg) text = f'[{filesize}]: Downloading {percent} - {downloaded}/{total} @ {speed}' edit_text(bot_msg, text) @@ -143,10 +144,13 @@ def ytdl_download(url, tempdir, bm) -> dict: return response for i in os.listdir(tempdir): - remain, _, ttl = VIP().check_remaining_quota(chat_id) p: "str" = os.path.join(tempdir, i) file_size = os.stat(p).st_size - result, err_msg = check_quota(file_size, chat_id) + if ENABLE_VIP: + remain, _, ttl = VIP().check_remaining_quota(chat_id) + result, err_msg = check_quota(file_size, chat_id) + else: + result, err_msg = True, "" if result is False: response["status"] = False response["error"] = err_msg diff --git a/limit.py b/limit.py index 7647a60..bcd78c7 100644 --- a/limit.py +++ b/limit.py @@ -22,19 +22,14 @@ import redis import requests from beautifultable import BeautifulTable -QUOTA = 5 * 1024 * 1024 * 1024 # 5G -if os.uname().sysname == "Darwin": - QUOTA = 10 * 1024 * 1024 # 10M - -EX = 24 * 3600 -MULTIPLY = 5 # VIP1 is 5*10-50G, VIP2 is 100G -USD2CNY = 6 # $5 --> ¥30 +from config import (AFD_TOKEN, AFD_USER_ID, COFFEE_TOKEN, ENABLE_VIP, EX, + MULTIPLY, OWNER, QUOTA, REDIS, USD2CNY) class Redis: def __init__(self): super(Redis, self).__init__() - self.r = redis.StrictRedis(host=os.getenv("REDIS", "redis"), db=4, decode_responses=True) + self.r = redis.StrictRedis(host=REDIS, db=4, decode_responses=True) db_banner = "=" * 20 + "DB data" + "=" * 20 quota_banner = "=" * 20 + "Quota" + "=" * 20 @@ -221,7 +216,7 @@ class VIP(Redis, SQLite): class BuyMeACoffee: def __init__(self): - self._token = os.getenv("COFFEE_TOKEN") + self._token = COFFEE_TOKEN self._url = "https://developers.buymeacoffee.com/api/v1/supporters" self._data = [] @@ -250,8 +245,8 @@ class BuyMeACoffee: class Afdian: def __init__(self): - self._token = os.getenv("AFD_TOKEN") - self._user_id = os.getenv("AFD_USER_ID") + self._token = AFD_TOKEN + self._user_id = AFD_USER_ID self._url = "https://afdian.net/api/open/query-order" def _generate_signature(self): @@ -288,6 +283,8 @@ class Afdian: def verify_payment(user_id, unique) -> "str": + if not ENABLE_VIP: + return "VIP is not enabled." logging.info("Verifying payment for %s - %s", user_id, unique) if "@" in unique: pay = BuyMeACoffee() @@ -297,10 +294,10 @@ def verify_payment(user_id, unique) -> "str": level, amount, pay_id = pay.get_user_payment(unique) if amount == 0: return f"You pay amount is {amount}. Did you input wrong order ID or email? " \ - f"Talk to @BennyThink if you need any assistant." + f"Talk to @{OWNER} if you need any assistant." if not level: return f"You pay amount {amount} is below minimum ${MULTIPLY}. " \ - f"Talk to @BennyThink if you need any assistant." + f"Talk to @{OWNER} if you need any assistant." else: vip = VIP() ud = { diff --git a/ytdl.py b/ytdl.py index c04b9ad..457cf1d 100644 --- a/ytdl.py +++ b/ytdl.py @@ -20,9 +20,28 @@ from pyrogram import Client, filters, types from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from tgbot_ping import get_runtime +from config import APP_HASH, APP_ID, ENABLE_VIP, OWNER, TOKEN, WORKERS from constant import BotText from downloader import convert_flac, sizeof_fmt, upload_hook, ytdl_download -from limit import VIP, Redis, verify_payment +from limit import Redis, verify_payment + + +def customize_logger(logger: "list"): + logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(filename)s [%(levelname)s]: %(message)s') + for log in logger: + logging.getLogger(log).setLevel(level=logging.WARNING) + + +def create_app(session="ytdl", workers=WORKERS): + _app = Client(session, APP_ID, APP_HASH, + bot_token=TOKEN, workers=workers) + + return _app + + +customize_logger(["pyrogram.client", "pyrogram.session.session", "pyrogram.client", "pyrogram.connection.connection"]) +app = create_app() +bot_text = BotText() def get_metadata(video_path): @@ -38,24 +57,6 @@ def get_metadata(video_path): return dict(height=height, width=width, duration=duration) -logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(filename)s [%(levelname)s]: %(message)s') - - -def create_app(session="ytdl", workers=100): - api_id = int(os.getenv("APP_ID", 0)) - api_hash = os.getenv("APP_HASH") - token = os.getenv("TOKEN") - - _app = Client(session, api_id, api_hash, - bot_token=token, workers=workers) - - return _app - - -app = create_app() -bot_text = BotText() - - @app.on_message(filters.command(["start"])) def start_handler(client: "Client", message: "types.Message"): chat_id = message.chat.id @@ -80,7 +81,7 @@ def ping_handler(client: "Client", message: "types.Message"): bot_info = "test" else: bot_info = get_runtime("botsrunner_ytdl_1", "YouTube-dl") - if chat_id == 260260121: + if message.chat.username == OWNER: client.send_document(chat_id, Redis().generate_file(), caption=bot_info) else: client.send_message(chat_id, f"{bot_info}") @@ -206,4 +207,13 @@ if __name__ == '__main__': scheduler = BackgroundScheduler() scheduler.add_job(Redis().reset_today, 'cron', hour=0, minute=0) scheduler.start() + banner = f""" +▌ ▌ ▀▛▘ ▌ ▛▀▖ ▜ ▌ +▝▞ ▞▀▖ ▌ ▌ ▌ ▌ ▌ ▛▀▖ ▞▀▖ ▌ ▌ ▞▀▖ ▌ ▌ ▛▀▖ ▐ ▞▀▖ ▝▀▖ ▞▀▌ + ▌ ▌ ▌ ▌ ▌ ▌ ▌ ▌ ▌ ▌ ▛▀ ▌ ▌ ▌ ▌ ▐▐▐ ▌ ▌ ▐ ▌ ▌ ▞▀▌ ▌ ▌ + ▘ ▝▀ ▝▀▘ ▘ ▝▀▘ ▀▀ ▝▀▘ ▀▀ ▝▀ ▘▘ ▘ ▘ ▘ ▝▀ ▝▀▘ ▝▀▘ + +By @BennyThink, VIP mode: {ENABLE_VIP} + """ + print(banner) app.run()