-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
94 lines (78 loc) · 2.99 KB
/
main.py
File metadata and controls
94 lines (78 loc) · 2.99 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
import requests
import time
import telegram
import os
from dotenv import load_dotenv
import logging
logger = logging.getLogger("DVMNBotLogsHandler")
REVIEWS_URL = 'https://dvmn.org/api/user_reviews/'
LONG_POLLING_URL = 'https://dvmn.org/api/long_polling/'
TIMEOUT = 90
LESSON_WITH_ERRORS = '''Преподаватель проверил работу "{}".
К сожалению, в работе нашлись ошибки.
Ссылка на урок: https://dvmn.org{}'''
LESSON_WITHOUT_ERRORS = '''Преподаватель проверил работу "{}".
Ошибок нет, можно приступать к следующему уроку.'''
def waiting_for_results(bot, token):
logger.info('Бот запущен')
requested_timestamp = time.time()
while True:
try:
dvmn_headers = {
'Authorization': 'Token {}'.format(token)
}
payload = {
'timestamp': requested_timestamp
}
response = requests.get(
LONG_POLLING_URL,
headers=dvmn_headers,
params=payload,
timeout=TIMEOUT
)
response.raise_for_status()
devman_answer = response.json()
if devman_answer['status'] == 'timeout':
requested_timestamp = devman_answer['timestamp_to_request']
else:
requested_timestamp = devman_answer['last_attempt_timestamp']
lesson_details = devman_answer['new_attempts'][0]
lesson_title = lesson_details['lesson_title']
lesson_url = lesson_details['lesson_url']
lesson_is_negative = lesson_details['is_negative']
if lesson_is_negative:
msg_text = (
LESSON_WITH_ERRORS
).format(lesson_title, lesson_url)
else:
msg_text = (
LESSON_WITHOUT_ERRORS
).format(lesson_title)
send_msg(bot, msg_text)
except requests.exceptions.ReadTimeout:
pass
except (
requests.exceptions.ConnectionError,
ConnectionResetError,
requests.exceptions.HTTPError
) as er:
logger.error(er, exc_info=True)
time.sleep(3)
continue
def send_msg(bot, msg_text):
bot.send_message(chat_id=os.getenv('TELEGRAM_CHAT_ID'), text=(msg_text))
def main():
load_dotenv()
bot = telegram.Bot(token=os.getenv('TELEGRAM_BOT_TOKEN'))
class DVMNBotLogsHandler(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
bot.send_message(
chat_id=os.getenv('TELEGRAM_CHAT_ID'),
text=log_entry
)
logger.setLevel(logging.DEBUG)
logger.addHandler(DVMNBotLogsHandler())
waiting_for_results(bot, os.getenv('DVMN_API_TOKEN'))
if __name__ == '__main__':
main()