Skip to Content

*.telegram.ts

The *.telegram.ts file receives every message, button press and Start tap sent to the app’s Telegram bot; each app has exactly one.

app/ ├── users/ │ └── users.table.ts # add a telegramChatId column ├── me/ │ └── telegram-link/ │ └── get.ts # returns the link that turns on notifications ├── orders/ │ └── repository.ts # sends a message with an "Approve" button for new orders └── bot/ ├── repository.ts └── bot.telegram.ts # everything sent to the bot

When to use it

Staff rarely open the app but always have Telegram open. The app’s bot tells them about new orders, approvals waiting, upcoming bookings; they tap a button right in Telegram to approve or reject. They can also send the bot short commands, like /orders for the number of pending orders.

Connect the bot

  1. The app owner creates a bot with @BotFather in Telegram.
  2. The owner pastes the bot token under Connections › Telegram in the project. manh.run keeps the token and points the bot at the app; app code never sees it.
  3. Messages go out under the owner’s bot, not manh.run.

Until a bot is connected, send and linkUrl throw “Telegram is not connected”. The agent never asks for the token; it asks the owner to do step 2.

Telegram only lets a bot message people who pressed Start, and the bot doesn’t know who they are in the app. So each user gets their own link:

  1. A handler calls linkUrl(user.id) from manh/telegram and gets https://t.me/<bot>?start=…. The link is signed, so nobody can claim another user’s account.
  2. A page shows a Get notifications on Telegram button that opens the link.
  3. The user presses Start. The *.telegram.ts file gets a kind: "link" event with userId and chatId.
  4. Store chatId on the user’s row. From then on the app messages them with send(chatId, …).

The handler

The file exports a default function async (e). Every event has:

FieldOnMeaning
kindevery event"message", "button" or "link"
chatIdevery eventthe chat to answer
fromevery eventsender’s { id, name, username } on Telegram
messageIdevery eventthe new message, or the message whose button was pressed
textmessage, linkmessage text, or a photo’s caption
databuttonthe pressed button’s data
callbackIdbuttonfor answerButton
userIdlinkthe id passed to linkUrl, as a string
rawevery eventTelegram’s original update

Return a string and it is sent back to the chat. Return undefined and nothing is sent. Button presses are acknowledged for you after the function finishes; call answerButton(e.callbackId, "Approved") to show a small toast instead.

Send from any server file with manh/telegram: send(chatId, text, { buttons, parse, silent, replyTo }) returns { chatId, messageId }; edit(chatId, messageId, text, { buttons }) changes a sent message. buttons is an array of rows, each button { text, data } (data up to 64 characters) or { text, url }.

Example

app/bot/bot.telegram.ts
import { saveChatId, userByChatId, approveOrder, pendingCount } from "./repository"; export default async function (e) { if (e.kind === "link") { await saveChatId(Number(e.userId), String(e.chatId)); return "Telegram notifications are on for your account."; } const user = await userByChatId(String(e.chatId)); if (!user) return "Your account isn't linked yet. Open the app, go to Profile and tap Get notifications on Telegram."; if (e.kind === "button") { const [action, id] = e.data.split(":"); if (action === "approve") return approveOrder(user, Number(id)); // returns "Order #12 approved" return; } if (e.text === "/orders") return `${await pendingCount(user)} orders waiting for approval.`; return "Commands: /orders"; }
app/orders/repository.ts
import { send } from "manh/telegram"; // … after the new order is written to the database: try { await send(manager.telegramChatId, `Order #${o.id} needs approval: ${o.total.toLocaleString("vi-VN")} ₫`, { buttons: [[{ text: "Approve", data: `approve:${o.id}` }, { text: "Reject", data: `reject:${o.id}` }]], }); } catch (err) { if (err.blocked) await clearChatId(manager.id); // the recipient blocked the bot }

Good to know

  • One *.telegram.ts file per app. Deploy refuses a second one; branch on e.kind and e.text inside one function.
  • Never write the bot token in code. check reports code.telegram-token-literal.
  • A button press is that person’s action: check the user’s role before approving, as in a handler. Button data comes from Telegram; validate it like any input.
  • An update reaches the function once, but still write data so that running twice does no harm.
  • If the function throws, the error is logged and Telegram does not resend. The user gets nothing, so catch errors and return a sentence they can understand.
  • The function must finish fast, under about 30 seconds. Push slow work to a background job.
  • Call send after the database write, in try/catch: a failed notification must not fail the business action. When the recipient blocked the bot, the error has err.blocked === true; clear the stored chatId.
  • Telegram allows about 30 messages per second per bot and 1 per second per chat; send waits and retries when limited. Messages over 4,096 characters are cut.
  • Add a nullable telegramChatId: text("telegram_chat_id") column to the users table, with an index if you look users up by it.
  • There is no signed-in user, and no middleware.ts or access.

Next steps

Last updated