Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import yt_dlp
|
| 4 |
+
from telegram import Update
|
| 5 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
| 6 |
+
|
| 7 |
+
# Enable logging
|
| 8 |
+
logging.basicConfig(
|
| 9 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
|
| 10 |
+
)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
# Bot token from environment variable
|
| 14 |
+
TOKEN = "7449252023:AAGl88ZXaJD6Gu1M49zmnZNUvddsgIZZ0C0"
|
| 15 |
+
if not TOKEN:
|
| 16 |
+
raise ValueError("No TELEGRAM_BOT_TOKEN found in environment variables")
|
| 17 |
+
|
| 18 |
+
bot_username = "ethioytdownloaderbot"
|
| 19 |
+
|
| 20 |
+
async def start(update: Update, context: CallbackContext) -> None:
|
| 21 |
+
await update.message.reply_text('Send me a YouTube link or a list of links separated by spaces, and I will download the videos for you!')
|
| 22 |
+
|
| 23 |
+
def progress_hook(d, status_message, context):
|
| 24 |
+
if d['status'] == 'downloading':
|
| 25 |
+
total_bytes = d.get('total_bytes', 0)
|
| 26 |
+
downloaded_bytes = d.get('downloaded_bytes', 0)
|
| 27 |
+
percentage = (downloaded_bytes / total_bytes) * 100 if total_bytes > 0 else 0
|
| 28 |
+
message = f"Downloading video... {percentage:.2f}%"
|
| 29 |
+
context.bot.edit_message_text(chat_id=status_message.chat_id, message_id=status_message.message_id, text=message)
|
| 30 |
+
|
| 31 |
+
async def download_youtube_video(update: Update, context: CallbackContext) -> None:
|
| 32 |
+
urls = update.message.text.split()
|
| 33 |
+
valid_urls = [url for url in urls if "youtube.com" in url or "youtu.be" in url]
|
| 34 |
+
|
| 35 |
+
if not valid_urls:
|
| 36 |
+
await update.message.reply_text('Please send valid YouTube links.')
|
| 37 |
+
return
|
| 38 |
+
|
| 39 |
+
status_message = await context.bot.send_message(chat_id=update.effective_chat.id, text="Processing your request...")
|
| 40 |
+
|
| 41 |
+
for url in valid_urls:
|
| 42 |
+
try:
|
| 43 |
+
ydl_opts = {
|
| 44 |
+
'format': 'best', # Download the best available format without merging
|
| 45 |
+
'progress_hooks': [lambda d: progress_hook(d, status_message, context)],
|
| 46 |
+
'outtmpl': 'downloads/%(title)s.%(ext)s',
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Ensure 'downloads' directory exists
|
| 50 |
+
os.makedirs('downloads', exist_ok=True)
|
| 51 |
+
|
| 52 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 53 |
+
info_dict = ydl.extract_info(url, download=True)
|
| 54 |
+
file_path = ydl.prepare_filename(info_dict)
|
| 55 |
+
thumbnail_url = info_dict.get('thumbnail', '')
|
| 56 |
+
description = info_dict.get('description', 'No description available')
|
| 57 |
+
title = info_dict.get('title', 'Unknown Title')
|
| 58 |
+
artist = info_dict.get('uploader', 'Unknown Artist')
|
| 59 |
+
|
| 60 |
+
file_size = os.path.getsize(file_path)
|
| 61 |
+
file_size_mb = file_size / (1024 * 1024)
|
| 62 |
+
await context.bot.edit_message_text(chat_id=update.effective_chat.id, message_id=status_message.message_id, text=f"Sending the video... (Size: {file_size_mb:.2f} MB)")
|
| 63 |
+
|
| 64 |
+
caption = f"Downloaded by @{bot_username}\nTitle: {title}\nArtist: {artist}\n\nDescription: {description}"
|
| 65 |
+
if len(caption) > 1024:
|
| 66 |
+
caption = caption[:1020] + "..."
|
| 67 |
+
|
| 68 |
+
await context.bot.send_video(
|
| 69 |
+
chat_id=update.effective_chat.id,
|
| 70 |
+
video=open(file_path, 'rb'),
|
| 71 |
+
caption=caption,
|
| 72 |
+
reply_to_message_id=update.message.message_id
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Send the thumbnail if it exists
|
| 76 |
+
if thumbnail_url:
|
| 77 |
+
await context.bot.send_photo(
|
| 78 |
+
chat_id=update.effective_chat.id,
|
| 79 |
+
photo=thumbnail_url,
|
| 80 |
+
caption=f"Thumbnail for {title}"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
os.remove(file_path) # Delete the file after sending
|
| 84 |
+
|
| 85 |
+
except Exception as e:
|
| 86 |
+
logger.error(f"Error: {e}")
|
| 87 |
+
await context.bot.edit_message_text(chat_id=update.effective_chat.id, message_id=status_message.message_id, text=f'Failed to download the YouTube video: {url}. Please make sure the link is correct.')
|
| 88 |
+
|
| 89 |
+
await context.bot.delete_message(chat_id=update.effective_chat.id, message_id=status_message.message_id)
|
| 90 |
+
|
| 91 |
+
async def error_handler(update: Update, context: CallbackContext) -> None:
|
| 92 |
+
logger.error(msg="Exception while handling an update:", exc_info=context.error)
|
| 93 |
+
if update and update.message:
|
| 94 |
+
await update.message.reply_text('An error occurred. Please try again later.')
|
| 95 |
+
|
| 96 |
+
def main() -> None:
|
| 97 |
+
# Create the Application and pass it your bot's token
|
| 98 |
+
application = Application.builder().token(TOKEN).build()
|
| 99 |
+
|
| 100 |
+
# Add handlers
|
| 101 |
+
application.add_handler(CommandHandler("start", start))
|
| 102 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, download_youtube_video))
|
| 103 |
+
application.add_error_handler(error_handler)
|
| 104 |
+
|
| 105 |
+
# Start polling
|
| 106 |
+
application.run_polling()
|
| 107 |
+
|
| 108 |
+
if __name__ == '__main__':
|
| 109 |
+
main()
|