telegram_bots/feeds/modules/vk_music.py

70 lines
2.0 KiB
Python
Raw Normal View History

2019-01-26 06:36:56 +00:00
import os
import tempfile
import requests
import sentry_sdk
from django.db import models
from djconfig import config
from telebot import TeleBot
from telebot.types import InputMediaPhoto
from vk_api import VkApi
from vk_api.audio import VkAudio
from feeds.models import FeedModuleConfig
from feeds.utils import DatabaseConfig
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, session=None):
if session is None:
session = requests
fname = '?'.join(url.split('?')[:-1])
extension = os.path.basename(fname).split('.')[-1]
f = tempfile.NamedTemporaryFile(suffix=f'.{extension}' if extension else None)
r = session.get(url, stream=True)
for chunk in r.iter_content(1024 * 1024):
if chunk:
f.write(chunk)
f.seek(0)
return f
class VKMusicFeedModuleConfig(FeedModuleConfig):
owner_id = models.IntegerField()
MODULE_NAME = 'VK music'
def execute(self, bot: TeleBot, chat_id, last_id):
config._reload_maybe()
if last_id is None:
last_id = 0
vk_session = VkApi(login=config.vk_username, password=config.vk_password, config=DatabaseConfig,
api_version='5.60')
if config.russian_proxy_string:
vk_session.http.proxies = {
'http': config.russian_proxy_string,
'https': config.russian_proxy_string,
}
vk_session.auth()
vk_audio = VkAudio(vk_session)
lst = []
for audio in vk_audio.get_iter(self.owner_id):
if audio['id'] > last_id:
lst = [audio] + lst
else:
break
2019-01-26 07:35:46 +00:00
for track in lst:
2019-01-26 06:36:56 +00:00
f = get_file(track['url'], vk_session.http)
bot.send_audio(chat_id, f, duration=track['duration'], performer=track['artist'],
title=track['title'])
2019-02-04 09:15:53 +00:00
yield track['id']