跳至主要內容

Bot API 接入範例:用 curl 或 Node.js 收發測試訊息

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

本文面向開發者,提供 curl 與 Node.js 測試範例。若需要依 Windows/macOS 分步操作,可選擇首次除錯教學,無需兩篇依序完成。 跑通第一個 MPChat Bot:手機測試與 Windows/macOS 除錯

用 getMe 驗證 token,用 getUpdates 讀取測試會話,再用 sendMessage 傳送第一則回覆。


傳送第一則 Bot 訊息

  1. 在手機上開啟 MPChat → 通訊錄 → 機器人,進入 BotFather。建立一個專用測試 Bot,或選擇你已管理的測試 Bot,然後複製它的 token。詳見BotFather 取得 token 的步驟。

  2. 開啟與測試 Bot 的私聊,傳送 mpchat-quickstart。

  3. 使用未啟用 Webhook、也沒有其他程序在輪詢的測試 Bot。

在執行指令的終端設定環境變數 MPCHAT_BOT_TOKEN。請勿將 token 寫入原始碼、指令歷史、截圖或日誌。

方式 A · curl

以下指令在 Bash 或 zsh 中執行。先確認傳回的使用者名稱是你的測試 Bot。

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

在 result 中找到包含 mpchat-quickstart 的私聊訊息,複製該則的 message.chat.id。

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

用剛複製的 ID 取代 REPLACE_WITH_CHAT_ID,然後傳送回覆。

export MPCHAT_CHAT_ID='REPLACE_WITH_CHAT_ID'
curl -sS -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 MPChat Bot.\"}"

方式 B · Node.js

將完整範例存為 quickstart.mjs,使用 Node.js 22 或更新版本執行 node quickstart.mjs。若已試過 curl,請先傳送一則新的測試訊息。

const token = process.env.MPCHAT_BOT_TOKEN;
if (!token) throw new Error("Set MPCHAT_BOT_TOKEN before running this file.");

async function call(method, body) {
let response;
try {
response = await fetch(
`https://call.mp.net/bot/bot${token}/${method}`,
body === undefined ? undefined : {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
},
);
} catch {
throw new Error(`${method}: network request failed.`);
}

const data = await response.json().catch(() => null);
const code = data?.error_code ?? response.status;
if (code === 409 && method === "getUpdates") {
throw new Error("getUpdates: 409. Use a test bot without a webhook.");
}
if (!response.ok || !data?.ok) {
throw new Error(`${method}: request failed (${code}).`);
}
return data.result;
}

const bot = await call("getMe");
console.log(`Connected as @${bot.username}`);

const updates = await call("getUpdates", {
timeout: 10,
limit: 50,
allowed_updates: ["message"],
});
const matchingChatIds = new Set(updates
.filter(({ message }) => message?.chat?.type === "private" &&
message.text === "mpchat-quickstart")
.map(({ message }) => message.chat.id));
if (matchingChatIds.size !== 1) {
throw new Error("Use a test bot with exactly one matching private chat, then send a new test message.");
}
const [chatId] = matchingChatIds;
if (!(Number.isSafeInteger(chatId) && chatId >= 0) &&
!(typeof chatId === "string" && /^[0-9]+$/.test(chatId))) {
throw new Error("Use a valid Bot API chat ID from the update.");
}
const sent = await call("sendMessage", {
chat_id: String(chatId),
text: "Hello from MPChat Bot.",
});
console.log(`Sent message ${sent.message_id}`);

測試 Bot 會在私聊中回覆 Hello from MPChat Bot.。傳送成功時會傳回 message_id。

排查

  • 401。核對 token 是否屬於測試 Bot、是否仍然有效。

  • 結果為空或沒有相符訊息。重新傳送 mpchat-quickstart。getUpdates 成功時只消費本次回應實際傳回的更新。

  • 409。該 Bot 已啟用 Webhook,請改用未啟用 Webhook 的獨立測試 Bot。

  • sendMessage 回傳 400。使用測試會話中的 message.chat.id,以十進位字串傳入。

下一步

是否回答了您的問題?