delojza/robot.py

187 lines
5.9 KiB
Python
Raw Normal View History

2018-01-31 12:32:25 +01:00
#!/usr/bin/env python3
2018-02-02 15:28:49 +01:00
import errno
2018-01-30 13:47:33 +01:00
import logging
import os
2018-01-31 14:34:59 +01:00
import re
2018-01-31 14:11:42 +01:00
import shutil
2018-01-31 12:30:08 +01:00
import sys
2018-01-31 14:23:01 +01:00
from glob import glob
2018-01-30 13:47:33 +01:00
2018-01-31 14:34:59 +01:00
import filetype
2018-01-30 13:47:33 +01:00
import requests
import youtube_dl
from telegram import MessageEntity
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
DIR = os.path.dirname(os.path.realpath(__file__))
TMP_DIR = '/var/tmp'
2018-01-30 13:47:33 +01:00
OUT_DIR = DIR + '/out'
2018-01-31 15:58:56 +01:00
logging.basicConfig(level=logging.INFO,
2018-01-31 14:56:29 +01:00
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("kunsax")
2018-01-30 13:47:33 +01:00
2018-02-02 15:28:49 +01:00
def datestr(date):
return date.strftime("%Y-%m-%d@%H%M")
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
2018-01-30 13:47:33 +01:00
def ytdl_has(url):
ies = youtube_dl.extractor.gen_extractors()
for ie in ies:
if ie.suitable(url) and ie.IE_NAME != 'generic' \
and '/channel/' not in url:
# Site has dedicated extractor
return True
return False
2018-02-02 16:03:25 +01:00
def download_ydl(urls, subdir, date, extract=False):
2018-01-30 13:47:33 +01:00
ydl_opts = {
'noplaylist': True,
2018-01-31 14:23:01 +01:00
'restrictfilenames': True,
2018-01-30 13:47:33 +01:00
'download_archive': DIR + '/downloaded.lst',
2018-02-02 15:28:49 +01:00
'outtmpl': f'{TMP_DIR}/' + datestr(date) + '__%(title)s__%(id)s.%(ext)s'
2018-01-30 13:47:33 +01:00
}
2018-02-02 16:03:25 +01:00
if extract:
ydl_opts['format'] = 'bestaudio'
2018-02-04 23:38:07 +01:00
# ydl_opts['postprocessors'] = [{
# 'key': 'FFmpegExtractAudio',
# 'preferredcodec': 'wav'
# }]
2018-01-30 13:47:33 +01:00
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(urls)
2018-02-02 15:28:49 +01:00
out_dir = f'{OUT_DIR}/{subdir}/'
2018-01-31 14:11:42 +01:00
for filename in map(ydl.prepare_filename, map(ydl.extract_info, urls)):
2018-01-31 14:23:01 +01:00
globbeds = glob(os.path.splitext(filename)[0] + '.*')
for globbed in globbeds:
2018-02-02 15:28:49 +01:00
logger.info("Moving %s to %s..." % (globbed, out_dir))
shutil.move(globbed, out_dir)
2018-01-30 13:47:33 +01:00
2018-02-02 15:28:49 +01:00
def download_raw(url, subdir, date):
local_filename = f"{OUT_DIR}/{subdir}/" + "%s__%s" % (datestr(date), url.split('/')[-1])
# local_filename = OUT_DIR + '/' + ("%s/" % subdir) if subdir else '' + datestr(date) + '__' + url.split('/')[-1]
2018-01-30 13:47:33 +01:00
r = requests.get(url, stream=True)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
2018-01-31 14:34:59 +01:00
if not re.match(r'.*\..{3,5}$', os.path.split(local_filename)[-1]):
kind = filetype.guess(local_filename)
if kind is None:
logger.error("File has no extension and could not be determined!")
else:
logger.info('Moving file without extension... %s?' % kind.extension)
shutil.move(local_filename, local_filename + '.' + kind.extension)
2018-01-30 13:47:33 +01:00
2018-02-02 15:28:49 +01:00
def get_first_hashtag(message):
hashtags = list(filter(lambda e: e.type == 'hashtag', message.entities))
if len(hashtags) == 0:
return None
hashtag = message.parse_entity(hashtags[0])
return hashtag[1:].upper()
2018-01-31 12:30:08 +01:00
# noinspection PyBroadException
2018-01-30 13:47:33 +01:00
def handle_url(bot, update):
ytdl_urls = list(filter(ytdl_has,
2018-02-02 15:28:49 +01:00
map(lambda e: update.message.parse_entity(e),
filter(lambda e: e.type == 'url',
update.message.entities))))
if len(ytdl_urls) > 0:
2018-01-31 12:30:08 +01:00
try:
2018-01-31 12:40:42 +01:00
logger.info("Downloading %s" % ytdl_urls)
2018-02-02 15:28:49 +01:00
hashtag = get_first_hashtag(update.message)
2018-02-02 16:03:25 +01:00
reply = 'Downloading'
2018-02-02 15:28:49 +01:00
if hashtag:
mkdir_p(f'{OUT_DIR}/{hashtag}')
2018-02-02 16:03:25 +01:00
reply += f' to "{hashtag}"'
reply += '...'
if hashtag == 'AUDIO':
reply += ' (And also guessing you want to extract the audio)'
update.message.reply_text(reply)
download_ydl(ytdl_urls, hashtag or '.', update.message.date, extract=hashtag == 'AUDIO')
2018-01-31 12:30:08 +01:00
except:
type, value, _ = sys.exc_info()
update.message.reply_text("Something is FUCKED: %s, %s" % (type, value))
# noinspection PyBroadException
def handle_rest(bot, update):
file = None
2018-01-31 13:42:16 +01:00
if len(update.message.photo) > 0:
2018-01-31 12:30:08 +01:00
photo = max(update.message.photo, key=lambda p: p.width)
file = photo.file_id
elif update.message.document is not None:
file = update.message.document.file_id
elif update.message.audio is not None:
file = update.message.audio.file_id
elif update.message.video is not None:
file = update.message.video.file_id
2018-02-03 15:44:01 +01:00
elif update.message.voice is not None:
file = update.message.voice.file_id
2018-01-31 12:30:08 +01:00
if file is not None:
try:
2018-01-31 12:40:42 +01:00
url = bot.getFile(file).file_path
2018-02-02 15:28:49 +01:00
logger.info("Downloading %s" % url)
hashtag = get_first_hashtag(update.message)
2018-02-03 19:14:34 +01:00
reply = 'Downloading'
if hashtag:
mkdir_p(f'{OUT_DIR}/{hashtag}')
reply += f' to "{hashtag}"'
reply += '...'
update.message.reply_text(reply)
2018-02-02 15:28:49 +01:00
if hashtag:
mkdir_p(f'{OUT_DIR}/{hashtag}')
download_raw(url, hashtag or '.', update.message.date)
2018-01-31 12:30:08 +01:00
except:
type, value, _ = sys.exc_info()
update.message.reply_text("Something is FUCKED: %s, %s" % (type, value))
2018-01-30 13:47:33 +01:00
def start(bot, update):
update.message.reply_text('WOOP WOOP')
def error(bot, update, error):
logger.error(error)
2018-01-30 15:18:17 +01:00
if update is not None:
update.message.reply_text("Something is fucked: %s" % error)
2018-01-30 13:47:33 +01:00
def main():
updater = Updater("***REMOVED***")
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_error_handler(error)
dp.add_handler(MessageHandler(Filters.entity(MessageEntity.URL), handle_url))
2018-02-03 15:44:01 +01:00
dp.add_handler(MessageHandler(Filters.photo | Filters.video | Filters.audio | Filters.voice | Filters.document, handle_rest))
2018-01-30 13:47:33 +01:00
updater.start_polling()
logger.info("Started Telegram bot...")
updater.idle()
if __name__ == '__main__':
main()