-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_reg_middleware.py
89 lines (62 loc) · 2.34 KB
/
test_reg_middleware.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
from vk import VK
from vk.utils import TaskManager
from vk.bot_framework import Dispatcher, rules
from vk.bot_framework import BaseRule, BaseMiddleware
from vk import types
import logging
from config import TOKEN, GROUP_ID # PLUGINS_PATH #, loop
from keyboards import *
logging.basicConfig(level="DEBUG")
vk = VK(TOKEN)
gid = GROUP_ID
task_manager = TaskManager(vk.loop)
api = vk.get_api()
dp = Dispatcher(vk, gid)
USERS = {} # schema - id: status
class RegistrationMiddleware(BaseMiddleware):
"""
Register users in bot.
"""
async def pre_process_event(self, event, data: dict):
if event["type"] == "message_new":
from_id = event["object"]["from_id"]
if from_id not in USERS:
USERS[from_id] = "user"
return data
async def post_process_event(self):
pass
class IsAdmin(BaseRule):
"""
Check admin rights of user.
"""
def __init__(self, is_admin: bool):
self.is_admin: bool = is_admin
async def check(self, message: types.Message, data: dict):
status = USERS[message.from_id]
if not self.is_admin and status != "admin":
return True
elif not self.is_admin and status == "admin":
return False
elif self.is_admin and status == "admin":
return True
elif self.is_admin and status != "admin":
return False
@dp.message_handler(rules.Command("start"))
async def handle(message: types.Message, data: dict):
await message.reply("Hello!")
@dp.message_handler(rules.Command("admin"), IsAdmin(True))
async def admin_panel(message: types.Message, data: dict):
await message.reply("Is admin panel!")
@dp.message_handler(rules.Command("get"), IsAdmin(False))
async def get_admin_rights(message: types.Message, data: dict):
USERS[message.from_id] = "admin"
await message.reply("Successfully!")
@dp.message_handler() # обработка названий команды. TODO: машина состояний для определения момента ввода команды
async def handle_other_messages(message: types.Message, data: dict):
await message.answer(message.text)
async def run():
dp.run_polling()
if __name__ == "__main__":
dp.setup_middleware(RegistrationMiddleware()) # setup middleware
task_manager.add_task(run)
task_manager.run()