*.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 botWhen 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
- The app owner creates a bot with @BotFather in Telegram.
- 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.
- 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.
Link a user to the bot
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:
- A handler calls
linkUrl(user.id)frommanh/telegramand getshttps://t.me/<bot>?start=…. The link is signed, so nobody can claim another user’s account. - A page shows a Get notifications on Telegram button that opens the link.
- The user presses Start. The
*.telegram.tsfile gets akind: "link"event withuserIdandchatId. - Store
chatIdon the user’s row. From then on the app messages them withsend(chatId, …).
The handler
The file exports a default function async (e). Every event has:
| Field | On | Meaning |
|---|---|---|
kind | every event | "message", "button" or "link" |
chatId | every event | the chat to answer |
from | every event | sender’s { id, name, username } on Telegram |
messageId | every event | the new message, or the message whose button was pressed |
text | message, link | message text, or a photo’s caption |
data | button | the pressed button’s data |
callbackId | button | for answerButton |
userId | link | the id passed to linkUrl, as a string |
raw | every event | Telegram’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
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";
}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.tsfile per app. Deploy refuses a second one; branch one.kindande.textinside one function. - Never write the bot token in code.
checkreportscode.telegram-token-literal. - A button press is that person’s action: check the
user’s role before approving, as in a handler. Buttondatacomes 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
sendafter the database write, intry/catch: a failed notification must not fail the business action. When the recipient blocked the bot, the error haserr.blocked === true; clear the storedchatId. - Telegram allows about 30 messages per second per bot and 1 per second per chat;
sendwaits 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.tsoraccess.
Next steps
- The app’s Telegram bot — Telegram notices with approve buttons, start to finish.
- std/telegram —
send,edit,answerButton,linkUrland the errors they raise.