如何在Google Apps Script中用JavaScript实现Google Chat带图消息发送
Google Chat 通过JavaScript(Google Apps Script)发送带图片的消息
要在Google Chat消息中插入图片,你不能直接把Drive文件对象塞进JSON payload,原代码存在两个核心问题:
DriveApp.getFilesByName()返回的是文件迭代器(FileIterator),无法被JSON序列化- Google Chat的webhook不支持直接在
text字段中嵌入图片,需要使用**消息卡片(Card)**或者指定正确的附件格式
正确实现步骤与代码
以下是可运行的Google Apps Script代码,实现从Drive读取图片并发送到Google Chat:
var Body = "这是带图片的消息"; var chatWebhookUrl = "你的Google Chat Webhook链接"; // 1. 获取Drive中的图片文件(注意:getFilesByName返回迭代器,需用next()取第一个匹配的文件) var fileIterator = DriveApp.getFilesByName('DMS.png'); if (!fileIterator.hasNext()) { throw new Error("未找到名为DMS.png的文件"); } var imageFile = fileIterator.next(); // 2. 设置文件权限为公开可读(确保Google Chat能访问到图片) imageFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); var imageUrl = imageFile.getUrl(); // 3. 构造符合Google Chat要求的消息payload(使用消息卡片展示图片) const payload = JSON.stringify({ cardsV2: [ { cardId: "image-card-1", card: { sections: [ { widgets: [ { textParagraph: { text: Body } }, { image: { imageUrl: imageUrl, altText: "图片描述" } } ] } ] } } ] }); const options = { method: 'POST', contentType: 'application/json', payload: payload, muteHttpExceptions: true // 可选:开启后能捕获错误信息便于调试 }; // 发送请求 var response = UrlFetchApp.fetch(chatWebhookUrl, options); Logger.log("响应状态: " + response.getResponseCode()); Logger.log("响应内容: " + response.getContentText());
关键说明
- 文件权限:必须确保Google Chat能访问图片,设置为
ANYONE_WITH_LINK是最简单的方式;如果不想公开,可将文件共享给Google Chat的机器人邮箱,但操作更复杂。 - 消息格式:Google Chat的webhook推荐用
cardsV2来展示富内容(包括图片),纯文本字段无法直接嵌入图片。 - 迭代器处理:
getFilesByName可能返回多个同名文件,所以必须用hasNext()和next()来获取实际的文件对象,不能直接赋值给变量。
内容的提问来源于stack exchange,提问作者M Buck
相关产品推荐
相关产品推荐

