久々にChatWorkのAPIを触ってみました。
投稿のAPIのドキュメントは以下です
roomIDって
チャットワークのルームのURLはhttps://www.chatwork.com/#!rid12345
となり、ridの後ろの数字がIDになる模様
/#!rid12345
の場合12345
がRoomID
APIトークン
headerにx-chatworktoken: <APIトークン>
という形で詰め込む
サンプルリクエスト
curl --request POST \
--url https://api.chatwork.com/v2/rooms/12345/messages \
--header 'accept: application/json' \
--header 'content-type: application/x-www-form-urlencoded' \
--header 'x-chatworktoken: <APIトークン>' \
--data self_unread=0 \
--data body=hello
Node.jsから
v24で動作。OpenAI o3に書いてもらいました。
// chatwork-post.mjs
// Node.js v24 で動作(ES Modules)
// ────────────────────────────────
// 使い方:この 1 ファイルを実行するか、下部の call 部分を
// 別ファイルからコピーして呼び出しても OK です。
/**
* Chatwork にメッセージを POST する関数
* @param {Object} options
* @param {string} options.roomId 送信先ルーム ID
* @param {string} options.body メッセージ本文
* @param {string} options.token Chatwork API トークン
* @param {number} [options.selfUnread=0] 自分を未読にするか (0: しない, 1: する)
* @returns {Promise<Object>} Chatwork API のレスポンス JSON
*/
const postChatworkMessage = async ({
roomId,
body,
token,
selfUnread = 0,
}) => {
if (!roomId) throw new Error('roomId が指定されていません');
if (!token) throw new Error('API token が指定されていません');
// 送信先 URL を組み立て
const url = `https://api.chatwork.com/v2/rooms/${roomId}/messages`;
// フォームデータを URLSearchParams でエンコード
const params = new URLSearchParams({
self_unread: String(selfUnread),
body,
});
// fetch で POST
const res = await fetch(url, {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/x-www-form-urlencoded',
'x-chatworktoken': token,
},
body: params,
});
// エラーハンドリング
if (!res.ok) {
const text = await res.text(); // 詳細を取得
throw new Error(`HTTP ${res.status}: ${res.statusText}\n${text}`);
}
// 正常終了 ⇒ JSON で返す
return res.json();
};
// ────────────────
// 呼び出し例(このブロックを削除してライブラリ的に使っても OK)
// ────────────────
(async () => {
try {
const result = await postChatworkMessage({
roomId: '12345', // ★ ここで自由に指定
body: 'こんばんわ',
token: 'APIトークン', // ★ 自分のトークン
// selfUnread: 1, // ← 必要なら未読フラグも指定
});
console.log('送信成功:', result);
} catch (err) {
console.error('送信失敗:', err);
}
})();