# Telegram Bot

## Overview

MailTrixy can connect to a Telegram Bot to receive and respond to messages from Telegram users. All Telegram conversations appear in your unified inbox, and AI-powered replies work seamlessly on this channel. Telegram is free to use with no per-message costs, making it an excellent channel for businesses with a tech-savvy audience.

## Creating a Telegram Bot

Telegram bots are created through Telegram's official BotFather bot.

1. Open Telegram and search for @BotFather (the official bot management tool).
2. Start a conversation and send the command `/newbot`.
3. BotFather will ask you for a display name (e.g., "Acme Support") and a username (must end in "bot", e.g., "acme_support_bot").
4. Once created, BotFather will give you an HTTP API Token. This is your bot token — copy it immediately.

Optional but recommended customizations via BotFather:

- `/setdescription` — Set a description shown when users first open your bot.
- `/setabouttext` — Set the "About" text visible on the bot's profile.
- `/setuserpic` — Upload a profile picture for the bot (your company logo).
- `/setcommands` — Define bot commands (e.g., /start, /help, /status).

## Bot Token Setup

1. In MailTrixy, go to Settings → Channels → Telegram.
2. Paste the bot token from BotFather.
3. Click Test Connection. MailTrixy will call the Telegram API to verify the token is valid and retrieve your bot's details.
4. If successful, you will see the bot's username and display name confirmed on screen.

> Security: Your bot token grants full control of the bot. Never share it publicly. If you suspect it has been compromised, use `/revoke` in BotFather to generate a new token, then update it in MailTrixy.

## Webhook Configuration

Webhooks tell Telegram where to send incoming messages. MailTrixy sets this up automatically when you save the bot token, but you can also configure it manually.

Automatic setup: When you click Save in the Telegram channel settings, MailTrixy calls the Telegram `setWebhook` API with the URL:

    https://yourdomain.com/api/webhooks/telegram

Manual setup: If automatic setup fails (e.g., your server was temporarily unreachable), you can set the webhook manually by visiting this URL in your browser:

    https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://yourdomain.com/api/webhooks/telegram

You should see a JSON response: `{"ok": true, "result": true, "description": "Webhook was set"}`.

> Requirements: Your server must have a valid SSL certificate (HTTPS). Telegram does not send webhooks to HTTP URLs. Self-signed certificates are supported but require additional configuration.

## Message Handling

Once the webhook is active, MailTrixy processes Telegram messages as follows:

- Text messages: Displayed in the conversation thread. AI and keyword auto-reply rules can respond to these.
- Photos and files: Downloaded and attached to the conversation. The AI receives a note that an attachment was sent but does not analyze image content.
- Voice messages: Stored as audio attachments. Future versions will support speech-to-text transcription.
- Stickers and GIFs: Logged in the conversation but not processed by AI.

## The `/start` Command & @username Lookup

When a new user sends `/start` to your bot, MailTrixy immediately:

1. Creates a Contact for them (phone = Telegram user ID, `last_name` = `@username`).
2. Opens a Conversation with `channel_conversation_id` = Telegram chat id.
3. Sends the welcome reply back through the bot.

After this registration, you can compose a message to that user from Compose → Telegram → To: @theirusername. MailTrixy looks up the stored `@username` in Contacts and routes the message to the right chat id.

> If @username compose fails with "not found, user must send /start": the user has not yet sent `/start` to your specific bot. Telegram bots can only message users who initiated contact first — there is no way around this, it is a Telegram platform restriction.

## Outbound Formatting

Telegram's `parse_mode=HTML` accepts only a restricted tag subset. MailTrixy automatically sanitizes every outbound message to match:

- Allowed tags: `<b>`, `<strong>`, `<i>`, `<em>`, `<u>`, `<ins>`, `<s>`, `<strike>`, `<del>`, `<a>`, `<code>`, `<pre>`, `<blockquote>`.
- Converted to newlines: `<p>…</p>`, `<div>…</div>`, `<br>` — the rich-text editor's paragraph wrapping no longer breaks Telegram sends.
- Stripped: everything else (spans, styles, scripts, etc.).

If you previously saw `Bad Request: can't parse entities: Unsupported start tag "p"` when replying, the sanitizer now prevents that class of error.

## Webhook Token Resolution

When an inbound update arrives at `/api/webhooks/telegram`, the webhook controller:

1. Looks up the active Telegram integration for the workspace.
2. Reads the `bot_token` from the integration's encrypted credentials.
3. Constructs a `TelegramService` bound to that token so the welcome reply and any auto-reply use the right `api.telegram.org/bot{token}/…` URL.

There is no need to set `TELEGRAM_BOT_TOKEN` in `.env` — saving the token in the admin UI is sufficient.

## Common issues

- Welcome reply never arrives after `/start`: check that the bot_token saved in Settings matches the one BotFather gave you. A missing/stale token produces a 404 from `api.telegram.org/bot/sendMessage`.
- Inbound message saves fail with "Data truncated for column 'type'": this was a past bug where the service inserted `type = 'text'`. Fixed — all inbound Telegram messages now save with `type = 'message'`. Re-deploy if you still see this.
- Webhook shows "No webhook_secret configured": harmless by default. Optionally set a `webhook_secret` in the integration credentials so Telegram signs each delivery with `X-Telegram-Bot-Api-Secret-Token`.