跳转到主要内容

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,按十进制字符串传入。

下一步

这是否解答了您的问题?