-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
75 lines (66 loc) · 2.54 KB
/
main.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
import os
import time
import logging
import requests
import ptbot
import telegram
from dotenv import load_dotenv
import setup_logging
logger = logging.getLogger(__name__)
def check_long_polling(base_api_url, headers, timestamp=None):
logger.info('Start long polling...')
api_command = "long_polling"
payload = {'timestamp': timestamp}
response = requests.get(
base_api_url + api_command,
headers=headers,
params=payload,
timeout=91
)
response.raise_for_status()
return response.json()
def main():
base_api_url = "https://dvmn.org/api/"
headers = {
"Authorization": "Token {}".format(os.getenv("DEVMAN_TOKEN")),
}
while True:
while True:
try:
bot = telegram.Bot(os.getenv("TELEGRAM_TOKEN"))
logger.info("Бот запущен...")
break
except telegram.error.NetworkError:
logger.exception('TelegramError')
time.sleep(60)
timestamp = None
try:
json_data = check_long_polling(base_api_url, headers, timestamp)
if json_data['status'] == 'timeout':
timestamp = json_data['timestamp_to_request']
elif json_data['status'] == 'found':
last_lesson = json_data['new_attempts'][0]
lesson_title = last_lesson['lesson_title']
logger.debug(lesson_title)
logger.debug(last_lesson)
score = last_lesson['is_negative']
score_message = "Преподавателю всё понравилось, можно приступать к следующему уроку!"
if score:
score_message = "К сожалению в работе нашлись ошибки"
message = f"У вас проверили работу \"{lesson_title}\"\n\n{score_message}"
bot.send_message(
os.getenv("TELEGRAM_CHAT_ID"),
message
)
except requests.exceptions.ReadTimeout:
logger.exception('ReadTimeout')
except telegram.error.NetworkError:
logger.exception('TelegramError')
except requests.RequestException as requests_error:
logger.exception('RequestException')
except Exception:
logger.exception('UnknownException')
if __name__ == "__main__":
load_dotenv()
setup_logging.config_logging(os.getenv("TELEGRAM_TOKEN"), os.getenv("TELEGRAM_CHAT_ID"))
main()