forked from RichardAtCT/claude-code-telegram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
351 lines (288 loc) · 12.1 KB
/
Copy pathcore.py
File metadata and controls
351 lines (288 loc) · 12.1 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""Main Telegram bot class.
Features:
- Command registration
- Handler management
- Context injection
- Graceful shutdown
"""
import asyncio
from typing import Any, Callable, Dict, Optional
import structlog
from telegram import Update
from telegram.ext import (
AIORateLimiter,
Application,
ContextTypes,
Defaults,
MessageHandler,
filters,
)
from ..config.settings import Settings
from ..exceptions import ClaudeCodeTelegramError
from .features.registry import FeatureRegistry
from .orchestrator import MessageOrchestrator
logger = structlog.get_logger()
class ClaudeCodeBot:
"""Main bot orchestrator."""
def __init__(self, settings: Settings, dependencies: Dict[str, Any]):
"""Initialize bot with settings and dependencies."""
self.settings = settings
self.deps = dependencies
self.app: Optional[Application] = None
self.is_running = False
self.feature_registry: Optional[FeatureRegistry] = None
self.orchestrator = MessageOrchestrator(settings, dependencies)
async def initialize(self) -> None:
"""Initialize bot application. Idempotent — safe to call multiple times."""
if self.app is not None:
return
logger.info("Initializing Telegram bot")
# Create application
builder = Application.builder()
builder.token(self.settings.telegram_token_str)
builder.defaults(Defaults(do_quote=self.settings.reply_quote))
builder.rate_limiter(AIORateLimiter(max_retries=1))
from .update_processor import StopAwareUpdateProcessor
builder.concurrent_updates(StopAwareUpdateProcessor())
# Configure connection settings
builder.connect_timeout(30)
builder.read_timeout(30)
builder.write_timeout(30)
builder.pool_timeout(30)
self.app = builder.build()
# Initialize feature registry
self.feature_registry = FeatureRegistry(
config=self.settings,
storage=self.deps.get("storage"),
security=self.deps.get("security"),
)
# Add feature registry to dependencies
self.deps["features"] = self.feature_registry
# Initialize the underlying Telegram Application so the bot's
# HTTP client is ready before we make API calls.
await self.app.initialize()
# Set bot commands for menu (requires initialized HTTP client)
await self._set_bot_commands()
# Register handlers
self._register_handlers()
# Add middleware
self._add_middleware()
# Set error handler
self.app.add_error_handler(self._error_handler)
logger.info("Bot initialization complete")
async def _set_bot_commands(self) -> None:
"""Set bot command menu via orchestrator."""
commands = await self.orchestrator.get_bot_commands()
await self.app.bot.set_my_commands(commands)
logger.info("Bot commands set", commands=[cmd.command for cmd in commands])
def _register_handlers(self) -> None:
"""Register handlers via orchestrator (mode-aware)."""
self.orchestrator.register_handlers(self.app)
def _add_middleware(self) -> None:
"""Add middleware to application."""
from .middleware.auth import auth_middleware
from .middleware.rate_limit import rate_limit_middleware
from .middleware.security import security_middleware
# Middleware runs in order of group numbers (lower = earlier)
# Security middleware first (validate inputs)
self.app.add_handler(
MessageHandler(
filters.ALL, self._create_middleware_handler(security_middleware)
),
group=-3,
)
# Authentication second
self.app.add_handler(
MessageHandler(
filters.ALL, self._create_middleware_handler(auth_middleware)
),
group=-2,
)
# Rate limiting third
self.app.add_handler(
MessageHandler(
filters.ALL, self._create_middleware_handler(rate_limit_middleware)
),
group=-1,
)
logger.info("Middleware added to bot")
def _create_middleware_handler(self, middleware_func: Callable) -> Callable:
"""Create middleware handler that injects dependencies.
When middleware rejects a request (returns without calling the handler),
ApplicationHandlerStop is raised to prevent subsequent handler groups
from processing the update.
"""
from telegram.ext import ApplicationHandlerStop
async def middleware_wrapper(
update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
# Ignore updates generated by bots (including this bot) to avoid
# self-authentication loops and duplicate processing.
if update.effective_user and getattr(
update.effective_user, "is_bot", False
):
logger.debug(
"Skipping bot-originated update in middleware",
user_id=update.effective_user.id,
middleware=middleware_func.__name__,
)
raise ApplicationHandlerStop
# Inject dependencies into context
for key, value in self.deps.items():
context.bot_data[key] = value
context.bot_data["settings"] = self.settings
# Track whether the middleware allowed the request through
handler_called = False
async def dummy_handler(event: Any, data: Any) -> None:
nonlocal handler_called
handler_called = True
# Call middleware with Telegram-style parameters
await middleware_func(dummy_handler, update, context.bot_data)
# If middleware didn't call the handler, it rejected the request.
# Raise ApplicationHandlerStop to prevent subsequent handler groups
# (including the main message handlers) from processing this update.
if not handler_called:
raise ApplicationHandlerStop()
return middleware_wrapper
async def start(self) -> None:
"""Start the bot."""
if self.is_running:
logger.warning("Bot is already running")
return
await self.initialize()
logger.info(
"Starting bot", mode="webhook" if self.settings.webhook_url else "polling"
)
try:
self.is_running = True
if self.settings.webhook_url:
# Webhook mode
await self.app.run_webhook(
listen="0.0.0.0",
port=self.settings.webhook_port,
url_path=self.settings.webhook_path,
webhook_url=self.settings.webhook_url,
drop_pending_updates=True,
allowed_updates=Update.ALL_TYPES,
)
else:
# Polling mode - initialize and start polling manually
await self.app.initialize()
await self.app.start()
await self.app.updater.start_polling(
allowed_updates=Update.ALL_TYPES,
drop_pending_updates=True,
)
# Keep running until manually stopped
while self.is_running:
await asyncio.sleep(1)
except Exception as e:
logger.error("Error running bot", error=str(e))
raise ClaudeCodeTelegramError(f"Failed to start bot: {str(e)}") from e
finally:
self.is_running = False
async def stop(self) -> None:
"""Gracefully stop the bot."""
if not self.is_running:
logger.warning("Bot is not running")
return
logger.info("Stopping bot")
try:
self.is_running = False # Stop the main loop first
# Shutdown feature registry
if self.feature_registry:
self.feature_registry.shutdown()
if self.app:
# Stop the updater if it's running
if self.app.updater.running:
await self.app.updater.stop()
# Stop the application
await self.app.stop()
await self.app.shutdown()
logger.info("Bot stopped successfully")
except Exception as e:
logger.error("Error stopping bot", error=str(e))
raise ClaudeCodeTelegramError(f"Failed to stop bot: {str(e)}") from e
async def _error_handler(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Handle errors globally."""
error = context.error
logger.error(
"Global error handler triggered",
error=str(error),
update_type=type(update).__name__ if update else None,
user_id=(
update.effective_user.id if update and update.effective_user else None
),
)
# Determine error message for user
from ..exceptions import (
AuthenticationError,
ConfigurationError,
RateLimitExceeded,
SecurityError,
)
error_messages = {
AuthenticationError: "🔒 Authentication required. Please contact the administrator.",
SecurityError: "🛡️ Security violation detected. This incident has been logged.",
RateLimitExceeded: "⏱️ Rate limit exceeded. Please wait before sending more messages.",
ConfigurationError: "⚙️ Configuration error. Please contact the administrator.",
asyncio.TimeoutError: "⏰ Operation timed out. Please try again with a simpler request.",
}
error_type = type(error)
user_message = error_messages.get(
error_type, "❌ An unexpected error occurred. Please try again."
)
# Try to notify user
if update and update.effective_message:
try:
await update.effective_message.reply_text(user_message)
except Exception:
logger.exception("Failed to send error message to user")
# Log to audit system if available
from ..security.audit import AuditLogger
audit_logger: Optional[AuditLogger] = context.bot_data.get("audit_logger")
if audit_logger and update and update.effective_user:
try:
await audit_logger.log_security_violation(
user_id=update.effective_user.id,
violation_type="system_error",
details=f"Error type: {error_type.__name__}, Message: {str(error)}",
severity="medium",
)
except Exception:
logger.exception("Failed to log error to audit system")
async def get_bot_info(self) -> Dict[str, Any]:
"""Get bot information."""
if not self.app:
return {"status": "not_initialized"}
try:
me = await self.app.bot.get_me()
return {
"status": "running" if self.is_running else "initialized",
"username": me.username,
"first_name": me.first_name,
"id": me.id,
"can_join_groups": me.can_join_groups,
"can_read_all_group_messages": me.can_read_all_group_messages,
"supports_inline_queries": me.supports_inline_queries,
"webhook_url": self.settings.webhook_url,
"webhook_port": (
self.settings.webhook_port if self.settings.webhook_url else None
),
}
except Exception as e:
logger.error("Failed to get bot info", error=str(e))
return {"status": "error", "error": str(e)}
async def health_check(self) -> bool:
"""Perform health check."""
try:
if not self.app:
return False
# Try to get bot info
await self.app.bot.get_me()
return True
except Exception as e:
logger.error("Health check failed", error=str(e))
return False