telegram_bots/feeds/modules/utils.py

39 lines
1007 B
Python
Raw Normal View History

2019-10-26 23:03:51 +00:00
import os
import subprocess
import tempfile
from io import BytesIO
from uuid import uuid4
import requests
def get_vk_audio(m3u8):
with tempfile.TemporaryDirectory() as d:
fname = '{}.mp3'.format(uuid4())
path = os.path.join(d, fname)
subprocess.check_output(['ffmpeg', '-i', m3u8, path])
with open(path, 'rb') as f:
tf = BytesIO(f.read())
tf.name = fname
tf.seek(0)
return tf
def get_vk_photo(attachment):
for size in (2560, 1280, 807, 604, 130, 75):
if f'photo_{size}' in attachment:
return attachment[f'photo_{size}']
return None
def get_file(url):
fname = '?'.join(url.split('?')[:-1])
extension = os.path.basename(fname).split('.')[-1]
f = tempfile.NamedTemporaryFile(suffix=f'.{extension}' if extension else None)
r = requests.get(url, stream=True)
for chunk in r.iter_content(1024 * 1024):
if chunk:
f.write(chunk)
f.seek(0)
return f