-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_handler.py
More file actions
221 lines (188 loc) · 8.45 KB
/
Copy pathcommand_handler.py
File metadata and controls
221 lines (188 loc) · 8.45 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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import sys
import json
import importlib.util
import asyncio
import logging
from typing import Dict, Callable, Optional, Set
_DB_DIR = "db"
_SEEN_DB_PATH = os.path.join(_DB_DIR, "seen_users.json")
def _load_seen_users() -> set:
try:
if os.path.exists(_SEEN_DB_PATH):
with open(_SEEN_DB_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return set(data)
except Exception as e:
logging.error(f"Failed to load seen_users: {e}")
return set()
def _save_seen_users(seen: set):
try:
os.makedirs(_DB_DIR, exist_ok=True)
with open(_SEEN_DB_PATH, "w", encoding="utf-8") as f:
json.dump(sorted(seen), f, ensure_ascii=False, indent=2)
except Exception as e:
logging.error(f"Failed to save seen_users: {e}")
class CommandHandler:
def __init__(self):
self.commands: Dict[str, Callable] = {}
self.default_handler: Optional[Callable] = None
self.qwen = None
self.bot = None
self.active_requests: Dict[str, asyncio.Task] = {}
self.room_public_commands: Set[str] = set()
self._help_entries: Dict[str, tuple] = {}
self._help_groups: Dict[str, list] = {}
self._seen_users: set = _load_seen_users()
logging.info(f"Seen users loaded: {len(self._seen_users)} entries")
def register_command(self, command: str, handler: Callable,
help_text: str = None, group: str = "Прочее"):
self.commands[command] = handler
if help_text:
self._help_entries[command] = (help_text, group)
self._help_groups.setdefault(group, [])
if command not in self._help_groups[group]:
self._help_groups[group].append(command)
def build_help_text(self) -> str:
group_order = [
"Основные",
"Чат-комнаты",
"Погода",
"Игры",
"Утилиты",
"Прочее",
]
lines = ["Доступные команды:\n"]
seen_groups = set()
for group in group_order:
if group in self._help_groups:
seen_groups.add(group)
lines.append(f"{group}:")
for cmd in self._help_groups[group]:
text, _ = self._help_entries[cmd]
lines.append(f" {text}")
lines.append("")
for group, cmds in self._help_groups.items():
if group not in seen_groups:
lines.append(f"{group}:")
for cmd in cmds:
text, _ = self._help_entries[cmd]
lines.append(f" {text}")
lines.append("")
lines.append("Qwen отвечает сам, когда пишете в личку.")
lines.append("В общей комнате: /qwen <вопрос>")
lines.append("/weather <город>")
return "\n".join(lines).strip()
def set_default_handler(self, handler: Callable):
self.default_handler = handler
def register_qwen(self, api_key: str):
from qwen_handler import QwenHandler
self.qwen = QwenHandler(api_key=api_key)
def get_qwen(self):
"""Публичный метод для доступа к Qwen из других модулей."""
return self.qwen
async def call_qwen(self, user_id: str, message: str) -> Optional[str]:
"""Публичный метод для вызова Qwen из других модулей."""
return await self._call_qwen(user_id, message)
def load_commands_from_directory(self, directory: str):
if not os.path.exists(directory):
logging.warning(f"Commands directory {directory} not found")
return
for filename in sorted(os.listdir(directory)):
if filename.endswith('.py') and filename != '__init__.py':
module_name = filename[:-3]
module_path = os.path.join(directory, filename)
try:
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module # регистрируем ДО exec, чтобы import нашёл тот же объект
spec.loader.exec_module(module)
if hasattr(module, 'setup'):
module.setup(self)
logging.info(f"Loaded command module: {module_name}")
else:
logging.warning(f"Module {module_name} has no setup() function")
except Exception as e:
logging.error(f"Failed to load command module {filename}: {e}")
def _is_new_user(self, user_id: str) -> bool:
if user_id in self._seen_users:
return False
self._seen_users.add(user_id)
_save_seen_users(self._seen_users)
logging.info(f"New user: {user_id}")
return True
async def _call_qwen(self, user_id: str, message: str) -> Optional[str]:
if not self.qwen:
return None
if user_id in self.active_requests:
task = self.active_requests[user_id]
if not task.done():
return "Подождите, предыдущий запрос ещё обрабатывается..."
task = asyncio.create_task(self.qwen.process_message(user_id, message))
self.active_requests[user_id] = task
try:
return await task
except asyncio.CancelledError:
return "Запрос отменён."
except Exception as e:
logging.error(f"Qwen processing error: {e}")
return f"Ошибка: {e}"
finally:
self.active_requests.pop(user_id, None)
async def handle_message_async(self, bot, user_id: str, message: str) -> Optional[str]:
if self._is_new_user(user_id):
return self.build_help_text()
if message.startswith('/'):
parts = message[1:].split(' ', 1)
command = parts[0].lower()
args = parts[1] if len(parts) > 1 else ""
if self.default_handler and command in self.room_public_commands:
logging.debug(f"Public room command intercepted: /{command} from {user_id}")
try:
if asyncio.iscoroutinefunction(self.default_handler):
result = await self.default_handler(bot, user_id, message)
else:
result = self.default_handler(bot, user_id, message)
if result is not False:
return result
except Exception as e:
logging.error(f"Default handler error (public command): {e}")
return f"Error: {str(e)}"
if command == "qwen":
return await self._call_qwen(user_id, args)
if command in self.commands:
handler = self.commands[command]
try:
if asyncio.iscoroutinefunction(handler):
return await handler(bot, user_id, args)
else:
return handler(bot, user_id, args)
except Exception as e:
logging.error(f"Command handler error: {e}")
return f"Error: {str(e)}"
return None
if self.default_handler:
try:
if asyncio.iscoroutinefunction(self.default_handler):
result = await self.default_handler(bot, user_id, message)
else:
result = self.default_handler(bot, user_id, message)
if result is not False:
return result
except Exception as e:
logging.error(f"Default handler error: {e}")
return f"Error: {str(e)}"
return await self._call_qwen(user_id, message)
def admin_only(func=None):
def decorator(f):
async def wrapper(bot, user_id: str, args: str) -> str:
admin_uin = os.environ.get("ADMIN_UIN", "")
if user_id != admin_uin:
return ""
return await f(bot, user_id, args)
wrapper.__wrapped__ = f
return wrapper
if func is not None:
return decorator(func)
return decorator