-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
86 lines (62 loc) · 2.99 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
76
77
78
79
80
81
82
83
84
85
86
import telebot
import json
import datetime as dt
def read_id_or_api_key(file_path):
with open(file_path, 'r+') as f:
key = f.readline().strip()
assert key
print(f'Got {file_path.split("/")[-1]}')
return key
API_KEY = read_id_or_api_key('input/API_KEY')
TEACHER_ID = read_id_or_api_key('input/teacher_id')
BOT = telebot.TeleBot(API_KEY, parse_mode=None)
def read_file():
with open('output/questions.json', 'r', encoding='utf-8') as f:
try:
data = json.loads(f.read())
print('Content loaded from json')
except json.JSONDecodeError:
print('Questions file is empty, filling...')
write_to_file({"number_of_questions": 0})
data = read_file()
return data
def write_to_file(data):
with open('output/questions.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False, indent=2))
print(f'Content written in json\n')
@BOT.message_handler(commands=['start', 'help'])
def send_welcome(command):
text = """Привет, пиши сюда если у тебя появились вопросы по курсу, не бойся.
Этот бот написан так, что я не смогу увидеть автора сообщения, так что он анонимен.
Если непонятна целая тема, то пиши её, но лучше конечно конкретные пункты по ней.
"""
print(f'Получена команда {command.text}')
BOT.reply_to(command, text)
@BOT.message_handler(func=lambda message: True)
def get_question(message):
if len(message.text) > 500:
BOT.reply_to(message,
'Прости, сообщение слишком большое. Попробуй разбить вопрос на части и попробовать ещё раз.')
return
answer = f"""Хорошо, твой вопрос: "{message.text}"
Успешно записан. На следующей лекции постараюсь разобрать.🙃"""
print(f'\nGot new question: "{message.text}"')
BOT.send_message(chat_id=TEACHER_ID, text=f'❗Новый вопрос, "{message.text}"')
try:
message.text.encode(encoding='utf-8')
except UnicodeEncodeError:
print('Сообщение не записано из-за проблем с кодировкой.')
BOT.reply_to(message, 'Произошла ошибка, попробуй удалить спец. символы и смайлики')
return
file_data['number_of_questions'] += 1
file_data[str(file_data['number_of_questions'])] = {
'date': str(dt.datetime.now().date()),
'time': str(dt.datetime.now().time())[:-10],
'text': message.text
}
write_to_file(file_data)
BOT.reply_to(message, answer)
if __name__ == '__main__':
file_data = read_file()
print('Бот начинает работу\n')
BOT.infinity_polling(timeout=5)