video_bot/main.py

60 lines
1.8 KiB
Python
Raw Permalink Normal View History

2021-06-13 14:07:49 +00:00
import simplematrixbotlib as botlib
from re import search
2022-07-31 19:38:51 +00:00
from urllib.parse import quote as sanitize_url
import yt_dlp
2021-06-13 14:07:49 +00:00
2022-07-31 19:38:51 +00:00
from config import config
2021-06-13 14:07:49 +00:00
2022-07-31 22:01:37 +00:00
class Logger(object):
2021-06-13 14:07:49 +00:00
def debug(self, msg):
pass
def warning(self, msg):
pass
def error(self, msg):
print(msg)
2022-07-31 19:38:51 +00:00
def progress_hook(d):
if d['status'] == 'started':
print('Started downloading')
elif d['status'] == 'finished':
print('Done downloading')
2021-06-13 14:07:49 +00:00
2022-07-31 19:38:51 +00:00
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=')
2021-06-13 14:07:49 +00:00
else:
return False
2022-07-31 22:01:37 +00:00
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],
}
2022-07-31 19:38:51 +00:00
@bot.listener.on_message_event
2021-06-13 14:07:49 +00:00
async def youtube(room, message):
match = botlib.MessageMatch(room, message, bot)
pieces = str(message).split()
2021-06-15 14:28:05 +00:00
try:
2022-07-31 19:38:51 +00:00
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)
2021-06-15 14:28:05 +00:00
except Exception as e:
2022-07-31 19:38:51 +00:00
await bot.api.send_text_message(room.room_id, str(e))
2021-06-13 14:07:49 +00:00
bot.run()