import telebot
import os
import pytube
import yt_dlp

bot = telebot.TeleBot('5358652365:AAGpc3Lt5j8v8rY7vzbtwllZczgxBrZVivk')

#directorio donde guardar la descarga
path = "/var/www/html/TelegramBots/pytube/"
pathLinks = "/var/www/html/msdos/episodios/pruebas/"
pathFile = "https://msdos.club/episodios/pruebas/"

def main():
        bot.polling()

@bot.message_handler(commands=['musica'])
def musica(message):
    texto = message.text
    chat = message.chat.id
    l = len(texto)
    url = texto[8:l]
    print(url)
    #URL del video de Youtube
    try:
        yt = pytube.YouTube(url)
        imagen = yt.thumbnail_url
        #stream = yt.streams.filter(only_audio=True).desc().first()
        stream = yt.streams.filter(mime_type='audio/mp4',only_audio=True).desc().first()
        print(stream.default_filename)
        nombre = stream.default_filename
        nombre = nombre.replace(" ", "")
        nombre = nombre.replace("(", "-")
        nombre = nombre.replace(")", "-")
        nombre = ''.join(char for char in nombre if char.isalnum())
        nombre = nombre.replace("mp4", ".mp3")
        print(nombre)
        #Descargamos el audio seleccionado en el directorio escogido
        #TODO falta comprobar si hay alguna opcion de descarga
        stream.download(output_path=path,filename=nombre)
        #enviar imagen del audio (portada, es el thumbnail del video);
        bot.send_photo(chat_id=chat,photo=imagen)
        #enviar audio:
        #bot.send_audio(chat_id=chat, audio=open(path+nombre, 'rb'))
        bot.send_document(chat_id=chat , document=open(path+nombre,'rb'))
        #borrar archivo de musica (solo pasa si se envia sin error)
        operation = 'rm '+path+nombre
        os.system(operation)
        print(operation)
    except pytube.exceptions.RegexMatchError:
        bot.send_message(chat,'URL de vídeo no existe')
        print("URL no encontrada")
    except BaseException as err:
        #print(f"Unexpected {err=}, {type(err)=}")
        bot.send_message(chat,'Se ha producido un error')
    except Exception as e:
        #print(f"Unexpected {e=}, {type(e)=}")
        bot.send_message(chat,'Se ha producido un error')


@bot.message_handler(commands=['yt'])
def yt(message):
    try:
        texto = message.text
        chat = message.chat.id
        l = len(texto)
        url = texto[4:l]
        print(url)

        ydl_opts = {
            'outtmpl': 'pytube/%(title)s.%(ext)s',
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'm4a',
            }]
        }

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(url, download=False)
            nombre = ydl.prepare_filename(info_dict)
            error_code = ydl.download(url)

            print(nombre)
            bot.send_document(chat_id=chat , document=open(path+nombre,'rb'))
            #borrar archivo de musica (solo pasa si se envia sin error)
            #operation = 'rm '+path+nombre
            #print(operation) 
            #os.system(operation)
            #print(operation)

    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
        bot.send_message(chat,'Se ha producido un error')


@bot.message_handler(commands=['m'])
def m(message):
    texto = message.text
    chat = message.chat.id
    l = len(texto)
    url = texto[11:l]
    print(url)
    #URL del video de Youtube
    try:
        yt = pytube.YouTube(url)
        imagen = yt.thumbnail_url
        print("image")
        #Filtramos las descargas por audio solamente, orden descendiente de calidad y el primero que será el que tiene la calidad más alta
        #stream = yt.streams.filter(only_audio=True).desc().first()
        #stream = yt.streams.filter(mime_type='audio/mp4',only_audio=True).desc().first()
        stream = yt.streams.filter(file_extension='mp4').first()
        print(stream.default_filename)
        nombre = stream.default_filename
        nombre = nombre.replace(" ", "")
        nombre = nombre.replace("(", "-")
        nombre = nombre.replace(")", "-")
        nombre = ''.join(char for char in nombre if char.isalnum())
        nombre = nombre.replace("mp4", ".mp4")
        print(nombre)
        #Descargamos el audio seleccionado en el directorio escogido
        #TODO falta comprobar si hay alguna opcion de descarga
        stream.download(output_path=path,filename=nombre)
        #enviar imagen del audio (portada, es el thumbnail del video);
        bot.send_photo(chat_id=chat,photo=imagen)
        #enviar audio:
        #bot.send_audio(chat_id=chat, audio=open(path+nombre, 'rb'))
        bot.send_document(chat_id=chat , document=open(path+nombre,'rb'))
        #borrar archivo de musica (solo pasa si se envia sin error)
        operation = 'rm '+path+nombre
        os.system(operation)
        print(operation)
    except pytube.exceptions.RegexMatchError:
        bot.send_message(chat,'URL de vídeo no existe')
        print("URL no encontrada")
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
        bot.send_message(chat,'Se ha producido un error')

@bot.message_handler(commands=['ragnarok'])
def ragnarok(message):
    texto = message.text
    chat = message.chat.id

    try:
        #borrar pathLinks
        operation = 'rm '+pathLinks+"*.*"
        os.system(operation)
        print(operation)
    except Exception as err:
        #print(f"Unexpected {err=}, {type(err)=}")
        bot.send_message(chat,'Error al borrar.')

@bot.message_handler(commands=['l'])
def l(message):
    texto = message.text
    chat = message.chat.id
    l = len(texto)
    url = texto[8:l]
    print(url)
    #URL del video de Youtube
    try:
        yt = pytube.YouTube(url)
        imagen = yt.thumbnail_url
        #Filtramos las descargas por audio solamente, orden descendiente de calidad y el primero que será el que tiene la calidad más alta
        #stream = yt.streams.filter(only_audio=True).desc().first()
        stream = yt.streams.filter(mime_type='audio/mp4',only_audio=True).desc().first()
        print(stream.default_filename)
        nombre = stream.default_filename
        nombre = nombre.replace(" ", "")
        nombre = nombre.replace("(", "-")
        nombre = nombre.replace(")", "-")
        nombre = ''.join(char for char in nombre if char.isalnum())
        nombre = nombre.replace("mp4", ".mp4")
        print(nombre)
        #Descargamos el audio seleccionado en el directorio escogido
        #TODO falta comprobar si hay alguna opcion de descarga
        stream.download(output_path=pathLinks,filename=nombre)
        #enviar imagen del audio (portada, es el thumbnail del video);
        bot.send_photo(chat_id=chat,photo=imagen)
        #enviar audio:
        #bot.send_audio(chat_id=chat, audio=open(path+nombre, 'rb'))
        bot.send_message(chat, pathFile+nombre)
    except pytube.exceptions.RegexMatchError:
        bot.send_message(chat,'URL de vídeo no existe')
        print("URL no encontrada")
    except Exception as err:
        #print(f"Unexpected {err=}, {type(err)=}")
        bot.send_message(chat,'Se ha producido un error')

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        main()
