1
0
mirror of https://gitlab.com/MisterBiggs/telegram-video-download-bot.git synced 2025-06-15 14:46:41 +00:00

59 lines
1.7 KiB
Python

import io
import os
import re
import requests as r
import youtube_dl
from requests_toolbelt.downloadutils import stream
import telegram
from telegram import Update
from telegram.ext import (
CallbackContext,
CommandHandler,
Filters,
MessageHandler,
Updater,
)
URL_REGEX = r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\+.~#?&\/\/=]*)"
def start(update: Update, context: CallbackContext):
update.message.reply(
"This bot downloads the video from any link sent to it. @MisterBiggs for more help."
)
def url_search(update: Update, context: CallbackContext) -> None:
msg = update.message.text.strip()
print(msg)
if re.fullmatch(URL_REGEX, msg):
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
vid = ydl.extract_info(msg)
context.bot.send_chat_action(
chat_id=update.message.chat_id, action=telegram.ChatAction.UPLOAD_VIDEO
)
print(vid.keys())
b = io.BytesIO()
resp = r.get(vid["url"], stream=True)
file = stream.stream_response_to_file(resp, path=b)
b.seek(0)
try:
update.message.reply_video(b, caption=vid["title"])
except Exception:
update.message.reply_video(b)
updater = Updater(os.environ["TELEGRAM"])
updater.dispatcher.add_handler(CommandHandler("start", start))
updater.dispatcher.add_handler(CommandHandler("help", start))
updater.dispatcher.add_handler(CommandHandler("dl", url_search))
updater.dispatcher.add_handler(MessageHandler(Filters.text, url_search))
updater.start_polling()
print("bot running")
updater.idle()