API Version rollback. Added 2 more audio fallbacks

This commit is contained in:
Kylmakalle 2019-02-20 20:21:57 +03:00
parent 324e2f0ae3
commit b6122ae172
4 changed files with 76 additions and 7 deletions

3
bot.py
View File

@ -75,8 +75,7 @@ async def get_max_photo(obj, keyword='photo'):
async def get_content(url, docname='tgvkbot.document', chrome_headers=True, rewrite_name=False,
custom_ext=''):
try:
with aiohttp.ClientSession(headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'} if chrome_headers else {}) as session:
with aiohttp.ClientSession(headers=CHROME_HEADERS if chrome_headers else {}) as session:
r = await session.request('GET', url)
direct_url = str(r.url)
tempdir = tempfile.gettempdir()

View File

@ -34,17 +34,21 @@ AUDIO_URL = os.environ.get('AUDIO_URL', 'http://thatmusic.akentev.com/id/{owner_
AUDIO_ACCESS_URL = os.environ.get('AUDIO_ACCESS_URL',
'http://thatmusic.akentev.com/access_id/{token}/{owner_id}/{audio_id}')
TOKEN_REFRESH_URL = os.environ.get('TOKEN_REFRESH_URL', 'http://thatmusic.akentev.com/refresh')
AUDIO_SEARCH_URL = os.environ.get('AUDIO_SEARCH_URL', 'https://thatmusic.akentev.com/search/')
AUDIO_PROXY_URL = os.environ.get('AUDIO_PROXY_URL', 'https://thatmusic.akentev.com/proxy/')
AUDIO_HEADERS = {
'user-agent': 'KateMobileAndroid/52.1 lite-445 (Android 4.4.2; SDK 19; x86; unknown Android SDK built for x86; en)'}
CHROME_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}
BOT_TOKEN = os.environ.get('BOT_TOKEN')
SETTINGS_VAR = os.environ.get('SETTINGS_VAR', 'DJANGO_TGVKBOT_SETTINGS_MODULE')
MAX_FILE_SIZE = os.environ.get('MAX_FILE_SIZE', 52428800)
API_VERSION = os.environ.get('API_VERSION', '5.78')
API_VERSION = os.environ.get('API_VERSION', '5.71')
AUDIO_API_VERSION = os.environ.get('API_VERSION', '5.78')
# https://www.miniwebtool.com/django-secret-key-generator/
# Возможно достаточно заглушки в стиле 'tgvkbot-super-secret-key(nope)'

View File

@ -530,7 +530,7 @@ async def send_welcome(msg: types.Message):
if not existing_vkuser:
link = 'https://oauth.vk.com/authorize?client_id={}&' \
'display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends,messages,offline,docs,photos,video,stories,audio' \
'&response_type=token&v={}'.format(VK_APP_ID, API_VERSION)
'&response_type=token&v={}'.format(VK_APP_ID, AUDIO_API_VERSION)
mark = InlineKeyboardMarkup()
login = InlineKeyboardButton('ВХОД', url=link)
mark.add(login)

View File

@ -4,6 +4,7 @@ from aiovk.longpoll import LongPoll
from bot import *
from aiogram.utils.markdown import quote_html, hlink
import urllib
log = logging.getLogger('vk_messages')
inline_link_re = re.compile('\[([a-zA-Z0-9_]*)\|(.*?)\]', re.MULTILINE)
@ -706,7 +707,11 @@ async def process_message(msg, token=None, is_multichat=None, vk_chat_id=None, u
elif attachment['type'] == 'audio':
await bot.send_chat_action(to_tg_chat, ChatActions.UPLOAD_DOCUMENT)
tg_message = await tgsend(bot.send_audio, to_tg_chat, audio=attachment['content'],
reply_to_message_id=main_message, disable_notification=disable_notify)
caption=attachment.get('caption', None),
performer=attachment.get('artist', None),
title=attachment.get('title', None),
reply_to_message_id=main_message, disable_notification=disable_notify,
parse_mode='HTML')
Message.objects.create(
vk_chat=vk_chat_id,
vk_id=vk_msg_id,
@ -762,6 +767,19 @@ async def check_vk_url(url):
return False
def form_audio_title(data: dict, delimer=' '):
result = data.get('artist')
if result:
if 'title' in data:
result += delimer + data['title']
else:
if 'title' in data:
result = data['title']
else:
return
return result
async def process_attachment(attachment, token=None):
atype = attachment.get('type')
if atype == 'photo':
@ -769,6 +787,22 @@ async def process_attachment(attachment, token=None):
return {'content': photo_url, 'type': 'photo'}
elif atype == 'audio':
if attachment[atype].get('url') and AUDIO_PROXY_URL:
try:
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_PROXY_URL,
params={'url': urllib.parse.quote(attachment[atype]['url']),
'artist': urllib.parse.quote(attachment[atype].get('artist', '')),
'title': urllib.parse.quote(attachment[atype].get('title', ''))},
headers=CHROME_HEADERS)
if r.status != 200:
raise Exception
audio = await r.read()
audio = io.BytesIO(audio)
return {'content': audio, 'type': 'audio'}
except:
pass
if AUDIO_ACCESS_URL:
if token:
try:
@ -783,7 +817,7 @@ async def process_attachment(attachment, token=None):
return {'content': audio, 'type': 'audio'}
except:
pass
elif AUDIO_URL:
if AUDIO_URL:
try:
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_URL.format(owner_id=attachment[atype]['owner_id'],
@ -795,6 +829,38 @@ async def process_attachment(attachment, token=None):
return {'content': audio, 'type': 'audio'}
except:
pass
if AUDIO_SEARCH_URL:
try:
search = form_audio_title(attachment[atype])
if not search:
raise Exception
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_SEARCH_URL, params={'q': urllib.parse.quote(search)})
if r.status != 200:
raise Exception
audios = await r.json()
if audios['success'] and audios['data']:
if attachment[atype]['duration']:
audio = min(audios['data'],
key=lambda x: abs(x['duration'] - attachment[atype]['duration']))
else:
audio = audios['data'][0]
else:
raise Exception
with aiohttp.ClientSession() as session:
r = await session.request('GET', audio["download"])
if r.status != 200:
raise Exception
audio = await r.read()
audio = io.BytesIO(audio)
# search = form_audio_title(attachment[atype], ' - ')
# caption = '<i>🔍 {}</i>'.format(quote_html(search))
caption = '🔍'
return {'content': audio, 'type': 'audio', 'caption': caption,
'artist': attachment[atype].get('artist', None),
'title': attachment[atype].get('title', None)}
except:
pass
return {'content': '<i>Аудио</i>', 'type': 'text'}