Telegram Bot API — 我用过的最友好的开发者 API

发布: (2026年3月26日 GMT+8 08:09)
3 分钟阅读
原文: Dev.to

Source: Dev.to

为什么 Telegram Bot API 与众不同

大多数 API 都让你与 OAuth、速率限制和分页作斗争。Telegram Bot API 为你提供了一个简单的 HTTP 接口,支持即时 webhook,没有 OAuth,且限制宽松。

入门指南

  1. 打开 Telegram 并搜索 @BotFather
  2. 发送 /newbot
  3. 选择一个名称和用户名。
  4. 复制 API token。

完成。无需 OAuth 应用注册、重定向 URI,也不需要客户端密钥。

基础 Python 示例

import requests

TOKEN = "your_bot_token"
BASE = f"https://api.telegram.org/bot{TOKEN}"

def send_message(chat_id, text):
    r = requests.post(f"{BASE}/sendMessage", json={
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "HTML"
    })
    return r.json()["ok"]

send_message("your_chat_id", "**Hello** from Python!")

接收更新(长轮询)

def get_updates(offset=0):
    r = requests.get(f"{BASE}/getUpdates", params={"offset": offset, "timeout": 30})
    return r.json()["result"]

# 简单的机器人循环
offset = 0
while True:
    updates = get_updates(offset)
    for u in updates:
        msg = u.get("message", {})
        text = msg.get("text", "")
        chat_id = msg["chat"]["id"]

        if text == "/start":
            send_message(chat_id, "Welcome! I am your bot.")
        elif text == "/help":
            send_message(chat_id, "Commands: /start, /help, /ping")
        elif text == "/ping":
            send_message(chat_id, "Pong!")

        offset = u["update_id"] + 1

发送不同类型的内容

# 发送照片
def send_photo(chat_id, photo_url, caption=""):
    requests.post(f"{BASE}/sendPhoto", json={
        "chat_id": chat_id,
        "photo": photo_url,
        "caption": caption
    })

# 发送位置
def send_location(chat_id, lat, lon):
    requests.post(f"{BASE}/sendLocation", json={
        "chat_id": chat_id,
        "latitude": lat,
        "longitude": lon
    })

# 发送文档
def send_document(chat_id, file_url):
    requests.post(f"{BASE}/sendDocument", json={
        "chat_id": chat_id,
        "document": file_url
    })

内联键盘按钮

def send_with_buttons(chat_id, text, buttons):
    keyboard = {"inline_keyboard": buttons}
    requests.post(f"{BASE}/sendMessage", json={
        "chat_id": chat_id,
        "text": text,
        "reply_markup": keyboard
    })

send_with_buttons("chat_id", "Choose an option:", [
    [{"text": "Option A", "callback_data": "a"},
     {"text": "Option B", "callback_data": "b"}],
    [{"text": "Visit Website", "url": "https://example.com"}]
])

常见使用场景

  • 服务器监控 – 当 CPU/内存飙升时发送警报。
  • 每日摘要 – 每天早晨汇总新闻/数据。
  • 费用追踪 – 通过发送消息记录支出。
  • 部署通知 – 成功或失败的部署时发送提醒。
  • RSS 阅读器 – 转发你喜欢的博客的新文章。

功能对比

功能TelegramDiscordSlack
机器人创建60 秒5 分钟10 分钟
是否需要 OAuth
免费 API无限有限制
消息格式化HTML/MarkdownMarkdownBlocks
文件上传限制50 MB25 MB(免费)视情况而定
Webhook 设置1 次 API 调用仪表盘仪表盘

More API tutorials | GitHub

0 浏览
Back to Blog

相关文章

阅读更多 »