Connect a Website to the Telegram Bot API Safely

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Connect a Website to the Telegram Bot API Safely

A website form and a Telegram bot solve different parts of a workflow. Your application owns the submission; Telegram is a convenient notification channel. Keeping those responsibilities separate makes failures easier to handle and keeps your bot token out of visitors’ browsers.

网站表单和 Telegram 机器人分别解决了工作流中不同的部分。您的应用程序负责处理提交的内容,而 Telegram 只是一个便捷的通知渠道。将这些职责分开可以更轻松地处理故障,并防止您的机器人令牌(bot token)泄露到访问者的浏览器中。

Design the flow first A practical flow is: validate the form on your server, save the submission, put a notification job in a queue, and send a short message to the team’s Telegram chat. Return a response to the visitor once the submission is safely stored. The notification worker can run independently. Avoid placing the bot token in HTML, frontend JavaScript, a public repository, logs, or a screenshot. Store it in your application’s secrets system or environment. Use a separate test bot and test chat before connecting a production destination.

首先设计流程。一个实用的流程是:在服务器上验证表单,保存提交内容,将通知任务放入队列,并向团队的 Telegram 聊天发送简短消息。一旦提交内容被安全存储,即向访问者返回响应。通知工作进程可以独立运行。避免将机器人令牌放置在 HTML、前端 JavaScript、公共存储库、日志或截图中。请将其存储在应用程序的密钥系统或环境变量中。在连接生产环境目标之前,请使用单独的测试机器人和测试聊天进行验证。

Create a bot and choose a destination Use Telegram’s official @botfather account to create a bot and obtain its token. The token controls the bot; revoke and replace it if exposed. For a private chat, a user must first start a conversation with the bot. For a group, add the bot and confirm it has permission to send messages. Your application needs the destination’s chat_id. In a test environment, send a message to the bot and inspect the chat object in an update returned by getUpdates. Group identifiers can be negative, so preserve the complete value. Treat the destination as server configuration, not as a form field supplied by an anonymous visitor.

创建机器人并选择目标。使用 Telegram 官方的 @botfather 账号创建机器人并获取其令牌。该令牌控制着机器人;如果泄露,请撤销并更换它。对于私聊,用户必须先与机器人发起对话。对于群组,请添加机器人并确认其拥有发送消息的权限。您的应用程序需要目标聊天 ID(chat_id)。在测试环境中,向机器人发送消息,并检查 getUpdates 返回的更新中的聊天对象。群组标识符可能是负数,因此请保留完整数值。将目标视为服务器配置,而不是由匿名访问者提供的表单字段。

Incoming updates can be delivered by webhook or retrieved with long polling. Telegram does not provide getUpdates while a webhook is configured for that bot. Do not remove a working webhook just to perform a test; use another bot or inspect the existing handler instead. An outbound notification alone does not require a webhook.

传入的更新可以通过 Webhook 传递,也可以通过长轮询(long polling)获取。当机器人配置了 Webhook 时,Telegram 不会提供 getUpdates。不要为了进行测试而移除正在工作的 Webhook;请使用另一个机器人或检查现有的处理程序。仅发送出站通知不需要 Webhook。

Send a server-side test message The following PHP example uses cURL and environment variables. It sends plain text so that untrusted input cannot accidentally become formatting markup.

发送服务器端测试消息。以下 PHP 示例使用了 cURL 和环境变量。它发送纯文本,以防止不受信任的输入意外变成格式化标记。

<?php
function notifyTelegram(string $message): bool {
    $token = getenv('TELEGRAM_BOT_TOKEN');
    $chatId = getenv('TELEGRAM_CHAT_ID');
    if (!$token || !$chatId) {
        error_log('Telegram configuration is missing');
        return false;
    }
    $ch = curl_init('https://api.telegram.org/bot' . $token . '/sendMessage');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'chat_id' => $chatId,
            'text' => $message,
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => 10,
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $result = is_string($body) ? json_decode($body, true) : null;
    return $status >= 200 && $status < 300 && is_array($result) && !empty($result['ok']);
}

Call notifyTelegram(‘Test notification’) from a controlled server-side test. This is a connectivity example, not a complete form handler. The request URL contains the bot token, so make sure HTTP debugging, exception reporting, and proxy logs do not expose it. See the official Bot API reference for method parameters and responses.

从受控的服务器端测试中调用 notifyTelegram(‘Test notification’)。这是一个连接性示例,而非完整的表单处理程序。请求 URL 包含机器人令牌,因此请确保 HTTP 调试、异常报告和代理日志不会泄露它。有关方法参数和响应,请参阅官方 Bot API 参考文档。

Make delivery resilient Save the submission before starting a notification job. Include a stable internal reference such as “New request #1842” and, where appropriate, a link to a protected dashboard. A queue can record the job state, attempts, and last error while leaving the visitor-facing request responsive. Treat ambiguous failures carefully. A connection timeout does not prove the message was never delivered: the remote service may have accepted it before the response was lost. A blind retry can create duplicates. Record an uncertain outcome and use the internal request number to support reconciliation. Respect any rate-limit guidance returned by the API and alert an operator when delivery stays unhealthy. A successful Telegram response confirms an API operation; it is not your source of truth for the original submission. Check your own database or CRM for that.

增强交付的韧性。在启动通知任务之前保存提交内容。包含一个稳定的内部引用,例如“New request #1842”,并在适当的情况下提供指向受保护仪表板的链接。队列可以记录任务状态、尝试次数和最后一次错误,同时保持面向访问者的请求响应迅速。谨慎对待模糊的故障。连接超时并不证明消息未送达:远程服务可能在响应丢失前已经接收了它。盲目重试可能会产生重复。记录不确定的结果,并使用内部请求编号来支持对账。遵守 API 返回的任何速率限制指导,并在交付持续不健康时提醒操作员。成功的 Telegram 响应仅确认了 API 操作;它不是您原始提交内容的真实来源。请检查您自己的数据库或 CRM 以获取该信息。

Protect the form and the chat Validate fields and lengths on the server. Add appropriate CSRF protection to authenticated workflows, rate limits, and spam controls. Limit request sizes. Do not accept the target chat from the public form. Give the bot only the access it needs and restrict membership of the receiving group. Send the minimum useful information. An identifier and a link to an access-controlled record are often safer than forwarding the complete form. Avoid passwords, payment credentials, and other secrets in notifications. Decide how long chat history should be accessible and who is responsible for reviewing access.

保护表单和聊天。在服务器上验证字段和长度。为经过身份验证的工作流添加适当的 CSRF 保护、速率限制和垃圾邮件控制。限制请求大小。不要从公共表单接受目标聊天 ID。仅授予机器人所需的访问权限,并限制接收群组的成员资格。发送最少量的有用信息。标识符和指向受控访问记录的链接通常比转发完整表单更安全。避免在通知中包含密码、支付凭据和其他机密信息。决定聊天记录应保留多长时间,以及谁负责审查访问权限。

If the bot also receives messages Incoming messages require a separate handler. For a webhook, use an HTTPS endpoint and validate the secret header when configured using Telegram’s webhook secret token. Reject malformed input, limit payload size, and enqueue longer work. Store update identifiers to prevent a repeated update from triggering the same business action twice. For polling, manage the update offset and make sure only the intended consumer handles the bot. A bot cannot initiate an arbitrary private chat with a visitor simply because the site collected a name or phone number; the person must start the bot interaction through a supported Telegram flow.

如果机器人也接收消息,则需要单独的处理程序。对于 Webhook,请使用 HTTPS 端点,并在使用 Telegram 的 Webhook 密钥令牌配置时验证密钥标头。拒绝格式错误的输入,限制有效载荷大小,并将较长的任务放入队列。存储更新标识符,以防止重复的更新触发两次相同的业务操作。对于轮询,请管理更新偏移量,并确保只有预期的消费者处理该机器人。机器人不能仅仅因为网站收集了姓名或电话号码就主动发起与访问者的私聊;用户必须通过受支持的 Telegram 流程启动与机器人的交互。

Launch checklist Confirm the bot token is stored only on the server and is absent from logs. Verify the destination ID and send a test message to the intended chat. Save submissions before creating notification jobs. Test a network outage and verify that the submission is still available. Handle uncertain delivery outcomes without an uncontrolled retry loop. Review chat membership, data minimization, monitoring, and the escalation contact. If receiving updates, verify webhook authentication and duplicate handling. Start with one form and a test bot. Once failure handling and access controls are in place, switch the server configuration to the production destination.

发布检查清单。确认机器人令牌仅存储在服务器上,且未出现在日志中。验证目标 ID 并向预期的聊天发送测试消息。在创建通知任务之前保存提交内容。测试网络中断并验证提交内容是否仍然可用。处理不确定的交付结果,避免不受控制的重试循环。审查聊天成员资格、数据最小化、监控和升级联系人。如果接收更新,请验证 Webhook 身份验证和重复处理机制。从一个表单和一个测试机器人开始。一旦故障处理和访问控制到位,再将服务器配置切换到生产环境目标。