跳至主要內容

開發者快速接入:getMe、getUpdates、sendMessage(curl + Node.js)

用 curl 與 Node.js 搭起最小 MPChat Bot 接入:驗證 token、讀取 chat_id、傳送第一則訊息,內建 token 安全與錯誤處理。

最小鏈路:getMe(驗證 token)→ getUpdates(拿 chat_id)→ sendMessage(傳送)。token 從環境變數讀取,絕不硬編碼。


總覽

這是各桌面系統通用的開發者主路徑。基礎 URL:

https://call.mp.net/bot/bot{MPCHAT_BOT_TOKEN}/{methodName}

憑證放進環境變數或被 git 忽略的 .env

MPCHAT_BOT_TOKEN=your_mpbot_token_here
MPCHAT_CHAT_ID=your_chat_id_here

1. getMe(驗證 token)

curl -s "https://call.mp.net/bot/bot${MPCHAT_BOT_TOKEN}/getMe"

const token = process.env.MPCHAT_BOT_TOKEN;
const res = await fetch(`https://call.mp.net/bot/bot${token}/getMe`);
const data = await res.json();
if (!data.ok) throw new Error(`${data.error_code}: ${data.description}`);
console.log(data.result); // { id, is_bot, username }

401 表示 token 無效或已 revoke。

2. getUpdates(取得 chat_id)

curl -s -X POST "https://call.mp.net/bot/bot${MPCHAT_BOT_TOKEN}/getUpdates" \
  -H "Content-Type: application/json" \
  -d '{"timeout":30,"limit":50,"allowed_updates":["message"]}'

const res = await fetch(`https://call.mp.net/bot/bot${token}/getUpdates`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ timeout: 30, limit: 50, allowed_updates: ["message"] }),
});
const data = await res.json();
if (!data.ok) throw new Error(`${data.error_code}: ${data.description}`);
const chatId = data.result?.find((u) => u.message)?.message?.chat?.id;

成功回應會消費該批 updates;持續輪詢時傳 offset = 上一批最大 update_id + 1。回傳 409 表示已啟用 Webhook。

3. sendMessage(傳送第一則訊息)

curl -s -X POST "https://call.mp.net/bot/bot${MPCHAT_BOT_TOKEN}/sendMessage" \
  -H "Content-Type: application/json" \
  -d "{\"chat_id\":\"${MPCHAT_CHAT_ID}\",\"text\":\"Hello from mpbot\"}"

const res = await fetch(`https://call.mp.net/bot/bot${token}/sendMessage`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ chat_id: process.env.MPCHAT_CHAT_ID, text: "Hello from mpbot" }),
});
const data = await res.json();
if (!data.ok) throw new Error(`${data.error_code}: ${data.description}`);

請求前檢查清單

  • token 從環境變數讀取,絕不硬編碼或提交到倉庫。

  • ID 型別符合文件約定(安全整數或十進位字串)。

  • POST body 是合法 JSON,帶 Content-Type: application/json

  • 媒體方法使用公網 URL 或 multipart(不複用 file_id)。

相關文章

預設限流為每 token 每秒 30 次請求,超限回傳 429。上線前請加入指數退避重試。

是否回答了您的問題?