无法通过API添加新帖子

我无法使用 API 在我的 Discourse 论坛上发布新帖子,我的代码:

function postComment(topicId, comment) {
  const url = `${DISCOURSE_API_URL}/t/${topicId}/posts.json`; // 确保此 URL 正确
  Logger.log(`Posting to URL: ${url}`);
  const headers = {
    "Api-Key": DISCOURSE_API_KEY,
    "Api-Username": DISCOURSE_API_USERNAME
  };

  const payload = {
    post: {
      topic_id: topicId,
      raw: comment
    },
  };

  const options = {
    method: "post",
    contentType: "application/json",
    headers: headers,
    payload: JSON.stringify(payload),
    muteHttpExceptions: true, // 捕获完整的错误响应
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const jsonResponse = JSON.parse(response.getContentText());

    // 记录响应以进行调试
    Logger.log(`Response Code: ${response.getResponseCode()}`);
    Logger.log(`Response Body: ${JSON.stringify(jsonResponse, null, 2)}`);

    // 检查帖子是否成功
    if (response.getResponseCode() === 200) {
      Logger.log(`Posted comment successfully: ${JSON.stringify(jsonResponse, null, 2)}`);
    } else {
      Logger.log(`Failed to post comment: ${JSON.stringify(jsonResponse, null, 2)}`);
    }

    return jsonResponse; // 返回 API 响应
  } catch (error) {
    Logger.log(`Error posting comment: ${error}`);
    return null; // 错误时返回 null
  }
}

收到此响应:

Info
Response Code: 404
3:35:29 PM
Info
Response Body: {
  "errors": [
    "The requested URL or resource could not be found."
  ],
  "error_type": "not_found"
}

尽管论坛主题存在,并且我可以在论坛网站上直接发布。
请帮忙。

404 极不可能是你的 API 密钥无效或未正确传递。

除非它意味着你实际上使用了错误的路径。如果你逆向工程 Discourse API 来获取帖子,那么使用的就是该路径吗?

我正在使用此路径:${DISCOURSE_API_URL}/t/${topicId}/posts.json
其中 DISCOURSE_API_URL = \"https://community.xxxxxxxxxxx.com\"

我认为通过 API 回复主题的 URL 是 /posts.json。在创建回复时(与创建新主题不同),topic_id 是必需的参数。

详细信息在此处:Discourse API Docs UI 创建主题回复,然后在浏览器开发者工具的“网络”部分检查设置的 RequestURL。

2 个赞