telegram_bots/feeds/modules/utils.py

31 lines
757 B
Python
Raw Normal View History

2019-10-26 23:03:51 +00:00
import os
2019-10-26 23:18:55 +00:00
import re
2019-10-26 23:03:51 +00:00
import tempfile
import requests
2019-10-26 23:18:55 +00:00
def get_vk_audio(url):
if 'm3u8' in url:
2019-11-08 15:56:15 +00:00
url = re.sub(r'/[0-9a-f]+(/audios)?/([0-9a-f]+)/index.m3u8', r'\1/\2.mp3', url)
2019-10-26 23:18:55 +00:00
return get_file(url)
2019-10-26 23:03:51 +00:00
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