telegram_bots/feeds/modules/vk_feed.py

64 lines
2.6 KiB
Python
Raw Normal View History

2019-01-25 16:33:22 +00:00
import os
import tempfile
2019-02-08 14:04:37 +00:00
from io import BytesIO
2019-01-25 16:33:22 +00:00
import requests
import sentry_sdk
from django.db import models
from djconfig import config
2019-02-08 14:04:37 +00:00
from python_anticaptcha import AnticaptchaClient, ImageToTextTask
2019-01-25 16:33:22 +00:00
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
2019-10-26 23:03:51 +00:00
from feeds.modules.utils import get_vk_photo, get_vk_audio
2019-02-08 14:04:37 +00:00
from feeds.utils import DatabaseConfig, captcha_handler
2019-01-25 16:33:22 +00:00
class VKFeedModuleConfig(FeedModuleConfig):
owner_id = models.IntegerField()
send_text = models.BooleanField(default=True)
send_links = models.BooleanField(default=True)
MODULE_NAME = 'VK feed'
def execute(self, bot: TeleBot, chat_id, last_id):
config._reload_maybe()
2019-01-25 16:40:47 +00:00
if last_id is None:
last_id = 0
2019-01-25 16:33:22 +00:00
vk_session = VkApi(login=config.vk_username, password=config.vk_password, config=DatabaseConfig,
2019-02-08 14:04:37 +00:00
api_version='5.60', captcha_handler=captcha_handler)
2019-01-25 16:33:22 +00:00
vk_session.auth()
vk_audio = VkAudio(vk_session)
vk = vk_session.get_api()
wall_data = vk.wall.get(owner_id=self.owner_id)
for post in reversed(wall_data['items']):
if post['id'] > last_id:
try:
if self.send_text and post['text']:
bot.send_message(chat_id, post['text'])
if 'attachments' in post:
photos = []
for image in filter(lambda a: 'photo' in a, post['attachments']):
url = get_vk_photo(image['photo'])
if url:
photos.append(url.replace('\\', ''))
if len(photos) == 1:
bot.send_photo(chat_id, photos[0])
elif len(photos) > 1:
bot.send_media_group(chat_id, [InputMediaPhoto(photo) for photo in photos])
for a in post['attachments']:
if 'audio' in a:
2019-10-26 23:03:51 +00:00
f = get_vk_audio(vk_audio.get_audio_by_id(a['audio']['owner_id'], a['audio']['id']))
2019-01-26 08:33:32 +00:00
bot.send_audio(chat_id, f, None, a['audio'].get('artist'), a['audio'].get('title'))
2019-01-25 16:33:22 +00:00
if self.send_links:
bot.send_message(chat_id, f"https://vk.com/wall{post['owner_id']}_{post['id']}",
disable_web_page_preview=True)
except Exception as e:
sentry_sdk.capture_exception(e)
2019-02-04 09:15:53 +00:00
yield post['id']