forked from qwertyadrian/TG_AutoPoster
/
poster.py
84 lines (77 loc) · 3.49 KB
/
poster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import sys
import time
from os import remove
from os.path import getsize
from botlogs import log
from settings import config, api_vk, update_parameter
from classes import Post
def get_data(group: str):
"""
Функция получения новых постов с серверов VK. В случае успеха возвращает словарь с постами, а в случае неудачи -
ничего
:param group: ID группы ВК
:return: Возвращает словарь с постами
"""
# noinspection PyBroadException
try:
feed = api_vk.wall.get(domain=group, count=11)
return feed['items']
except Exception:
log.error('Ошибка получения информации о новых постах: {0}'.format(sys.exc_info()[0]))
return None
def updater(bot, domain, last_id):
log.info('[VK] Проверка на наличие новых постов в {0} с последним ID {1}'.format(domain, last_id))
posts = get_data(domain)
for post in reversed(posts):
if post['id'] > last_id:
log.info("[VK] Обнаружен новый пост с ID {0}".format(post['id']))
new_post = Post(post, domain)
new_post.generate_post()
send_post(bot, domain, new_post)
last_id = update_parameter(domain, 'last_id', post['id'])
time.sleep(5)
if post['id'] == last_id:
log.info('[VK] Новых постов больше не обнаружено')
log.info('[VK] Проверка завершена, last_id = {0}.'.format(last_id))
def send_post(bot, domain, post):
log.info("[TG] Отправка поста...")
if post.text:
if post.photos:
pass
else:
bot.sendMessage(chat_id=config.get(domain, 'channel'), text=post.text, parse_mode='HTML',
disable_web_page_preview=True)
if post.photos:
# noinspection PyBroadException
try:
if post.text:
if len(post.photos) == 1 and len(post.text) < 200:
bot.sendPhoto(chat_id=config.get(domain, 'channel'), photo=post.photos[0]['media'],
caption=post.text, parse_mode='HTML')
else:
bot.sendMessage(chat_id=config.get(domain, 'channel'), text=post.text, parse_mode='HTML',
disable_web_page_preview=True)
bot.sendMediaGroup(chat_id=config.get(domain, 'channel'), media=post.photos)
else:
bot.sendMediaGroup(chat_id=config.get(domain, 'channel'), media=post.photos)
except Exception:
log.warning('[TG] Невозможно отправить фото: {0}.'.format(sys.exc_info()[1]))
for m in post.videos:
try:
bot.sendVideo(chat_id=config.get(domain, 'channel'), video=open(m, 'rb'), timeout=60)
except Exception:
pass
for m in post.docs:
bot.sendDocument(chat_id=config.get(domain, 'channel'), document=open(m, 'rb'), timeout=60)
for (m, n) in post.tracks:
try:
if getsize(m) > 52428800:
remove(m)
else:
try:
bot.sendAudio(chat_id=config.get(domain, 'channel'), audio=open(m, 'rb'), duration=int(n), timeout=60)
except:
pass
remove(m)
except FileNotFoundError:
continue