-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
95 lines (85 loc) · 3.92 KB
/
main.py
File metadata and controls
95 lines (85 loc) · 3.92 KB
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
85
86
87
88
89
90
91
92
93
94
95
# -*- coding: utf-8 -*-
import time
import eventlet
import requests
import logging
import telebot
from time import sleep
# Каждый раз получаем по 10 последних записей со стены
URL_VK = 'https://api.vk.com/method/wall.get?domain=animalsinthestudio&count=10&filter=owner&access_token=6438650f571370826acc94d001ecf8b4a75142f9fe3463fece9de8cc4c954fb864e7e703513b4e64c19e9'
FILENAME_VK = 'last_known_id.txt'
BASE_POST_URL = 'https://vk.com/animalsinthestudio?w=wall-102162694_'
BOT_TOKEN = '462837275:AAFPEirpoI65HMhAhoK87Bb-vdua1UCWsx8'
CHANNEL_NAME = '@animalsinthestudio'
SINGLE_RUN = False
bot = telebot.TeleBot(BOT_TOKEN)
def get_data():
timeout = eventlet.Timeout(10)
try:
feed = requests.get(URL_VK)
return feed.json()
except eventlet.timeout.Timeout:
logging.warning('Got Timeout while retrieving VK JSON data. Cancelling...')
return None
finally:
timeout.cancel()
def send_new_posts(items, last_id):
for item in items:
if item['id'] <= last_id:
break
link = '{!s}{!s}'.format(BASE_POST_URL, item['id'])
bot.send_message(CHANNEL_NAME, link)
# Спим секунду, чтобы избежать разного рода ошибок и ограничений (на всякий случай!)
time.sleep(1)
return
def check_new_posts_vk():
# Пишем текущее время начала
logging.info('[VK] Started scanning for new posts')
with open(FILENAME_VK, 'rt') as file:
last_id = int(file.read())
if last_id is None:
logging.error('Could not read from storage. Skipped iteration.')
return
logging.info('Last ID (VK) = {!s}'.format(last_id))
try:
feed = get_data()
# Если ранее случился таймаут, пропускаем итерацию. Если всё нормально - парсим посты.
if feed is not None:
entries = feed['response'][1:]
try:
# Если пост был закреплен, пропускаем его
tmp = entries[0]['is_pinned']
# И запускаем отправку сообщений
send_new_posts(entries[1:], last_id)
except KeyError:
send_new_posts(entries, last_id)
# Записываем новый last_id в файл.
with open(FILENAME_VK, 'wt') as file:
try:
tmp = entries[0]['is_pinned']
# Если первый пост - закрепленный, то сохраняем ID второго
file.write(str(entries[1]['id']))
logging.info('New last_id (VK) is {!s}'.format((entries[1]['id'])))
except KeyError:
file.write(str(entries[0]['id']))
logging.info('New last_id (VK) is {!s}'.format((entries[0]['id'])))
except Exception as ex:
logging.error('Exception of type {!s} in check_new_post(): {!s}'.format(type(ex).__name__, str(ex)))
pass
logging.info('[VK] Finished scanning')
return
if __name__ == '__main__':
# Избавляемся от спама в логах от библиотеки requests
logging.getLogger('requests').setLevel(logging.CRITICAL)
# Настраиваем наш логгер
logging.basicConfig(format='[%(asctime)s] %(filename)s:%(lineno)d %(levelname)s - %(message)s', level=logging.INFO,
filename='bot_log.log', datefmt='%d.%m.%Y %H:%M:%S')
if not SINGLE_RUN:
while True:
check_new_posts_vk()
# Пауза в 4 минуты перед повторной проверкой
logging.info('[App] Script went to sleep.')
time.sleep(60 * 4)
else:
check_new_posts_vk()
logging.info('[App] Script exited.\n')