delojza/robot.py

137 lines
4.1 KiB
Python
Raw Normal View History

2018-01-31 12:32:25 +01:00
#!/usr/bin/env python3
2018-01-30 13:47:33 +01:00
import logging
import os
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
import requests
import youtube_dl
from telegram import MessageEntity
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("kunsax")
DIR = os.path.dirname(os.path.realpath(__file__))
2018-01-31 14:11:42 +01:00
TMP_DIR = '/tmp'
2018-01-30 13:47:33 +01:00
OUT_DIR = DIR + '/out'
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-01-31 13:28:54 +01:00
def datestr(date):
return date.strftime("%Y-%m-%d@%H%M")
2018-01-30 13:47:33 +01:00
2018-01-31 13:28:54 +01:00
def download_ydl(urls, date):
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-01-31 14:11:42 +01:00
'outtmpl': TMP_DIR + '/' + datestr(date) + '__%(title)s__%(id)s.%(ext)s'
2018-01-30 13:47:33 +01:00
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(urls)
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:
logger.info("Moving %s to %s..." % (globbed, OUT_DIR))
shutil.move(globbed, OUT_DIR)
2018-01-30 13:47:33 +01:00
2018-01-31 13:28:54 +01:00
def download_raw(url, date):
2018-01-31 14:26:51 +01:00
if 'api.telegram.org' in url \
and ('animation' in url or 'video' in url) \
and "mp4" not in url:
ext = '.mp4'
2018-01-31 14:26:51 +01:00
else:
ext = ''
2018-01-31 13:28:54 +01:00
local_filename = OUT_DIR + '/' + datestr(date) + '__' + url.split('/')[-1] + ext
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 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,
map(lambda e: update.message.text[e.offset:e.offset + e.length],
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)
update.message.reply_text('Downloading now...')
2018-01-31 13:28:54 +01:00
download_ydl(ytdl_urls, 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))
# 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
if file is not None:
try:
2018-01-31 12:40:42 +01:00
url = bot.getFile(file).file_path
update.message.reply_text('Downloading now...')
logger.info("Downloading '%s'" % url)
2018-01-31 13:28:54 +01:00
download_raw(url, 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-01-31 12:30:08 +01:00
dp.add_handler(MessageHandler(Filters.photo | Filters.video | Filters.audio | 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()