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

如何用App Script在Google Chat App向特定邮箱用户发送实时通知

解决Google Chat App无法向特定直属经理发送通知的问题

核心问题分析

你遇到的无法定位特定人员发送通知的本质是:Google Chat Bot发送一对一消息需要依赖目标用户的专属Chat空间ID,而非直接通过邮箱或姓名定位。以下是具体解决步骤:


1. 提前存储直属经理的Chat身份关联信息

在你的请假申请Sheet中新增一列(比如RM_Chat_Space_ID或RM_Email),用来关联直属经理的Chat身份:

  • 若选择存储邮箱:后续通过API自动获取对应的一对一Chat空间ID
  • 若选择直接存储空间ID:可让直属经理先给Bot发一条测试消息,然后通过ChatService.spaces.list()接口获取该一对一空间的ID,手动录入Sheet

2. 修正触发器中的消息发送逻辑

使用Google Apps Script编写逻辑,先获取目标经理的Chat空间ID,再发送通知。示例代码如下:

// 触发器执行的主函数
function processPendingLeaveRequests() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("请假申请");
  const allRows = sheet.getDataRange().getValues();
  
  // 遍历行(跳过表头)
  for (let rowIndex = 1; rowIndex < allRows.length; rowIndex++) {
    const currentRow = allRows[rowIndex];
    const status = currentRow[3]; // 假设状态列在第4位(索引从0开始)
    const rmEmail = currentRow[2]; // 假设经理邮箱列在第3位
    const leaveDetails = `员工${currentRow[0]}提交了请假申请:${currentRow[1]}`;

    if (status === "pending") {
      try {
        // 获取经理的一对一Chat空间ID
        const dmSpaceId = getDirectMessageSpace(rmEmail);
        if (dmSpaceId) {
          // 发送通知消息
          ChatService.spaces.messages.create({
            parent: dmSpaceId,
            message: { text: leaveDetails }
          });
          // 更新申请状态为已通知
          sheet.getRange(rowIndex + 1, 4).setValue("notified");
        } else {
          console.log(`未找到经理${rmEmail}的Chat空间,请确认其已与Bot对话过`);
        }
      } catch (error) {
        console.error(`发送通知失败:${error.message}`);
      }
    }
  }
}

// 获取指定邮箱用户的一对一Chat空间ID
function getDirectMessageSpace(userEmail) {
  const spacesResponse = ChatService.spaces.list({
    filter: `type="DM" AND user="${userEmail}"`
  });
  const dmSpaces = spacesResponse.spaces;
  return dmSpaces?.length > 0 ? dmSpaces[0].name : null;
}

3. 关键权限与配置检查

  • 启用Google Chat API:在Apps Script编辑器中,依次点击「资源」→「高级Google服务」,找到并启用Google Chat API
  • Bot权限配置:确保Chat Bot拥有chat.messages.create权限;若为域内应用,需在Google Admin控制台允许Bot向域内用户发送消息
  • 前置条件:直属经理必须先与Bot发起过至少一次对话(否则Bot无法创建或访问一对一Chat空间)

4. 调试方法

  • 查看Apps Script日志:编辑器中点击「查看」→「日志」,排查执行时的错误(如权限不足、空间ID不存在等)
  • 手动测试函数:单独调用getDirectMessageSpace()传入经理邮箱,验证是否能返回有效空间ID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:20:26