You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Chat API获取空间消息时遭遇404错误

Google Chat API 获取空间消息返回404 "Method not found" 问题解决

问题概述

调用Google Chat API批量获取指定Space的消息时,使用相同代码与权限范围发送POST消息可成功,但执行GET请求返回404错误(错误信息:Method not found.),在Google App Script调试器和Postman中测试结果一致。

错误原因

Google Chat API的spaces.messages.list(批量列出空间消息)接口要求使用POST方法,而非GET。你当前的GET请求路径https://chat.googleapis.com/v1/spaces/AAAAzf4hBOQ/messages对应「获取单个指定ID的消息」接口(需在路径后追加消息ID),并非批量拉取消息的接口,因此触发404。

修正方案

将请求方法改为POST,同时调整接口路径为messages:list,并可在请求体中添加过滤参数(如分页、关键词等):

修正后的代码

function getMessagesInSpaceAPI() {

  var service = OAuth2.createService('chat')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
      .setClientId(SERVICE_ACCOUNT_EMAIL)
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope('https://www.googleapis.com/auth/chat.messages');

  if (!service.hasAccess()) {
   Logger.log('Authentication error: %s', service.getLastError());
    return;
  } else {
    Logger.log('token = ' + service.getAccessToken())
  }

  // 调用批量列消息的POST接口
  var res = UrlFetchApp.fetch('https://chat.googleapis.com/v1/spaces/AAAAzf4hBOQ/messages:list', {
    method: 'POST',
    followRedirects: true,
    muteHttpExceptions: true,
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    // 可选:添加过滤条件,示例为分页配置
    payload: JSON.stringify({
      pageSize: 20 // 每页最多返回20条消息
    })
  });

  Logger.log(res.getContentText())
}

补充说明

  • 你当前使用的权限范围https://www.googleapis.com/auth/chat.messages同时支持消息发送与读取,无需调整。
  • 若需获取单个特定ID的消息,才使用GET请求,路径格式为:https://chat.googleapis.com/v1/spaces/{space_id}/messages/{message_id},需提前知晓目标消息的ID。

内容的提问来源于stack exchange,提问作者Joey Bronner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 23:25:28