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

基于Pub/Sub触发,使用Google Chat API自动发送私信的技术问题

Google Chat反馈机器人自动私信问题

问题概述

开发一款反馈机器人,需求是用户日历事件结束后自动发送私信。目前用AppScript完成大部分代码,Calendar API触发器正常工作,通过斜杠命令可触发功能,但无法实现基于日历事件触发的自动私信。

已知Google Chat API通常不允许主动发送私信,但存在成功案例。尝试两种发送方式均遇问题:

  • 使用AppScript Chat API SDK:日志显示流程正常,但无实际消息发出
  • 使用Google Chat REST API:先后出现400和403错误

错误详情

1. 首次400错误

12:10:32 PM Error   
Exception: Request failed for https://chat.googleapis.com returned code 400. Truncated server response: {
  "error": {
    "code": 400,
    "message": "Message cannot have cards for requests carrying human credentials.",
    "status": "INVALID_ARGUMEN... (use muteHttpExceptions option to examine full response)
showFeedbackMessageRest @ feedback.gs:105
pubsub_subscribe    @ feedback.gs:42

2. 改用纯文本后的403错误

12:30:36 PM Error   
Exception: Request failed for https://chat.googleapis.com returned code 403. Truncated server response: {
  "error": {
    "code": 403,
    "message": "This API is not accessible for external HTTP caller.",
    "status": "PERMISSION_DENIED"
  }
}
 (use muteHttpExceptions option to examine full response)
showFeedbackMessageRest @ feedback.gs:105
pubsub_subscribe    @ feedback.gs:42

相关代码

Pub/Sub订阅者代码

function pubsub_subscribe(e){
  var service = getService();
  
  if (!service.hasAccess()) {
    var authorizationUrl = service.getAuthorizationUrl();
    console.log('Authorize PubSub Service First : !!!!!!!!!!!!!!!!');
    console.log(authorizationUrl);
    showFeedbackMessageRest(e, {'auth_url' : authorizationUrl});
  }else{
    console.log('PubSub has Access!')
    var project_id = get_property('PROJECT_ID');
    // var topic = get_property('TOPIC');
    var subscriber = get_property('SUBSCRIBER');

    var url = `https://pubsub.googleapis.com/v1/projects/${project_id}/subscriptions/${subscriber}:pull`

    var body = {
      returnImmediately: true, 
      maxMessages: 1
    }

    var response = UrlFetchApp.fetch(url, {
      method: "POST",
      contentType: 'application/json',
      muteHttpExceptions: true,
      payload: JSON.stringify(body),
      headers: {
        Authorization: 'Bearer ' + getService().getAccessToken()
      }
    });

    var result = JSON.parse(response.getContentText());
    console.log(JSON.stringify(result));
    console.log(Object.keys(result).length);
    if (Object.keys(result).length > 0){
      var decoded = Utilities.base64Decode(result.receivedMessages[0].message.data);
      var event_details = JSON.parse(Utilities.newBlob(decoded).getDataAsString());
      var popup_obj = {
        'summary' : event_details.EventTitle
      };
      console.log(popup_obj);
      return showFeedbackMessageRest(e, popup_obj);
    }else{
      console.log('No Recent Messages!');
    }
  }
}

Chat REST API发送消息代码

function showFeedbackMessageRest(e, event) {
  var chat_service = getChatService()

  var message = {};

  if (!chat_service.hasAccess()) {
    var authorizationUrl = chat_service.getAuthorizationUrl();
    console.log('Authorize Chat Service First : !!!!!!!!!!!!!!!!');
    console.log(authorizationUrl);
  }else{
    console.log('Chat App Has Access!');
    if (event.hasOwnProperty('summary')){
      message = {
        "text" : `Provide Feedback For : ${event.summary}`
};
    }else{
      message = {
        "cards_v2": [{
          "card_id": "feedbackMessage",
          "card": {
            "header": {
              "title": `Provide Feedback For : ${event.summary}`,
              "subtitle": `This meeting just ended, provide feedback for the organizers to organize meetings more effectively.`,
              "imageUrl": "https://raw.githubusercontent.com/google/material-design-icons/master/png/social/poll/materialicons/24dp/2x/baseline_poll_black_24dp.png",
              "imageType": "CIRCLE"
            },
            "sections": [
              {
                "widgets": [
                  {
                    "buttonList": {
                      "buttons": [
                        {
                          "text": "Give Feedback",
                          "onClick": {
                            "action": {
                              "function": "promptQuestion",
                              "interaction": "OPEN_DIALOG"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }]
      };
    }
  }

  var url = 'https://chat.googleapis.com/v1/' + `${user_dm_space_name}` + '/messages';
  UrlFetchApp.fetch(url, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer ' + chat_service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify(message),
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:40:31