import simplematrixbotlib as botlib from re import search from urllib.parse import quote as sanitize_url import yt_dlp from config import config class Logger(object): def debug(self, msg): pass def warning(self, msg): pass def error(self, msg): print(msg) def progress_hook(d): if d['status'] == 'started': print('Started downloading') elif d['status'] == 'finished': print('Done downloading') def get_yt_vid_id(word): if search('www.youtube.com/watch', word): return word elif search('youtu.be', word): return word.replace('https://youtu.be/', 'https://www.youtube.com/watch?v=') else: return False creds = botlib.Creds(config['url'], config['username'], config['password']) bot = botlib.Bot(creds) ydl_opts = { 'format': config['yt_dlp_format'], 'outtmpl': config['download_dir'] + '/%(title)s.%(ext)s', 'restrictfilenames': True, 'logger': Logger(), 'progress_hooks': [progress_hook], } @bot.listener.on_message_event async def youtube(room, message): match = botlib.MessageMatch(room, message, bot) pieces = str(message).split() try: for i in pieces: yt_url = get_yt_vid_id(i) if yt_url: with yt_dlp.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(yt_url, download=False) fname = sanitize_url(yt_dlp.utils.sanitize_filename(info_dict.get('title', None), restricted=True)) url = 'https://trygve.me/video_bot/' + fname + '.webm' ydl.download([yt_url]) await bot.api.send_text_message(room.room_id, url) except Exception as e: await bot.api.send_text_message(room.room_id, str(e)) bot.run()