-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvk_quiz_bot.py
151 lines (114 loc) · 3.96 KB
/
vk_quiz_bot.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import json
import logging
import os
import random
import sys
import textwrap
import redis
import vk_api
from vk_api.keyboard import VkKeyboard
from vk_api.keyboard import VkKeyboardColor
from vk_api.longpoll import VkEventType
from vk_api.longpoll import VkLongPoll
from vk_api.utils import get_random_id
from answer_tools import get_answer_question
from answer_tools import remove_comments
logger = logging.getLogger(__name__)
def get_custom_keyboard():
keyboard = VkKeyboard()
keyboard.add_button('Новый вопрос', color=VkKeyboardColor.PRIMARY)
keyboard.add_button('Сдаться', color=VkKeyboardColor.NEGATIVE)
return keyboard.get_keyboard()
def handle_new_question(event, vk, redis_conn):
question_num = random.choice(redis_conn.hkeys('questions'))
redis_conn.hset(
'users',
f'user_vk_{event.user_id}',
json.dumps({'last_asked_question': question_num})
)
qa = json.loads(redis_conn.hget('questions', question_num))
question = qa.get('question')
vk.messages.send(
peer_id=event.user_id,
random_id=get_random_id(),
keyboard=get_custom_keyboard(),
message=question
)
def handle_solution_attempt(event, vk, redis_conn):
answer = get_answer_question(event.user_id, redis_conn, source='vk')
user_response = event.text
correct_answer = remove_comments(answer).lower().strip('.')
if user_response.lower() == correct_answer:
message = textwrap.dedent(
'''
Правильно! Поздравляю!
Для следующего вопроса нажми «Новый вопрос».
'''
)
vk.messages.send(
peer_id=event.user_id,
random_id=get_random_id(),
keyboard=get_custom_keyboard(),
message=message
)
else:
vk.messages.send(
peer_id=event.user_id,
random_id=get_random_id(),
keyboard=get_custom_keyboard(),
message='Неправильно. Попробуешь ещё раз?'
)
def handle_give_up(event, vk, redis_conn):
answer = get_answer_question(event.user_id, redis_conn, source='vk')
response = (
f'Вот тебе правильный ответ: {answer} '
'Чтобы продолжить нажми «Новый вопрос»'
)
vk.messages.send(
peer_id=event.user_id,
random_id=get_random_id(),
keyboard=get_custom_keyboard(),
message=response
)
def run_chatbot(token, redis_host, redis_port, redis_pass):
vk_session = vk_api.VkApi(token=token)
api_vk = vk_session.get_api()
longpoll = VkLongPoll(vk_session)
redis_conn = redis.Redis(
host=redis_host,
port=redis_port,
password=redis_pass,
charset='utf-8',
decode_responses=True
)
for event in longpoll.listen():
if not (event.type == VkEventType.MESSAGE_NEW and event.to_me):
continue
if event.text == 'Новый вопрос':
handle_new_question(event, api_vk, redis_conn)
continue
if event.text == 'Сдаться':
handle_give_up(event, api_vk, redis_conn)
continue
handle_solution_attempt(event, api_vk, redis_conn)
def main():
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
vk_token = os.getenv('VK_TOKEN')
redis_host = os.getenv('REDIS_HOST')
redis_port = os.getenv('REDIS_PORT')
redis_password = os.getenv('REDIS_PASSWORD')
while True:
try:
run_chatbot(vk_token, redis_host, redis_port, redis_password)
except Exception as err:
logger.error(f'Бот "{__file__}" упал с ошибкой.')
logger.exception(err)
continue
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit()