├── .gitignore ├── README.md ├── bot.py ├── modules ├── checker.py ├── myqueues.py └── ytdownloader.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | /vids 163 | .mp4 164 | /telegram-bot-api 165 | 166 | 167 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #
YouTube Downloader Bot
2 |A Telegram Bot to Download YouTube Videos upto 4K under 2GB.
3 |(Only for Educational Purposes)
4 | 5 | # 6 | ## Features 7 | - ✅ Fast Downloads 8 | - ✅ Choose video quality before download. 9 | - ✅ Downloading Queue for users. 10 | - ✅ Max video upload size : 2GB 11 | - ✅ Save server side resources. 12 | - ✅ No Developer side limits. 13 | 14 | ## How to Deploy 15 | ### 1. Setup Environment Variables 16 | - Get your [BOT_API_KEY](https://core.telegram.org/bots/tutorial#obtain-your-bot-token) from here. 17 | - Create .env file 18 | - Paste this code into your file and replace with your own values. 19 | ``` 20 | BOT_API_KEY = "9999999999:AAHePL8-xSzjOlnF5dRGiwhNyxxZsS3u7f4" # Replace with your own token 21 | ``` 22 | - Save it! 23 | 24 | # 25 | ### 2. Install Dependencies 26 | ``` 27 | git clone https://github.com/hansanaD/TelegramYTDLBot.git; 28 | cd TelegramYTDLBot; 29 | pip install -r requirements.txt; 30 | ``` 31 | # 32 | ### 3. Run api server locally (optional) 33 | You can choose not to use this service.\ 34 | But then you won't be able to **upload files up to 2000 MB** and get these [features](https://core.telegram.org/bots/api#using-a-local-bot-api-server). 35 | 36 | - Generate your instructions from [here](https://tdlib.github.io/telegram-bot-api/build.html). _(This step might take upto 20 mins.)_ 37 | - Go to: 38 | - ``` 39 | cd telegram-bot-api/bin 40 | ``` 41 | - Get API ID & HASH from [here](https://core.telegram.org/api/obtaining_api_id). (Watch this [Tutorial](https://www.youtube.com/watch?v=8naENmP3rg4) to get help.) 42 | - Start the server. (Remember to replace the values with your own values): 43 | - ``` 44 | ./telegram-bot-api --api-id=XXXXX --api-hash=XXXXXXXXXXXX --http-port=8081 --local 45 | ``` 46 | 47 | Read the instructions on [eternnoir/pyTelegramBotAPI](https://github.com/eternnoir/pyTelegramBotAPI/#using-local-bot-api-sever) and [tdlib/telegram-bot-api](https://github.com/tdlib/telegram-bot-api) for more information. 48 | # 49 | ### 4. Run your bot 50 | - open a new "[screen](https://www.geeksforgeeks.org/screen-command-in-linux-with-examples/)" or tab on your terminal. 51 | - run: ```python bot.py``` 52 | 53 | **both script & api server should run at the same time order to work.** 54 | # 55 | 56 | ## Disclaimer 57 | This repository is intended for educational and personal use only. The use of this repository for any commercial or illegal purposes is strictly prohibited. The repository owner does not endorse or encourage the downloading or sharing of copyrighted material without permission. The repository owner is not responsible for any misuse of the software or any legal consequences that may arise from such misuse 58 | 59 | - **APIs : [y2mate-api](https://github.com/Simatwa/y2mate-api/) , [pytelegramBotAPI](https://github.com/eternnoir/pyTelegramBotAPI/)** 60 | - **Contact for issues : [@dev00111](https://t.me/dev00111)** 61 | # 62 | _Sorry for my bad english and my messy documentation. 😶_ 63 | 64 | 65 | -------------------------------------------------------------------------------- /bot.py: -------------------------------------------------------------------------------- 1 | import os 2 | import telebot 3 | import threading 4 | 5 | from modules import checker, myqueues 6 | 7 | from dotenv import load_dotenv 8 | load_dotenv() 9 | 10 | TOKEN = os.getenv("BOT_API_KEY") 11 | 12 | bot = telebot.TeleBot(TOKEN, parse_mode="HTML") 13 | 14 | @bot.message_handler(commands=['start']) 15 | def send_welcome(message): 16 | bot.reply_to( 17 | message, "Hello, I'm a Simple Youtube Downloader!👋\n\nTo get started, just type the /help command.") 18 | 19 | @bot.message_handler(commands=['help']) 20 | def send_help(message): 21 | bot.reply_to( 22 | message, 23 | """ 24 | Just send your youtube link and select the video quality. 😉 25 | 26 | Developer: @dev00111 27 | Source: TelegramYTDLBot 28 | """, disable_web_page_preview=True,) 29 | 30 | 31 | 32 | @bot.message_handler(func=lambda m: True) 33 | def link_check(message): 34 | checker.linkCheck(bot=bot, message=message) 35 | # print(checker.videoURL) 36 | 37 | # Callback handler for # getVidInfo() 38 | @bot.callback_query_handler(func=lambda call: [call.data == item for item in checker.showList]) 39 | def callback_query(call): 40 | 41 | data = call.data.split("#") 42 | receivedData = data[0] 43 | videoURL = data[1] 44 | # print(receivedData) 45 | 46 | bot.answer_callback_query(call.id, f"Selected {receivedData} to download.") 47 | bot.delete_message(chat_id=call.message.chat.id, message_id=call.message.message_id) 48 | 49 | myqueues.download_queue.put((call.message, videoURL, receivedData)) 50 | queue_position = myqueues.download_queue.qsize() 51 | 52 | 53 | if queue_position == 0 & 1: 54 | bot.send_message(call.message.chat.id, f"Download has been added to the queue.") 55 | else: 56 | bot.send_message(call.message.chat.id, f"Download has been added to the queue at #{queue_position}.") 57 | 58 | 59 | # downloader.download(bot=bot, message=call.message, userInput=receivedData, videoURL=checker.videoURL) 60 | # bot.send_message(call.message.chat.id, f"{videoURL} \n{receivedData} : Download Triggered!") 61 | 62 | # message, videoURL, receivedData 63 | 64 | download_thread = threading.Thread(target=myqueues.download_worker, args=(bot, myqueues.download_queue)) 65 | download_thread.daemon = True 66 | download_thread.start() 67 | 68 | print("TelegramYTDLBot is running..\n") 69 | bot.infinity_polling() 70 | -------------------------------------------------------------------------------- /modules/checker.py: -------------------------------------------------------------------------------- 1 | from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton 2 | import re 3 | from y2mate_api import Handler 4 | 5 | 6 | def linkCheck(bot, message): 7 | 8 | linkFilter = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') 9 | userLinks = re.findall(linkFilter, message.text) 10 | 11 | yt_link = [] 12 | for link in userLinks: 13 | if 'youtube.com' in link or 'youtu.be' in link: 14 | yt_link.append(link) 15 | 16 | if yt_link: 17 | # bot.reply_to(message, "YouTube links found.") 18 | 19 | # global videoURL 20 | # global ytApi 21 | 22 | videoURL = yt_link[0] 23 | 24 | 25 | qualityChecker(bot=bot, message=message, videoURL=videoURL) 26 | 27 | else: 28 | bot.reply_to(message, "No YouTube links found!") 29 | 30 | 31 | def qualityChecker(bot, message, videoURL): 32 | 33 | qualityCheckerMsg = bot.reply_to(message, "Looking for Available Qualities..🔎") 34 | 35 | ytApi = Handler(videoURL) 36 | 37 | q_list = ['4k', '1080p', '720p', '480p', '360p', '240p'] 38 | # q_list.reverse() 39 | 40 | urlList = [] 41 | 42 | def getVidInfo(r): 43 | for video_metadata in ytApi.run(quality=r): 44 | 45 | q = video_metadata.get("q") 46 | dlink = video_metadata.get("dlink") 47 | size = video_metadata.get("size") 48 | 49 | if dlink == None: 50 | pass 51 | else: 52 | urlList.append([q, size, dlink]) 53 | # print(r, " fetched") 54 | 55 | # Iterate over q_list to check if res quality exist on that video 56 | for r in q_list: 57 | getVidInfo(r) 58 | 59 | # print(urlList) 60 | 61 | # Create a new list to show 62 | global showList 63 | showList = {} 64 | for count, item in enumerate(urlList, 1): 65 | del item[2] # Remove dlink from list 66 | q = item[0] 67 | # print(i) 68 | size = item[1] 69 | showList.update( { count: { "q":q, "size": size }} ) 70 | 71 | # print(showList) 72 | 73 | 74 | # Add Inline Buttons to get user input 75 | 76 | def gen_markup(): 77 | markup = InlineKeyboardMarkup() 78 | for value in showList.values(): 79 | callbackData = f"{ value["q"] }#{ videoURL }" 80 | button = InlineKeyboardButton(text=f"{value['q']} ({value['size']})", callback_data=callbackData) 81 | markup.add(button) 82 | return markup 83 | 84 | 85 | bot.delete_message(qualityCheckerMsg.chat.id, qualityCheckerMsg.message_id) 86 | 87 | bot.reply_to(message=message, text="Choose a stream:", reply_markup=gen_markup()) 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /modules/myqueues.py: -------------------------------------------------------------------------------- 1 | import time 2 | from queue import Queue 3 | from modules.ytdownloader import download 4 | 5 | download_queue = Queue() 6 | 7 | def download_worker(bot, download_queue): 8 | while True: 9 | message, videoURL, receivedData = download_queue.get() 10 | try: 11 | download(bot=bot, message=message, userInput=receivedData, videoURL=videoURL) 12 | 13 | except Exception as e: 14 | print(f"Error downloading file: {e}") 15 | download_queue.task_done() 16 | 17 | # Check if the queue is empty 18 | if download_queue.empty(): 19 | print("All downloads have been completed. Queue is empty now.\n\n") 20 | 21 | 22 | -------------------------------------------------------------------------------- /modules/ytdownloader.py: -------------------------------------------------------------------------------- 1 | import os 2 | from y2mate_api import Handler 3 | import requests 4 | import pytube 5 | 6 | # Download the YouTube Video 7 | def download(bot, message, userInput, videoURL): 8 | 9 | api = Handler(videoURL) 10 | yt = pytube.YouTube(videoURL) 11 | 12 | mediaPath = f"{os.getcwd()}/vids" 13 | 14 | # Download the video using user's input 15 | for video_metadata in api.run(quality=userInput): 16 | # print(video_metadata) 17 | 18 | if not os.path.exists(mediaPath): 19 | os.makedirs(mediaPath) 20 | 21 | downloadMsg = bot.send_message(chat_id=message.chat.id, text="Downloading...📥") 22 | 23 | vidFileName = f"{ video_metadata['vid'] }_{ video_metadata['q'] }.{ video_metadata['ftype'] }" 24 | 25 | try: 26 | # Start Downloading the Video 27 | api.save(third_dict=video_metadata, dir="vids", naming_format=vidFileName, progress_bar=True) 28 | except Exception as e: 29 | bot.reply_to(message, f"Error downloading video: {e}") 30 | 31 | bot.edit_message_text(chat_id=downloadMsg.chat.id, message_id=downloadMsg.message_id, text="Uploading...📤") 32 | 33 | # Upload the video to Telegram 34 | try: 35 | print(vidFileName, "Uploading..") 36 | bot.send_video( 37 | message.chat.id, 38 | open(f"vids/{vidFileName}", 'rb'), 39 | thumb=requests.get(yt.thumbnail_url).content, 40 | width=1920, 41 | height=1080, 42 | # caption= f" Thanks for Using @{bot.get_me().username }. ", 43 | caption=f""" 44 | Title: { yt.title } 45 | URL: { videoURL } 46 | Quality: { video_metadata['q'] } 47 | 48 | Thanks for Using @YoutubeDownloader4K0_bot.""", 49 | ) 50 | 51 | print("File was uploaded/sent to the User.") 52 | 53 | except Exception as e: 54 | bot.reply_to(message, f"Error uploading video: {e}") 55 | print(vidFileName, f": Error uploading video: {e}") 56 | 57 | bot.delete_message(downloadMsg.chat.id, downloadMsg.message_id) 58 | 59 | # Delete the Media files after download. 60 | os.remove(f"{mediaPath}/{vidFileName}") 61 | print(vidFileName, ": Done!") 62 | print("-------------------------------") 63 | 64 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.9.3 2 | aiosignal==1.3.1 3 | amqp==5.2.0 4 | annotated-types==0.6.0 5 | anyio==4.2.0 6 | appdirs==1.4.4 7 | async-timeout==4.0.3 8 | attrs==23.2.0 9 | beautifulsoup4==4.12.3 10 | billiard==4.2.0 11 | Brotli==1.1.0 12 | cachetools==5.3.2 13 | celery==5.3.6 14 | certifi==2023.11.17 15 | cffi==1.16.0 16 | charset-normalizer==3.3.2 17 | click==8.1.3 18 | click-didyoumean==0.3.1 19 | click-plugins==1.1.1 20 | click-repl==0.3.0 21 | colorama==0.4.6 22 | decorator==4.4.2 23 | decouple==0.0.7 24 | docopt==0.6.2 25 | emoji==2.10.0 26 | ffmpeg-progress-yield==0.7.8 27 | ffmpeg-python==0.2.0 28 | ffpb==0.4.1 29 | frozenlist==1.4.1 30 | future==0.18.3 31 | google-api-core==2.17.1 32 | google-api-python-client==2.123.0 33 | google-auth==2.28.0 34 | google-auth-httplib2==0.2.0 35 | googleapis-common-protos==1.62.0 36 | h11==0.14.0 37 | httpcore==1.0.2 38 | httplib2==0.22.0 39 | httpx==0.26.0 40 | idna==3.6 41 | imageio==2.33.1 42 | imageio-ffmpeg==0.4.9 43 | kombu==5.3.7 44 | markdown-it-py==3.0.0 45 | mdurl==0.1.2 46 | moviepy==1.0.3 47 | multidict==6.0.5 48 | mutagen==1.47.0 49 | numpy==1.26.4 50 | outcome==1.3.0.post0 51 | pillow==10.2.0 52 | pipreqs==0.4.13 53 | proglog==0.1.10 54 | prompt-toolkit==3.0.43 55 | protobuf==4.25.3 56 | pyasn1==0.5.1 57 | pyasn1-modules==0.3.0 58 | pycparser==2.22 59 | pycryptodomex==3.20.0 60 | pydantic==2.6.0 61 | pydantic_core==2.16.1 62 | pyee==11.1.0 63 | Pygments==2.17.2 64 | pygramtic==0.2.0 65 | pyparsing==3.1.1 66 | PySocks==1.7.1 67 | pyTelegramBotAPI==4.15.4 68 | python-dateutil==2.9.0.post0 69 | python-dotenv==1.0.1 70 | python-ffmpeg==2.0.10 71 | python-telegram-bot==20.8 72 | python-telegram-bot-api==0.0.7 73 | pytube==15.0.0 74 | redis==5.0.2 75 | requests==2.28.2 76 | rich==13.7.0 77 | rq==1.16.1 78 | rsa==4.9 79 | selenium==4.19.0 80 | setuptools==70.0.0 81 | six==1.16.0 82 | sniffio==1.3.0 83 | sortedcontainers==2.4.0 84 | soupsieve==2.5 85 | tabulate==0.9.0 86 | tqdm==4.65.0 87 | trio==0.25.0 88 | trio-websocket==0.11.1 89 | typing_extensions==4.9.0 90 | tzdata==2024.1 91 | uritemplate==4.1.1 92 | urllib3==1.26.18 93 | vine==5.1.0 94 | wcwidth==0.2.13 95 | websockets==12.0 96 | wsproto==1.2.0 97 | y2mate==1.0.0 98 | y2mate-api==1.0.4 99 | yarg==0.1.9 100 | yarl==1.9.4 101 | --------------------------------------------------------------------------------