devcopilot 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- api/__init__.py +17 -0
- api/admin_config.py +1303 -0
- api/admin_routes.py +287 -0
- api/admin_static/admin.css +459 -0
- api/admin_static/admin.js +497 -0
- api/admin_static/index.html +77 -0
- api/admin_urls.py +34 -0
- api/app.py +194 -0
- api/command_utils.py +164 -0
- api/dependencies.py +144 -0
- api/detection.py +152 -0
- api/gateway_model_ids.py +54 -0
- api/model_catalog.py +133 -0
- api/model_router.py +125 -0
- api/models/__init__.py +45 -0
- api/models/anthropic.py +234 -0
- api/models/openai_responses.py +28 -0
- api/models/responses.py +60 -0
- api/optimization_handlers.py +154 -0
- api/request_pipeline.py +424 -0
- api/routes.py +156 -0
- api/runtime.py +334 -0
- api/validation_log.py +48 -0
- api/web_server_tools.py +22 -0
- api/web_tools/__init__.py +17 -0
- api/web_tools/constants.py +15 -0
- api/web_tools/egress.py +99 -0
- api/web_tools/outbound.py +278 -0
- api/web_tools/parsers.py +104 -0
- api/web_tools/request.py +87 -0
- api/web_tools/streaming.py +206 -0
- cli/__init__.py +5 -0
- cli/claude_env.py +12 -0
- cli/entrypoints.py +166 -0
- cli/env.example +209 -0
- cli/launchers/__init__.py +1 -0
- cli/launchers/claude.py +84 -0
- cli/launchers/codex.py +204 -0
- cli/launchers/codex_model_catalog.py +186 -0
- cli/launchers/common.py +93 -0
- cli/managed/__init__.py +6 -0
- cli/managed/claude.py +215 -0
- cli/managed/manager.py +157 -0
- cli/managed/session.py +260 -0
- cli/process_registry.py +78 -0
- config/__init__.py +5 -0
- config/constants.py +13 -0
- config/logging_config.py +159 -0
- config/nim.py +118 -0
- config/paths.py +91 -0
- config/provider_catalog.py +259 -0
- config/provider_ids.py +7 -0
- config/settings.py +538 -0
- core/__init__.py +1 -0
- core/anthropic/__init__.py +46 -0
- core/anthropic/content.py +31 -0
- core/anthropic/conversion.py +587 -0
- core/anthropic/emitted_sse_tracker.py +346 -0
- core/anthropic/errors.py +70 -0
- core/anthropic/native_messages_request.py +280 -0
- core/anthropic/native_sse_block_policy.py +313 -0
- core/anthropic/provider_stream_error.py +34 -0
- core/anthropic/server_tool_sse.py +14 -0
- core/anthropic/sse.py +440 -0
- core/anthropic/stream_contracts.py +205 -0
- core/anthropic/stream_recovery.py +346 -0
- core/anthropic/stream_recovery_session.py +133 -0
- core/anthropic/thinking.py +140 -0
- core/anthropic/tokens.py +117 -0
- core/anthropic/tools.py +212 -0
- core/anthropic/utils.py +9 -0
- core/openai_responses/__init__.py +5 -0
- core/openai_responses/adapter.py +31 -0
- core/openai_responses/anthropic_sse.py +59 -0
- core/openai_responses/errors.py +22 -0
- core/openai_responses/events.py +19 -0
- core/openai_responses/ids.py +21 -0
- core/openai_responses/input.py +258 -0
- core/openai_responses/items.py +37 -0
- core/openai_responses/reasoning.py +52 -0
- core/openai_responses/stream.py +25 -0
- core/openai_responses/stream_state.py +654 -0
- core/openai_responses/tools.py +374 -0
- core/openai_responses/usage.py +37 -0
- core/rate_limit.py +60 -0
- core/trace.py +216 -0
- devcopilot-0.2.0.dist-info/METADATA +687 -0
- devcopilot-0.2.0.dist-info/RECORD +189 -0
- devcopilot-0.2.0.dist-info/WHEEL +4 -0
- devcopilot-0.2.0.dist-info/entry_points.txt +6 -0
- devcopilot-0.2.0.dist-info/licenses/LICENSE +21 -0
- messaging/__init__.py +26 -0
- messaging/cli_event_constants.py +67 -0
- messaging/command_context.py +66 -0
- messaging/command_dispatcher.py +37 -0
- messaging/commands.py +275 -0
- messaging/event_parser.py +181 -0
- messaging/limiter.py +300 -0
- messaging/models.py +36 -0
- messaging/node_event_pipeline.py +127 -0
- messaging/node_runner.py +342 -0
- messaging/platforms/__init__.py +15 -0
- messaging/platforms/base.py +228 -0
- messaging/platforms/discord.py +567 -0
- messaging/platforms/factory.py +103 -0
- messaging/platforms/outbox.py +144 -0
- messaging/platforms/telegram.py +688 -0
- messaging/platforms/voice_flow.py +295 -0
- messaging/rendering/__init__.py +3 -0
- messaging/rendering/discord_markdown.py +318 -0
- messaging/rendering/markdown_tables.py +49 -0
- messaging/rendering/profiles.py +55 -0
- messaging/rendering/telegram_markdown.py +327 -0
- messaging/safe_diagnostics.py +17 -0
- messaging/session.py +334 -0
- messaging/transcript.py +581 -0
- messaging/transcription.py +164 -0
- messaging/trees/__init__.py +15 -0
- messaging/trees/data.py +482 -0
- messaging/trees/manager.py +433 -0
- messaging/trees/processor.py +179 -0
- messaging/trees/repository.py +177 -0
- messaging/turn_intake.py +235 -0
- messaging/ui_updates.py +101 -0
- messaging/voice.py +76 -0
- messaging/workflow.py +200 -0
- providers/__init__.py +31 -0
- providers/base.py +152 -0
- providers/cerebras/__init__.py +7 -0
- providers/cerebras/client.py +31 -0
- providers/cerebras/request.py +55 -0
- providers/codestral/__init__.py +7 -0
- providers/codestral/client.py +34 -0
- providers/deepseek/__init__.py +11 -0
- providers/deepseek/client.py +51 -0
- providers/deepseek/request.py +475 -0
- providers/defaults.py +41 -0
- providers/error_mapping.py +309 -0
- providers/exceptions.py +113 -0
- providers/fireworks/__init__.py +5 -0
- providers/fireworks/client.py +45 -0
- providers/fireworks/request.py +48 -0
- providers/gemini/__init__.py +7 -0
- providers/gemini/client.py +49 -0
- providers/gemini/request.py +199 -0
- providers/groq/__init__.py +7 -0
- providers/groq/client.py +31 -0
- providers/groq/request.py +83 -0
- providers/kimi/__init__.py +10 -0
- providers/kimi/client.py +53 -0
- providers/kimi/request.py +42 -0
- providers/llamacpp/__init__.py +3 -0
- providers/llamacpp/client.py +16 -0
- providers/lmstudio/__init__.py +5 -0
- providers/lmstudio/client.py +16 -0
- providers/mistral/__init__.py +7 -0
- providers/mistral/client.py +31 -0
- providers/mistral/request.py +37 -0
- providers/model_listing.py +133 -0
- providers/nvidia_nim/__init__.py +7 -0
- providers/nvidia_nim/client.py +91 -0
- providers/nvidia_nim/request.py +430 -0
- providers/nvidia_nim/voice.py +95 -0
- providers/ollama/__init__.py +7 -0
- providers/ollama/client.py +39 -0
- providers/open_router/__init__.py +7 -0
- providers/open_router/client.py +124 -0
- providers/open_router/request.py +42 -0
- providers/opencode/__init__.py +11 -0
- providers/opencode/client.py +31 -0
- providers/opencode/request.py +35 -0
- providers/rate_limit.py +300 -0
- providers/registry.py +527 -0
- providers/transports/__init__.py +1 -0
- providers/transports/anthropic_messages/__init__.py +5 -0
- providers/transports/anthropic_messages/http.py +118 -0
- providers/transports/anthropic_messages/recovery.py +206 -0
- providers/transports/anthropic_messages/stream.py +295 -0
- providers/transports/anthropic_messages/transport.py +236 -0
- providers/transports/openai_chat/__init__.py +5 -0
- providers/transports/openai_chat/recovery.py +217 -0
- providers/transports/openai_chat/stream.py +384 -0
- providers/transports/openai_chat/tool_calls.py +293 -0
- providers/transports/openai_chat/transport.py +156 -0
- providers/wafer/__init__.py +10 -0
- providers/wafer/client.py +50 -0
- providers/zai/__init__.py +10 -0
- providers/zai/client.py +46 -0
- providers/zai/request.py +42 -0
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Telegram Platform Adapter
|
|
3
|
+
|
|
4
|
+
Implements MessagingPlatform for Telegram using python-telegram-bot.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import contextlib
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
# Opt-in to future behavior for python-telegram-bot (retry_after as timedelta)
|
|
12
|
+
# This must be set BEFORE importing telegram.error
|
|
13
|
+
os.environ["PTB_TIMEDELTA"] = "1"
|
|
14
|
+
|
|
15
|
+
from collections.abc import Awaitable, Callable
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
from loguru import logger
|
|
19
|
+
|
|
20
|
+
from core.anthropic import format_user_error_preview
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from telegram import Update
|
|
24
|
+
from telegram.ext import ContextTypes
|
|
25
|
+
|
|
26
|
+
from ..models import IncomingMessage
|
|
27
|
+
from ..rendering.telegram_markdown import escape_md_v2, format_status
|
|
28
|
+
from .base import MessagingPlatform
|
|
29
|
+
from .outbox import PlatformOutbox
|
|
30
|
+
from .voice_flow import VoiceNoteFlow, VoiceNoteRequest, audio_suffix_from_metadata
|
|
31
|
+
|
|
32
|
+
# Optional import - python-telegram-bot may not be installed
|
|
33
|
+
try:
|
|
34
|
+
from telegram import Update
|
|
35
|
+
from telegram.error import NetworkError, RetryAfter, TelegramError
|
|
36
|
+
from telegram.ext import (
|
|
37
|
+
Application,
|
|
38
|
+
CommandHandler,
|
|
39
|
+
ContextTypes,
|
|
40
|
+
MessageHandler,
|
|
41
|
+
filters,
|
|
42
|
+
)
|
|
43
|
+
from telegram.request import HTTPXRequest
|
|
44
|
+
|
|
45
|
+
TELEGRAM_AVAILABLE = True
|
|
46
|
+
except ImportError:
|
|
47
|
+
TELEGRAM_AVAILABLE = False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class TelegramPlatform(MessagingPlatform):
|
|
51
|
+
"""
|
|
52
|
+
Telegram messaging platform adapter.
|
|
53
|
+
|
|
54
|
+
Uses python-telegram-bot (BoT API) for Telegram access.
|
|
55
|
+
Requires a Bot Token from @BotFather.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
name = "telegram"
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
bot_token: str | None = None,
|
|
63
|
+
allowed_user_id: str | None = None,
|
|
64
|
+
*,
|
|
65
|
+
voice_note_enabled: bool = True,
|
|
66
|
+
whisper_model: str = "base",
|
|
67
|
+
whisper_device: str = "cpu",
|
|
68
|
+
hf_token: str = "",
|
|
69
|
+
nvidia_nim_api_key: str = "",
|
|
70
|
+
messaging_rate_limit: int = 1,
|
|
71
|
+
messaging_rate_window: float = 1.0,
|
|
72
|
+
log_raw_messaging_content: bool = False,
|
|
73
|
+
log_api_error_tracebacks: bool = False,
|
|
74
|
+
):
|
|
75
|
+
if not TELEGRAM_AVAILABLE:
|
|
76
|
+
raise ImportError(
|
|
77
|
+
"python-telegram-bot is required. Install with: pip install python-telegram-bot"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
self.bot_token = bot_token
|
|
81
|
+
self.allowed_user_id = allowed_user_id
|
|
82
|
+
|
|
83
|
+
if not self.bot_token:
|
|
84
|
+
# We don't raise here to allow instantiation for testing/conditional logic,
|
|
85
|
+
# but start() will fail.
|
|
86
|
+
logger.warning("TELEGRAM_BOT_TOKEN not set")
|
|
87
|
+
|
|
88
|
+
self._application: Application | None = None
|
|
89
|
+
self._message_handler: Callable[[IncomingMessage], Awaitable[None]] | None = (
|
|
90
|
+
None
|
|
91
|
+
)
|
|
92
|
+
self._connected = False
|
|
93
|
+
self._limiter: Any | None = None # Will be MessagingRateLimiter
|
|
94
|
+
|
|
95
|
+
async def send_operation(
|
|
96
|
+
chat_id: str,
|
|
97
|
+
text: str,
|
|
98
|
+
reply_to: str | None,
|
|
99
|
+
parse_mode: str | None,
|
|
100
|
+
message_thread_id: str | None,
|
|
101
|
+
) -> str:
|
|
102
|
+
return await self.send_message(
|
|
103
|
+
chat_id,
|
|
104
|
+
text,
|
|
105
|
+
reply_to,
|
|
106
|
+
parse_mode,
|
|
107
|
+
message_thread_id,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
async def edit_operation(
|
|
111
|
+
chat_id: str,
|
|
112
|
+
message_id: str,
|
|
113
|
+
text: str,
|
|
114
|
+
parse_mode: str | None,
|
|
115
|
+
) -> None:
|
|
116
|
+
await self.edit_message(chat_id, message_id, text, parse_mode)
|
|
117
|
+
|
|
118
|
+
async def delete_operation(chat_id: str, message_id: str) -> None:
|
|
119
|
+
await self.delete_message(chat_id, message_id)
|
|
120
|
+
|
|
121
|
+
async def delete_many_operation(
|
|
122
|
+
chat_id: str,
|
|
123
|
+
message_ids: list[str],
|
|
124
|
+
) -> None:
|
|
125
|
+
await self.delete_messages(chat_id, message_ids)
|
|
126
|
+
|
|
127
|
+
self._outbox = PlatformOutbox(
|
|
128
|
+
get_limiter=lambda: self._limiter,
|
|
129
|
+
send=send_operation,
|
|
130
|
+
edit=edit_operation,
|
|
131
|
+
delete=delete_operation,
|
|
132
|
+
delete_many=delete_many_operation,
|
|
133
|
+
)
|
|
134
|
+
self._voice_flow = VoiceNoteFlow(
|
|
135
|
+
voice_note_enabled=voice_note_enabled,
|
|
136
|
+
whisper_model=whisper_model,
|
|
137
|
+
whisper_device=whisper_device,
|
|
138
|
+
hf_token=hf_token,
|
|
139
|
+
nvidia_nim_api_key=nvidia_nim_api_key,
|
|
140
|
+
log_raw_messaging_content=log_raw_messaging_content,
|
|
141
|
+
log_api_error_tracebacks=log_api_error_tracebacks,
|
|
142
|
+
)
|
|
143
|
+
self._messaging_rate_limit = messaging_rate_limit
|
|
144
|
+
self._messaging_rate_window = messaging_rate_window
|
|
145
|
+
self._log_raw_messaging_content = log_raw_messaging_content
|
|
146
|
+
self._log_api_error_tracebacks = log_api_error_tracebacks
|
|
147
|
+
|
|
148
|
+
async def _register_pending_voice(
|
|
149
|
+
self, chat_id: str, voice_msg_id: str, status_msg_id: str
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Register a voice note as pending transcription (for /clear reply during transcription)."""
|
|
152
|
+
await self._voice_flow.register_pending_voice(
|
|
153
|
+
chat_id,
|
|
154
|
+
voice_msg_id,
|
|
155
|
+
status_msg_id,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
async def cancel_pending_voice(
|
|
159
|
+
self, chat_id: str, reply_id: str
|
|
160
|
+
) -> tuple[str, str] | None:
|
|
161
|
+
"""Cancel a pending voice transcription. Returns (voice_msg_id, status_msg_id) if found."""
|
|
162
|
+
return await self._voice_flow.cancel_pending_voice(chat_id, reply_id)
|
|
163
|
+
|
|
164
|
+
async def _is_voice_still_pending(self, chat_id: str, voice_msg_id: str) -> bool:
|
|
165
|
+
"""Check if a voice note is still pending (not cancelled)."""
|
|
166
|
+
return await self._voice_flow.is_voice_still_pending(chat_id, voice_msg_id)
|
|
167
|
+
|
|
168
|
+
async def start(self) -> None:
|
|
169
|
+
"""Initialize and connect to Telegram."""
|
|
170
|
+
if not self.bot_token:
|
|
171
|
+
raise ValueError("TELEGRAM_BOT_TOKEN is required")
|
|
172
|
+
|
|
173
|
+
# Configure request with longer timeouts
|
|
174
|
+
request = HTTPXRequest(
|
|
175
|
+
connection_pool_size=8, connect_timeout=30.0, read_timeout=30.0
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# Build Application
|
|
179
|
+
builder = Application.builder().token(self.bot_token).request(request)
|
|
180
|
+
self._application = builder.build()
|
|
181
|
+
|
|
182
|
+
# Register Internal Handlers
|
|
183
|
+
# We catch ALL text messages and commands to forward them
|
|
184
|
+
self._application.add_handler(
|
|
185
|
+
MessageHandler(filters.TEXT & (~filters.COMMAND), self._on_telegram_message)
|
|
186
|
+
)
|
|
187
|
+
self._application.add_handler(CommandHandler("start", self._on_start_command))
|
|
188
|
+
# Catch-all for other commands if needed, or let them fall through
|
|
189
|
+
self._application.add_handler(
|
|
190
|
+
MessageHandler(filters.COMMAND, self._on_telegram_message)
|
|
191
|
+
)
|
|
192
|
+
# Voice note handler
|
|
193
|
+
self._application.add_handler(
|
|
194
|
+
MessageHandler(filters.VOICE, self._on_telegram_voice)
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
# Initialize internal components with retry logic
|
|
198
|
+
max_retries = 3
|
|
199
|
+
for attempt in range(max_retries):
|
|
200
|
+
try:
|
|
201
|
+
await self._application.initialize()
|
|
202
|
+
await self._application.start()
|
|
203
|
+
|
|
204
|
+
# Start polling (non-blocking way for integration)
|
|
205
|
+
if self._application.updater:
|
|
206
|
+
await self._application.updater.start_polling(
|
|
207
|
+
drop_pending_updates=False
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
self._connected = True
|
|
211
|
+
break
|
|
212
|
+
except (NetworkError, Exception) as e:
|
|
213
|
+
if attempt < max_retries - 1:
|
|
214
|
+
wait_time = 2 * (attempt + 1)
|
|
215
|
+
logger.warning(
|
|
216
|
+
f"Connection failed (attempt {attempt + 1}/{max_retries}): {e}. Retrying in {wait_time}s..."
|
|
217
|
+
)
|
|
218
|
+
await asyncio.sleep(wait_time)
|
|
219
|
+
else:
|
|
220
|
+
logger.error(f"Failed to connect after {max_retries} attempts")
|
|
221
|
+
raise
|
|
222
|
+
|
|
223
|
+
# Initialize rate limiter
|
|
224
|
+
from ..limiter import MessagingRateLimiter
|
|
225
|
+
|
|
226
|
+
self._limiter = await MessagingRateLimiter.get_instance(
|
|
227
|
+
rate_limit=self._messaging_rate_limit,
|
|
228
|
+
rate_window=self._messaging_rate_window,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
# Send startup notification
|
|
232
|
+
try:
|
|
233
|
+
target = self.allowed_user_id
|
|
234
|
+
if target:
|
|
235
|
+
startup_text = (
|
|
236
|
+
f"🚀 *{escape_md_v2('Claude Code Proxy is online!')}* "
|
|
237
|
+
f"{escape_md_v2('(Bot API)')}"
|
|
238
|
+
)
|
|
239
|
+
await self.send_message(
|
|
240
|
+
target,
|
|
241
|
+
startup_text,
|
|
242
|
+
)
|
|
243
|
+
except Exception as e:
|
|
244
|
+
if self._log_api_error_tracebacks:
|
|
245
|
+
logger.warning("Could not send startup message: {}", e)
|
|
246
|
+
else:
|
|
247
|
+
logger.warning(
|
|
248
|
+
"Could not send startup message: exc_type={}",
|
|
249
|
+
type(e).__name__,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
logger.info("Telegram platform started (Bot API)")
|
|
253
|
+
|
|
254
|
+
async def stop(self) -> None:
|
|
255
|
+
"""Stop the bot."""
|
|
256
|
+
if self._application and self._application.updater:
|
|
257
|
+
await self._application.updater.stop()
|
|
258
|
+
await self._application.stop()
|
|
259
|
+
await self._application.shutdown()
|
|
260
|
+
|
|
261
|
+
self._connected = False
|
|
262
|
+
logger.info("Telegram platform stopped")
|
|
263
|
+
|
|
264
|
+
async def _with_retry(
|
|
265
|
+
self, func: Callable[..., Awaitable[Any]], *args, **kwargs
|
|
266
|
+
) -> Any:
|
|
267
|
+
"""Helper to execute a function with exponential backoff on network errors."""
|
|
268
|
+
max_retries = 3
|
|
269
|
+
for attempt in range(max_retries):
|
|
270
|
+
try:
|
|
271
|
+
return await func(*args, **kwargs)
|
|
272
|
+
except (TimeoutError, NetworkError) as e:
|
|
273
|
+
if "Message is not modified" in str(e):
|
|
274
|
+
return None
|
|
275
|
+
if attempt < max_retries - 1:
|
|
276
|
+
wait_time = 2**attempt # 1s, 2s, 4s
|
|
277
|
+
logger.warning(
|
|
278
|
+
f"Telegram API network error (attempt {attempt + 1}/{max_retries}): {e}. Retrying in {wait_time}s..."
|
|
279
|
+
)
|
|
280
|
+
await asyncio.sleep(wait_time)
|
|
281
|
+
else:
|
|
282
|
+
logger.error(
|
|
283
|
+
f"Telegram API failed after {max_retries} attempts: {e}"
|
|
284
|
+
)
|
|
285
|
+
raise
|
|
286
|
+
except RetryAfter as e:
|
|
287
|
+
# Telegram explicitly tells us to wait (PTB_TIMEDELTA: retry_after is timedelta)
|
|
288
|
+
from datetime import timedelta
|
|
289
|
+
|
|
290
|
+
retry_after = e.retry_after
|
|
291
|
+
if isinstance(retry_after, timedelta):
|
|
292
|
+
wait_secs = retry_after.total_seconds()
|
|
293
|
+
else:
|
|
294
|
+
wait_secs = float(retry_after)
|
|
295
|
+
|
|
296
|
+
logger.warning(f"Rate limited by Telegram, waiting {wait_secs}s...")
|
|
297
|
+
await asyncio.sleep(wait_secs)
|
|
298
|
+
# We don't increment attempt here, as this is a specific instruction
|
|
299
|
+
return await func(*args, **kwargs)
|
|
300
|
+
except TelegramError as e:
|
|
301
|
+
# Non-network Telegram errors
|
|
302
|
+
err_lower = str(e).lower()
|
|
303
|
+
if "message is not modified" in err_lower:
|
|
304
|
+
return None
|
|
305
|
+
# Best-effort no-op cases (common during chat cleanup / /clear).
|
|
306
|
+
if any(
|
|
307
|
+
x in err_lower
|
|
308
|
+
for x in [
|
|
309
|
+
"message to edit not found",
|
|
310
|
+
"message to delete not found",
|
|
311
|
+
"message can't be deleted",
|
|
312
|
+
"message can't be edited",
|
|
313
|
+
"not enough rights to delete",
|
|
314
|
+
]
|
|
315
|
+
):
|
|
316
|
+
return None
|
|
317
|
+
if "Can't parse entities" in str(e) and kwargs.get("parse_mode"):
|
|
318
|
+
logger.warning("Markdown failed, retrying without parse_mode")
|
|
319
|
+
kwargs["parse_mode"] = None
|
|
320
|
+
return await func(*args, **kwargs)
|
|
321
|
+
raise
|
|
322
|
+
|
|
323
|
+
async def _send_message_raw(
|
|
324
|
+
self,
|
|
325
|
+
chat_id: str,
|
|
326
|
+
text: str,
|
|
327
|
+
reply_to: str | None = None,
|
|
328
|
+
parse_mode: str | None = "MarkdownV2",
|
|
329
|
+
message_thread_id: str | None = None,
|
|
330
|
+
) -> str:
|
|
331
|
+
"""Send a message to a chat."""
|
|
332
|
+
app = self._application
|
|
333
|
+
if not app or not app.bot:
|
|
334
|
+
raise RuntimeError("Telegram application or bot not initialized")
|
|
335
|
+
|
|
336
|
+
async def _do_send(parse_mode=parse_mode):
|
|
337
|
+
bot = app.bot
|
|
338
|
+
kwargs: dict[str, Any] = {
|
|
339
|
+
"chat_id": chat_id,
|
|
340
|
+
"text": text,
|
|
341
|
+
"reply_to_message_id": int(reply_to) if reply_to else None,
|
|
342
|
+
"parse_mode": parse_mode,
|
|
343
|
+
}
|
|
344
|
+
if message_thread_id is not None:
|
|
345
|
+
kwargs["message_thread_id"] = int(message_thread_id)
|
|
346
|
+
msg = await bot.send_message(**kwargs)
|
|
347
|
+
return str(msg.message_id)
|
|
348
|
+
|
|
349
|
+
return await self._with_retry(_do_send, parse_mode=parse_mode)
|
|
350
|
+
|
|
351
|
+
async def send_message(
|
|
352
|
+
self,
|
|
353
|
+
chat_id: str,
|
|
354
|
+
text: str,
|
|
355
|
+
reply_to: str | None = None,
|
|
356
|
+
parse_mode: str | None = "MarkdownV2",
|
|
357
|
+
message_thread_id: str | None = None,
|
|
358
|
+
) -> str:
|
|
359
|
+
"""Send a message to a chat."""
|
|
360
|
+
return await self._send_message_raw(
|
|
361
|
+
chat_id,
|
|
362
|
+
text,
|
|
363
|
+
reply_to,
|
|
364
|
+
parse_mode,
|
|
365
|
+
message_thread_id,
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
async def _edit_message_raw(
|
|
369
|
+
self,
|
|
370
|
+
chat_id: str,
|
|
371
|
+
message_id: str,
|
|
372
|
+
text: str,
|
|
373
|
+
parse_mode: str | None = "MarkdownV2",
|
|
374
|
+
) -> None:
|
|
375
|
+
"""Edit an existing message."""
|
|
376
|
+
app = self._application
|
|
377
|
+
if not app or not app.bot:
|
|
378
|
+
raise RuntimeError("Telegram application or bot not initialized")
|
|
379
|
+
|
|
380
|
+
async def _do_edit(parse_mode=parse_mode):
|
|
381
|
+
bot = app.bot
|
|
382
|
+
await bot.edit_message_text(
|
|
383
|
+
chat_id=chat_id,
|
|
384
|
+
message_id=int(message_id),
|
|
385
|
+
text=text,
|
|
386
|
+
parse_mode=parse_mode,
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
await self._with_retry(_do_edit, parse_mode=parse_mode)
|
|
390
|
+
|
|
391
|
+
async def edit_message(
|
|
392
|
+
self,
|
|
393
|
+
chat_id: str,
|
|
394
|
+
message_id: str,
|
|
395
|
+
text: str,
|
|
396
|
+
parse_mode: str | None = "MarkdownV2",
|
|
397
|
+
) -> None:
|
|
398
|
+
"""Edit an existing message."""
|
|
399
|
+
await self._edit_message_raw(chat_id, message_id, text, parse_mode)
|
|
400
|
+
|
|
401
|
+
async def _delete_message_raw(
|
|
402
|
+
self,
|
|
403
|
+
chat_id: str,
|
|
404
|
+
message_id: str,
|
|
405
|
+
) -> None:
|
|
406
|
+
"""Delete a message from a chat."""
|
|
407
|
+
app = self._application
|
|
408
|
+
if not app or not app.bot:
|
|
409
|
+
raise RuntimeError("Telegram application or bot not initialized")
|
|
410
|
+
|
|
411
|
+
async def _do_delete():
|
|
412
|
+
bot = app.bot
|
|
413
|
+
await bot.delete_message(chat_id=chat_id, message_id=int(message_id))
|
|
414
|
+
|
|
415
|
+
await self._with_retry(_do_delete)
|
|
416
|
+
|
|
417
|
+
async def delete_message(
|
|
418
|
+
self,
|
|
419
|
+
chat_id: str,
|
|
420
|
+
message_id: str,
|
|
421
|
+
) -> None:
|
|
422
|
+
"""Delete a message from a chat."""
|
|
423
|
+
await self._delete_message_raw(chat_id, message_id)
|
|
424
|
+
|
|
425
|
+
async def _delete_messages_raw(self, chat_id: str, message_ids: list[str]) -> None:
|
|
426
|
+
"""Delete multiple messages (best-effort)."""
|
|
427
|
+
if not message_ids:
|
|
428
|
+
return
|
|
429
|
+
app = self._application
|
|
430
|
+
if not app or not app.bot:
|
|
431
|
+
raise RuntimeError("Telegram application or bot not initialized")
|
|
432
|
+
|
|
433
|
+
# PTB supports bulk deletion via delete_messages; fall back to per-message.
|
|
434
|
+
bot = app.bot
|
|
435
|
+
if hasattr(bot, "delete_messages"):
|
|
436
|
+
|
|
437
|
+
async def _do_bulk():
|
|
438
|
+
mids = []
|
|
439
|
+
for mid in message_ids:
|
|
440
|
+
try:
|
|
441
|
+
mids.append(int(mid))
|
|
442
|
+
except Exception:
|
|
443
|
+
continue
|
|
444
|
+
if not mids:
|
|
445
|
+
return None
|
|
446
|
+
# delete_messages accepts a sequence of ints (up to 100).
|
|
447
|
+
await bot.delete_messages(chat_id=chat_id, message_ids=mids)
|
|
448
|
+
|
|
449
|
+
await self._with_retry(_do_bulk)
|
|
450
|
+
return
|
|
451
|
+
|
|
452
|
+
for mid in message_ids:
|
|
453
|
+
await self._delete_message_raw(chat_id, mid)
|
|
454
|
+
|
|
455
|
+
async def delete_messages(self, chat_id: str, message_ids: list[str]) -> None:
|
|
456
|
+
"""Delete multiple messages (best-effort)."""
|
|
457
|
+
await self._delete_messages_raw(chat_id, message_ids)
|
|
458
|
+
|
|
459
|
+
async def queue_send_message(
|
|
460
|
+
self,
|
|
461
|
+
chat_id: str,
|
|
462
|
+
text: str,
|
|
463
|
+
reply_to: str | None = None,
|
|
464
|
+
parse_mode: str | None = "MarkdownV2",
|
|
465
|
+
fire_and_forget: bool = True,
|
|
466
|
+
message_thread_id: str | None = None,
|
|
467
|
+
) -> str | None:
|
|
468
|
+
"""Enqueue a message to be sent (using limiter)."""
|
|
469
|
+
return await self._outbox.queue_send_message(
|
|
470
|
+
chat_id,
|
|
471
|
+
text,
|
|
472
|
+
reply_to,
|
|
473
|
+
parse_mode,
|
|
474
|
+
fire_and_forget,
|
|
475
|
+
message_thread_id,
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
async def queue_edit_message(
|
|
479
|
+
self,
|
|
480
|
+
chat_id: str,
|
|
481
|
+
message_id: str,
|
|
482
|
+
text: str,
|
|
483
|
+
parse_mode: str | None = "MarkdownV2",
|
|
484
|
+
fire_and_forget: bool = True,
|
|
485
|
+
) -> None:
|
|
486
|
+
"""Enqueue a message edit."""
|
|
487
|
+
await self._outbox.queue_edit_message(
|
|
488
|
+
chat_id,
|
|
489
|
+
message_id,
|
|
490
|
+
text,
|
|
491
|
+
parse_mode,
|
|
492
|
+
fire_and_forget,
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
async def queue_delete_message(
|
|
496
|
+
self,
|
|
497
|
+
chat_id: str,
|
|
498
|
+
message_id: str,
|
|
499
|
+
fire_and_forget: bool = True,
|
|
500
|
+
) -> None:
|
|
501
|
+
"""Enqueue a message delete."""
|
|
502
|
+
await self._outbox.queue_delete_message(chat_id, message_id, fire_and_forget)
|
|
503
|
+
|
|
504
|
+
async def queue_delete_messages(
|
|
505
|
+
self,
|
|
506
|
+
chat_id: str,
|
|
507
|
+
message_ids: list[str],
|
|
508
|
+
fire_and_forget: bool = True,
|
|
509
|
+
) -> None:
|
|
510
|
+
"""Enqueue a bulk delete (if supported) or a sequence of deletes."""
|
|
511
|
+
await self._outbox.queue_delete_messages(
|
|
512
|
+
chat_id,
|
|
513
|
+
message_ids,
|
|
514
|
+
fire_and_forget,
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
def fire_and_forget(self, task: Awaitable[Any]) -> None:
|
|
518
|
+
"""Execute a coroutine without awaiting it."""
|
|
519
|
+
self._outbox.fire_and_forget(task)
|
|
520
|
+
|
|
521
|
+
def on_message(
|
|
522
|
+
self,
|
|
523
|
+
handler: Callable[[IncomingMessage], Awaitable[None]],
|
|
524
|
+
) -> None:
|
|
525
|
+
"""Register a message handler callback."""
|
|
526
|
+
self._message_handler = handler
|
|
527
|
+
|
|
528
|
+
@property
|
|
529
|
+
def is_connected(self) -> bool:
|
|
530
|
+
"""Check if connected."""
|
|
531
|
+
return self._connected
|
|
532
|
+
|
|
533
|
+
async def _on_start_command(
|
|
534
|
+
self, update: Update, context: ContextTypes.DEFAULT_TYPE
|
|
535
|
+
) -> None:
|
|
536
|
+
"""Handle /start command."""
|
|
537
|
+
if update.message:
|
|
538
|
+
await update.message.reply_text("👋 Hello! I am the Claude Code Proxy Bot.")
|
|
539
|
+
# We can also treat this as a message if we want it to trigger something
|
|
540
|
+
await self._on_telegram_message(update, context)
|
|
541
|
+
|
|
542
|
+
async def _on_telegram_message(
|
|
543
|
+
self, update: Update, context: ContextTypes.DEFAULT_TYPE
|
|
544
|
+
) -> None:
|
|
545
|
+
"""Handle incoming updates."""
|
|
546
|
+
if (
|
|
547
|
+
not update.message
|
|
548
|
+
or not update.message.text
|
|
549
|
+
or not update.effective_user
|
|
550
|
+
or not update.effective_chat
|
|
551
|
+
):
|
|
552
|
+
return
|
|
553
|
+
|
|
554
|
+
user_id = str(update.effective_user.id)
|
|
555
|
+
chat_id = str(update.effective_chat.id)
|
|
556
|
+
|
|
557
|
+
# Security check
|
|
558
|
+
if self.allowed_user_id and user_id != str(self.allowed_user_id).strip():
|
|
559
|
+
logger.warning(f"Unauthorized access attempt from {user_id}")
|
|
560
|
+
return
|
|
561
|
+
|
|
562
|
+
message_id = str(update.message.message_id)
|
|
563
|
+
reply_to = (
|
|
564
|
+
str(update.message.reply_to_message.message_id)
|
|
565
|
+
if update.message.reply_to_message
|
|
566
|
+
else None
|
|
567
|
+
)
|
|
568
|
+
thread_id = (
|
|
569
|
+
str(update.message.message_thread_id)
|
|
570
|
+
if getattr(update.message, "message_thread_id", None) is not None
|
|
571
|
+
else None
|
|
572
|
+
)
|
|
573
|
+
raw_text = update.message.text or ""
|
|
574
|
+
if self._log_raw_messaging_content:
|
|
575
|
+
text_preview = raw_text[:80]
|
|
576
|
+
if len(raw_text) > 80:
|
|
577
|
+
text_preview += "..."
|
|
578
|
+
logger.info(
|
|
579
|
+
"TELEGRAM_MSG: chat_id={} message_id={} reply_to={} text_preview={!r}",
|
|
580
|
+
chat_id,
|
|
581
|
+
message_id,
|
|
582
|
+
reply_to,
|
|
583
|
+
text_preview,
|
|
584
|
+
)
|
|
585
|
+
else:
|
|
586
|
+
logger.info(
|
|
587
|
+
"TELEGRAM_MSG: chat_id={} message_id={} reply_to={} text_len={}",
|
|
588
|
+
chat_id,
|
|
589
|
+
message_id,
|
|
590
|
+
reply_to,
|
|
591
|
+
len(raw_text),
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
if not self._message_handler:
|
|
595
|
+
return
|
|
596
|
+
|
|
597
|
+
incoming = IncomingMessage(
|
|
598
|
+
text=update.message.text,
|
|
599
|
+
chat_id=chat_id,
|
|
600
|
+
user_id=user_id,
|
|
601
|
+
message_id=message_id,
|
|
602
|
+
platform="telegram",
|
|
603
|
+
reply_to_message_id=reply_to,
|
|
604
|
+
message_thread_id=thread_id,
|
|
605
|
+
raw_event=update,
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
try:
|
|
609
|
+
await self._message_handler(incoming)
|
|
610
|
+
except Exception as e:
|
|
611
|
+
if self._log_api_error_tracebacks:
|
|
612
|
+
logger.error("Error handling message: {}", e)
|
|
613
|
+
else:
|
|
614
|
+
logger.error("Error handling message: exc_type={}", type(e).__name__)
|
|
615
|
+
with contextlib.suppress(Exception):
|
|
616
|
+
await self.send_message(
|
|
617
|
+
chat_id,
|
|
618
|
+
f"❌ *{escape_md_v2('Error:')}* {escape_md_v2(format_user_error_preview(e))}",
|
|
619
|
+
reply_to=incoming.message_id,
|
|
620
|
+
message_thread_id=thread_id,
|
|
621
|
+
parse_mode="MarkdownV2",
|
|
622
|
+
)
|
|
623
|
+
|
|
624
|
+
async def _on_telegram_voice(
|
|
625
|
+
self, update: Update, context: ContextTypes.DEFAULT_TYPE
|
|
626
|
+
) -> None:
|
|
627
|
+
"""Handle incoming voice messages."""
|
|
628
|
+
message = update.message
|
|
629
|
+
effective_user = update.effective_user
|
|
630
|
+
effective_chat = update.effective_chat
|
|
631
|
+
if (
|
|
632
|
+
message is None
|
|
633
|
+
or message.voice is None
|
|
634
|
+
or effective_user is None
|
|
635
|
+
or effective_chat is None
|
|
636
|
+
):
|
|
637
|
+
return
|
|
638
|
+
voice = message.voice
|
|
639
|
+
|
|
640
|
+
async def _reply_text(text: str) -> None:
|
|
641
|
+
await message.reply_text(text)
|
|
642
|
+
|
|
643
|
+
if await self._voice_flow.reply_if_disabled(_reply_text):
|
|
644
|
+
return
|
|
645
|
+
|
|
646
|
+
user_id = str(effective_user.id)
|
|
647
|
+
chat_id = str(effective_chat.id)
|
|
648
|
+
|
|
649
|
+
if self.allowed_user_id and user_id != str(self.allowed_user_id).strip():
|
|
650
|
+
logger.warning(f"Unauthorized voice access attempt from {user_id}")
|
|
651
|
+
return
|
|
652
|
+
|
|
653
|
+
thread_id = (
|
|
654
|
+
str(message.message_thread_id)
|
|
655
|
+
if getattr(message, "message_thread_id", None) is not None
|
|
656
|
+
else None
|
|
657
|
+
)
|
|
658
|
+
message_id = str(message.message_id)
|
|
659
|
+
reply_to = (
|
|
660
|
+
str(message.reply_to_message.message_id)
|
|
661
|
+
if message.reply_to_message
|
|
662
|
+
else None
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
async def _download_to(tmp_path) -> None:
|
|
666
|
+
tg_file = await context.bot.get_file(voice.file_id)
|
|
667
|
+
await tg_file.download_to_drive(custom_path=str(tmp_path))
|
|
668
|
+
|
|
669
|
+
await self._voice_flow.handle(
|
|
670
|
+
VoiceNoteRequest(
|
|
671
|
+
platform="telegram",
|
|
672
|
+
chat_id=chat_id,
|
|
673
|
+
user_id=user_id,
|
|
674
|
+
message_id=message_id,
|
|
675
|
+
raw_event=update,
|
|
676
|
+
content_type=voice.mime_type or "audio/ogg",
|
|
677
|
+
temp_suffix=audio_suffix_from_metadata(content_type=voice.mime_type),
|
|
678
|
+
status_text=format_status("⏳", "Transcribing voice note..."),
|
|
679
|
+
status_parse_mode="MarkdownV2",
|
|
680
|
+
message_thread_id=thread_id,
|
|
681
|
+
reply_to_message_id=reply_to,
|
|
682
|
+
download_to=_download_to,
|
|
683
|
+
reply_text=_reply_text,
|
|
684
|
+
),
|
|
685
|
+
message_handler=self._message_handler,
|
|
686
|
+
queue_send_message=self.queue_send_message,
|
|
687
|
+
queue_delete_message=self.queue_delete_message,
|
|
688
|
+
)
|