Skip to content

Telegram Client

llm_expose.clients.telegram

Telegram client adapter using python-telegram-bot.

TelegramClient

Bases: BaseClient


              flowchart TD
              llm_expose.clients.telegram.TelegramClient[TelegramClient]
              llm_expose.clients.base.BaseClient[BaseClient]

                              llm_expose.clients.base.BaseClient --> llm_expose.clients.telegram.TelegramClient
                


              click llm_expose.clients.telegram.TelegramClient href "" "llm_expose.clients.telegram.TelegramClient"
              click llm_expose.clients.base.BaseClient href "" "llm_expose.clients.base.BaseClient"
            

Messaging client adapter for Telegram.

Listens for incoming text messages and commands via the Telegram Bot API (long-polling) and forwards them to the registered LLM handler.

Parameters:

Name Type Description Default
config TelegramClientConfig

Telegram-specific configuration (bot token).

required
handler MessageHandler

Async callable that receives the user's text and returns the LLM's reply.

required
Source code in llm_expose/clients/telegram.py
 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
class TelegramClient(BaseClient):
    """Messaging client adapter for Telegram.

    Listens for incoming text messages and commands via the Telegram Bot API
    (long-polling) and forwards them to the registered LLM handler.

    Args:
        config: Telegram-specific configuration (bot token).
        handler: Async callable that receives the user's text and returns the
            LLM's reply.
    """

    def __init__(self, config: TelegramClientConfig, handler: LLMHandler) -> None:
        super().__init__(handler)
        self._config = config
        self._app: Application | None = None
        self._stop_event: asyncio.Event | None = None
        self._approval_messages: dict[str, tuple[str, str]] = {}

    # ------------------------------------------------------------------
    # Telegram update handlers
    # ------------------------------------------------------------------

    async def _reply_text_safe(self, message, text: str, **kwargs):
        """Send a reply using Markdown; retry as plain text on parse errors."""
        try:
            # Escape special characters in Telegram markdown
            for char in RESERVED_PARSE_CHARACTERS:
                text = text.replace(char, f"\\{char}")
            return await message.reply_text(
                text, parse_mode=MARKDOWN_PARSE_MODE, **kwargs
            )
        except BadRequest as exc:
            if "Can't parse entities" not in str(exc):
                raise
            logger.warning(
                "Markdown parse failed in reply_text, retrying plain text: %s", exc
            )
            return await message.reply_text(text, **kwargs)

    async def _edit_message_text_safe(self, query, text: str, **kwargs) -> None:
        """Edit a message using Markdown; retry as plain text on parse errors."""
        try:
            await query.edit_message_text(
                text, parse_mode=MARKDOWN_PARSE_MODE, **kwargs
            )
        except BadRequest as exc:
            if "Can't parse entities" not in str(exc):
                raise
            logger.warning(
                "Markdown parse failed in edit_message_text, retrying plain text: %s",
                exc,
            )
            await query.edit_message_text(text, **kwargs)

    async def _send_message_safe(self, bot, chat_id: str, text: str, **kwargs) -> None:
        """Send a message using Markdown; retry as plain text on parse errors."""
        try:
            await bot.send_message(
                chat_id=chat_id,
                text=text,
                parse_mode=MARKDOWN_PARSE_MODE,
                **kwargs,
            )
        except BadRequest as exc:
            if "Can't parse entities" not in str(exc):
                raise
            logger.warning(
                "Markdown parse failed in send_message, retrying plain text: %s", exc
            )
            await bot.send_message(chat_id=chat_id, text=text, **kwargs)

    async def _edit_chat_message_text_safe(
        self,
        bot,
        chat_id: str,
        message_id: str,
        text: str,
        **kwargs,
    ) -> None:
        """Edit a chat message by ID using Markdown with plain-text fallback."""
        message_id_int = int(message_id)
        try:
            await bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id_int,
                text=text,
                parse_mode=MARKDOWN_PARSE_MODE,
                **kwargs,
            )
        except BadRequest as exc:
            if "Can't parse entities" not in str(exc):
                raise
            logger.warning(
                "Markdown parse failed in edit_message_text by id, retrying plain text: %s",
                exc,
            )
            await bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id_int,
                text=text,
                **kwargs,
            )

    @property
    def _orchestrator(self):
        """Return the bound Orchestrator instance if one is registered as handler, else None."""
        bound_self = getattr(self._handler, "__self__", None)
        if bound_self is not None and bound_self.__class__.__name__ == "Orchestrator":
            return bound_self
        return None

    async def _handle_command(
        self, update: Update, context: ContextTypes.DEFAULT_TYPE
    ) -> None:
        """Catch-all handler for slash-commands delegated to orchestrator.

        Extracts the bare command name from the incoming message and delegates
        to ``Orchestrator.handle_admin_command()``.  Any client that integrates
        admin commands only needs to hook into that single orchestrator method.
        """
        if not update.message:
            return

        raw = (update.message.text or "").strip()
        # Handle both /cmd and /cmd@botname forms
        command = (
            raw.lstrip("/").split("@")[0].split()[0].lower()
            if raw.startswith("/")
            else ""
        )
        args = list(context.args or [])
        chat_id = str(update.message.chat.id)

        orch = self._orchestrator
        if orch is not None:
            response = await orch.handle_admin_command(chat_id, command, args)
        else:
            response = "Admin commands are only available in orchestrator mode."

        await self._reply_text_safe(update.message, response)

    async def _handle_message(
        self, update: Update, context: ContextTypes.DEFAULT_TYPE
    ) -> None:
        """Handle incoming text messages by delegating to the LLM handler."""
        if not update.message:
            return

        user_text = update.message.text or update.message.caption or ""
        image_urls = await self._extract_image_data_urls(update, context)
        if not user_text and not image_urls:
            return

        chat_id = str(update.message.chat.id)
        logger.info(
            "Received message from user %s in chat %s",
            update.effective_user,
            chat_id,
        )

        # Show a typing action while waiting for the LLM
        if update.message.chat:
            await context.bot.send_chat_action(
                chat_id=update.message.chat.id, action="typing"
            )

        try:
            # Keep backward compatibility with one-argument handlers used in
            # tests/custom integrations, but pass channel context when the
            # orchestrator handler is registered.
            bound_self = getattr(self._handler, "__self__", None)
            if (
                bound_self is not None
                and bound_self.__class__.__name__ == "Orchestrator"
            ):
                message_content = build_user_content(user_text, image_urls=image_urls)
                reply = await self._handler(
                    chat_id,
                    user_text,
                    message_content=message_content,
                    message_context={
                        "platform": "telegram",
                        "chat_type": getattr(update.message.chat, "type", None),
                        "effective_user_id": getattr(update.effective_user, "id", None),
                    },
                )
            else:
                reply = await self._handler(user_text)
        except Exception as exc:
            logger.exception("Error from LLM handler: %s", exc)
            reply = "⚠️ Sorry, I encountered an error. Please try again."

        # Check if reply is a structured MessageResponse with approval metadata
        if isinstance(reply, MessageResponse):
            if reply.approval_id:
                # Create inline keyboard with Approve/Reject buttons
                keyboard = [
                    [
                        InlineKeyboardButton(
                            "✅ Approve", callback_data=f"approve:{reply.approval_id}"
                        ),
                        InlineKeyboardButton(
                            "❌ Reject", callback_data=f"reject:{reply.approval_id}"
                        ),
                    ]
                ]
                reply_markup = InlineKeyboardMarkup(keyboard)
                approval_message = await self._reply_text_safe(
                    update.message,
                    reply.content,
                    reply_markup=reply_markup,
                )
                if (
                    approval_message is not None
                    and getattr(approval_message, "message_id", None) is not None
                ):
                    self._approval_messages[reply.approval_id] = (
                        chat_id,
                        str(approval_message.message_id),
                    )
                if reply.images:
                    await self._send_images_with_bot(context.bot, chat_id, reply.images)
            else:
                # No approval needed, just send the content
                await self._reply_text_safe(
                    update.message,
                    reply.content,
                )
                if reply.images:
                    await self._send_images_with_bot(context.bot, chat_id, reply.images)
        else:
            # Plain string response (backward compatibility)
            await self._reply_text_safe(update.message, reply)

    @staticmethod
    def _photo_payload_from_url(image_url: str) -> str | InputFile:
        """Convert a URL/data URL into a Telegram send_photo payload."""
        if not image_url.startswith("data:"):
            return image_url

        header, encoded = image_url.split(",", 1)
        if ";base64" not in header:
            raise ValueError("Unsupported non-base64 data URL")

        media_type = "image/jpeg"
        if header.startswith("data:"):
            media_type = header[5:].split(";", 1)[0] or media_type

        payload = base64.b64decode(encoded)
        extension = mimetypes.guess_extension(media_type) or ".jpg"
        return InputFile(payload, filename=f"reference{extension}")

    async def _send_images_with_bot(
        self, bot: Any, chat_id: str, image_urls: list[str]
    ) -> list[dict[str, str]]:
        """Send images using a specific bot instance and collect metadata."""
        sent: list[dict[str, str]] = []
        for image_url in image_urls:
            try:
                payload = self._photo_payload_from_url(image_url)
                message = await bot.send_photo(chat_id=chat_id, photo=payload)
                sent.append(
                    {
                        "message_id": str(message.message_id),
                        "timestamp": dt.now(UTC).isoformat(),
                    }
                )
            except Exception as exc:
                logger.warning("Failed to send reference image: %s", exc)
        return sent

    async def _extract_image_data_urls(
        self,
        update: Update,
        context: ContextTypes.DEFAULT_TYPE,
    ) -> list[str]:
        """Extract Telegram photo attachments as data URLs."""
        if not update.message or not update.message.photo:
            return []

        image_urls: list[str] = []
        # Telegram provides sizes from smallest to largest.
        best_photo = update.message.photo[-1]
        try:
            telegram_file = await context.bot.get_file(best_photo.file_id)
            payload: bytes | None = None

            download_as_bytearray = getattr(
                telegram_file, "download_as_bytearray", None
            )
            if callable(download_as_bytearray):
                payload = bytes(await download_as_bytearray())

            if payload:
                encoded = base64.b64encode(payload).decode("ascii")
                image_urls.append(f"data:image/jpeg;base64,{encoded}")
        except Exception as exc:
            logger.warning("Failed to extract photo attachment: %s", exc)

        return image_urls

    async def _handle_callback_query(
        self, update: Update, context: ContextTypes.DEFAULT_TYPE
    ) -> None:
        """Handle button press callbacks for approval decisions."""
        if not update.callback_query:
            return

        query = update.callback_query
        chat_id = str(query.message.chat.id) if query.message else None

        if not chat_id or not query.data:
            await query.answer("Invalid request.")
            return

        # Parse callback data: format is "approve:approval_id" or "reject:approval_id"
        try:
            decision, approval_id = query.data.split(":", 1)
        except ValueError:
            await query.answer("Invalid callback data.")
            return

        if decision not in ("approve", "reject"):
            await query.answer("Unknown action.")
            return

        # Answer the callback query immediately to remove button loading state
        await query.answer("Processing...")

        # Format as text command and send to orchestrator
        command_text = f"{decision} {approval_id}"
        logger.info(
            "Button press from user %s in chat %s: %s",
            update.effective_user,
            chat_id,
            command_text,
        )

        try:
            bound_self = getattr(self._handler, "__self__", None)
            if (
                bound_self is not None
                and bound_self.__class__.__name__ == "Orchestrator"
            ):
                reply = await self._handler(
                    chat_id,
                    command_text,
                    message_context={
                        "platform": "telegram",
                        "chat_type": (
                            getattr(query.message.chat, "type", None)
                            if query.message
                            else None
                        ),
                        "effective_user_id": getattr(update.effective_user, "id", None),
                    },
                )
            else:
                reply = await self._handler(command_text)
        except Exception as exc:
            logger.exception("Error from LLM handler during callback: %s", exc)
            reply = "⚠️ Sorry, I encountered an error processing your decision."

        # Extract content if reply is MessageResponse
        reply_text = reply.content if isinstance(reply, MessageResponse) else reply

        self._approval_messages.pop(approval_id, None)

        # Keep final responses as normal messages after approval handling.
        if chat_id and reply_text:
            await self._send_message_safe(context.bot, chat_id, str(reply_text))

    async def notify_tool_status(
        self,
        user_id: str,
        status: str,
        tool_name: str,
        *,
        approval_id: str | None = None,
        detail: str | None = None,
    ) -> None:
        """Publish interim tool lifecycle feedback to Telegram users."""
        if status == "running":
            text = f"🔨 Running: `{tool_name}`"
        elif status == "failed":
            text = f"❌ Failed: `{tool_name}`"
            if detail:
                text += f"\n{detail}"
        else:
            return

        bot = self._app.bot if self._app is not None else None

        if (
            status == "running"
            and approval_id
            and approval_id in self._approval_messages
            and bot is not None
        ):
            approval_chat_id, approval_message_id = self._approval_messages[approval_id]
            try:
                await self._edit_chat_message_text_safe(
                    bot,
                    approval_chat_id,
                    approval_message_id,
                    text,
                )
                return
            except Exception as exc:
                logger.warning(
                    "Could not edit approval message for running status: %s", exc
                )

        if bot is not None:
            await self._send_message_safe(bot, user_id, text)
            return

        await self.send_message(user_id, text)

    # ------------------------------------------------------------------
    # Lifecycle
    # ------------------------------------------------------------------

    async def start(self) -> None:
        """Build the Telegram application and start polling for updates."""
        self._stop_event = asyncio.Event()
        self._app = Application.builder().token(self._config.bot_token).build()

        # Catch-all for slash commands (/start, /status, /clear, /tools, /reload, …).
        self._app.add_handler(MessageHandler(filters.COMMAND, self._handle_command))
        self._app.add_handler(
            MessageHandler(
                (filters.TEXT | filters.PHOTO) & ~filters.COMMAND, self._handle_message
            )
        )
        self._app.add_handler(CallbackQueryHandler(self._handle_callback_query))

        logger.info("Starting Telegram bot (polling)…")
        await self._app.initialize()
        await self._app.start()
        updater = self._app.updater
        if updater is None:
            raise RuntimeError("Telegram updater is unavailable")
        await updater.start_polling(drop_pending_updates=True)
        logger.info("Telegram bot is running. Press Ctrl+C to stop.")

        # Keep running until stop() signals shutdown.
        await self._stop_event.wait()

    async def send_message(self, user_id: str, text: str) -> dict:
        """Send a direct message to a specific user.

        Uses the Markdown parsing with fallback to plain text on parse errors,
        consistent with reply and edit methods.

        Args:
            user_id: Telegram chat_id as string.
            text: Message text to send.

        Returns:
            Dict with keys: message_id, timestamp, status, user_id.

        Raises:
            RuntimeError: If the Telegram app cannot be initialized.
            BadRequest: If send fails (invalid chat_id, permissions, etc.).
        """
        # Initialize the app if not already done
        if self._app is None:
            self._app = Application.builder().token(self._config.bot_token).build()
            await self._app.initialize()

        try:
            # Try to send with Markdown formatting first
            try:
                message = await self._app.bot.send_message(
                    chat_id=user_id,
                    text=text,
                    parse_mode=MARKDOWN_PARSE_MODE,
                )
            except BadRequest as exc:
                if "Can't parse entities" not in str(exc):
                    raise
                # Retry without Markdown on parse error
                logger.warning(
                    "Markdown parse failed in send_message, retrying plain text: %s",
                    exc,
                )
                message = await self._app.bot.send_message(chat_id=user_id, text=text)

            return {
                "message_id": str(message.message_id),
                "timestamp": dt.now(UTC).isoformat(),
                "status": "sent",
                "user_id": user_id,
            }
        except BadRequest as exc:
            logger.error(
                "Failed to send message to user %s: %s",
                user_id,
                exc,
            )
            raise

    async def send_images(self, user_id: str, image_urls: list[str]) -> dict:
        """Send one or more images to a specific Telegram chat."""
        if self._app is None:
            self._app = Application.builder().token(self._config.bot_token).build()
            await self._app.initialize()

        sent_items = await self._send_images_with_bot(
            self._app.bot, user_id, image_urls
        )
        return {
            "status": "sent",
            "user_id": user_id,
            "count": len(sent_items),
            "items": sent_items,
        }

    async def send_file(self, user_id: str, file_path: str) -> dict:
        """Send a local file to a specific Telegram chat as a document."""
        resolved_path = Path(file_path).expanduser()
        if not resolved_path.exists() or not resolved_path.is_file():
            raise FileNotFoundError(f"File not found: {file_path}")

        if self._app is None:
            self._app = Application.builder().token(self._config.bot_token).build()
            await self._app.initialize()

        try:
            with resolved_path.open("rb") as handle:
                payload = InputFile(handle, filename=resolved_path.name)
                message = await self._app.bot.send_document(
                    chat_id=user_id,
                    document=payload,
                )

            document = getattr(message, "document", None)
            file_id = getattr(document, "file_id", None)
            return {
                "message_id": str(message.message_id),
                "timestamp": dt.now(UTC).isoformat(),
                "status": "sent",
                "user_id": user_id,
                "file_name": resolved_path.name,
                "file_id": str(file_id) if file_id else None,
            }
        except BadRequest as exc:
            logger.error(
                "Failed to send file to user %s: %s",
                user_id,
                exc,
            )
            raise

    async def stop(self) -> None:
        """Stop polling and shut down the Telegram application."""
        if self._app is None:
            return

        if self._stop_event is not None:
            self._stop_event.set()

        logger.info("Stopping Telegram bot…")
        updater = self._app.updater
        if updater is not None:
            await updater.stop()
        await self._app.stop()
        await self._app.shutdown()
        self._app = None
        self._stop_event = None

notify_tool_status(user_id, status, tool_name, *, approval_id=None, detail=None) async

Publish interim tool lifecycle feedback to Telegram users.

Source code in llm_expose/clients/telegram.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
async def notify_tool_status(
    self,
    user_id: str,
    status: str,
    tool_name: str,
    *,
    approval_id: str | None = None,
    detail: str | None = None,
) -> None:
    """Publish interim tool lifecycle feedback to Telegram users."""
    if status == "running":
        text = f"🔨 Running: `{tool_name}`"
    elif status == "failed":
        text = f"❌ Failed: `{tool_name}`"
        if detail:
            text += f"\n{detail}"
    else:
        return

    bot = self._app.bot if self._app is not None else None

    if (
        status == "running"
        and approval_id
        and approval_id in self._approval_messages
        and bot is not None
    ):
        approval_chat_id, approval_message_id = self._approval_messages[approval_id]
        try:
            await self._edit_chat_message_text_safe(
                bot,
                approval_chat_id,
                approval_message_id,
                text,
            )
            return
        except Exception as exc:
            logger.warning(
                "Could not edit approval message for running status: %s", exc
            )

    if bot is not None:
        await self._send_message_safe(bot, user_id, text)
        return

    await self.send_message(user_id, text)

send_file(user_id, file_path) async

Send a local file to a specific Telegram chat as a document.

Source code in llm_expose/clients/telegram.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
async def send_file(self, user_id: str, file_path: str) -> dict:
    """Send a local file to a specific Telegram chat as a document."""
    resolved_path = Path(file_path).expanduser()
    if not resolved_path.exists() or not resolved_path.is_file():
        raise FileNotFoundError(f"File not found: {file_path}")

    if self._app is None:
        self._app = Application.builder().token(self._config.bot_token).build()
        await self._app.initialize()

    try:
        with resolved_path.open("rb") as handle:
            payload = InputFile(handle, filename=resolved_path.name)
            message = await self._app.bot.send_document(
                chat_id=user_id,
                document=payload,
            )

        document = getattr(message, "document", None)
        file_id = getattr(document, "file_id", None)
        return {
            "message_id": str(message.message_id),
            "timestamp": dt.now(UTC).isoformat(),
            "status": "sent",
            "user_id": user_id,
            "file_name": resolved_path.name,
            "file_id": str(file_id) if file_id else None,
        }
    except BadRequest as exc:
        logger.error(
            "Failed to send file to user %s: %s",
            user_id,
            exc,
        )
        raise

send_images(user_id, image_urls) async

Send one or more images to a specific Telegram chat.

Source code in llm_expose/clients/telegram.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
async def send_images(self, user_id: str, image_urls: list[str]) -> dict:
    """Send one or more images to a specific Telegram chat."""
    if self._app is None:
        self._app = Application.builder().token(self._config.bot_token).build()
        await self._app.initialize()

    sent_items = await self._send_images_with_bot(
        self._app.bot, user_id, image_urls
    )
    return {
        "status": "sent",
        "user_id": user_id,
        "count": len(sent_items),
        "items": sent_items,
    }

send_message(user_id, text) async

Send a direct message to a specific user.

Uses the Markdown parsing with fallback to plain text on parse errors, consistent with reply and edit methods.

Parameters:

Name Type Description Default
user_id str

Telegram chat_id as string.

required
text str

Message text to send.

required

Returns:

Type Description
dict

Dict with keys: message_id, timestamp, status, user_id.

Raises:

Type Description
RuntimeError

If the Telegram app cannot be initialized.

BadRequest

If send fails (invalid chat_id, permissions, etc.).

Source code in llm_expose/clients/telegram.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
async def send_message(self, user_id: str, text: str) -> dict:
    """Send a direct message to a specific user.

    Uses the Markdown parsing with fallback to plain text on parse errors,
    consistent with reply and edit methods.

    Args:
        user_id: Telegram chat_id as string.
        text: Message text to send.

    Returns:
        Dict with keys: message_id, timestamp, status, user_id.

    Raises:
        RuntimeError: If the Telegram app cannot be initialized.
        BadRequest: If send fails (invalid chat_id, permissions, etc.).
    """
    # Initialize the app if not already done
    if self._app is None:
        self._app = Application.builder().token(self._config.bot_token).build()
        await self._app.initialize()

    try:
        # Try to send with Markdown formatting first
        try:
            message = await self._app.bot.send_message(
                chat_id=user_id,
                text=text,
                parse_mode=MARKDOWN_PARSE_MODE,
            )
        except BadRequest as exc:
            if "Can't parse entities" not in str(exc):
                raise
            # Retry without Markdown on parse error
            logger.warning(
                "Markdown parse failed in send_message, retrying plain text: %s",
                exc,
            )
            message = await self._app.bot.send_message(chat_id=user_id, text=text)

        return {
            "message_id": str(message.message_id),
            "timestamp": dt.now(UTC).isoformat(),
            "status": "sent",
            "user_id": user_id,
        }
    except BadRequest as exc:
        logger.error(
            "Failed to send message to user %s: %s",
            user_id,
            exc,
        )
        raise

start() async

Build the Telegram application and start polling for updates.

Source code in llm_expose/clients/telegram.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
async def start(self) -> None:
    """Build the Telegram application and start polling for updates."""
    self._stop_event = asyncio.Event()
    self._app = Application.builder().token(self._config.bot_token).build()

    # Catch-all for slash commands (/start, /status, /clear, /tools, /reload, …).
    self._app.add_handler(MessageHandler(filters.COMMAND, self._handle_command))
    self._app.add_handler(
        MessageHandler(
            (filters.TEXT | filters.PHOTO) & ~filters.COMMAND, self._handle_message
        )
    )
    self._app.add_handler(CallbackQueryHandler(self._handle_callback_query))

    logger.info("Starting Telegram bot (polling)…")
    await self._app.initialize()
    await self._app.start()
    updater = self._app.updater
    if updater is None:
        raise RuntimeError("Telegram updater is unavailable")
    await updater.start_polling(drop_pending_updates=True)
    logger.info("Telegram bot is running. Press Ctrl+C to stop.")

    # Keep running until stop() signals shutdown.
    await self._stop_event.wait()

stop() async

Stop polling and shut down the Telegram application.

Source code in llm_expose/clients/telegram.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
async def stop(self) -> None:
    """Stop polling and shut down the Telegram application."""
    if self._app is None:
        return

    if self._stop_event is not None:
        self._stop_event.set()

    logger.info("Stopping Telegram bot…")
    updater = self._app.updater
    if updater is not None:
        await updater.stop()
    await self._app.stop()
    await self._app.shutdown()
    self._app = None
    self._stop_event = None