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

如何从Google Cloud Storage向Google Chat空间发送图片

Google Chat卡片无法加载GCS存储图片的解决方案

问题背景

需要在Google Chat空间发送每日计算任务告警,将matplotlib生成的图片临时存储到Google Cloud Storage(GCS)存储桶,通过卡片的imageUrl字段展示图片。尝试了GCS认证URL、签名URL两种格式,以及Webhook、Chat REST API两种发送方式,均只能发送出无图片的空卡片;但替换为外部图床URL时,卡片可正常显示图片。因数据敏感,无法使用外部托管平台。


解决方案

1. 弃用GCP控制台访问URL

不要使用https://storage.cloud.google.com/project-id/test-image.png这类需要用户登录GCP控制台的界面URL,改用https://storage.googleapis.com/[bucket-name]/[image-path]作为图片对象的基础访问路径,再基于此生成签名URL。

2. 正确生成签名URL

签名URL需允许匿名GET请求,设置合理的过期时间,并匹配图片的Content-Type。以下是Python环境下使用google-cloud-storage库生成签名URL的示例:

from google.cloud import storage
from datetime import timedelta

def generate_gcs_signed_image_url(bucket_name, image_blob_name):
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(image_blob_name)

    # 生成有效期15分钟的签名URL,足够卡片完成加载
    signed_url = blob.generate_signed_url(
        version="v4",
        expiration=timedelta(minutes=15),
        method="GET",
        content_type="image/png"  # 根据实际图片类型调整,如image/jpeg
    )
    return signed_url

生成后先在浏览器隐私窗口测试URL是否能直接打开图片,确认有效后再填入卡片的imageUrl字段。

3. 配置GCS存储桶CORS规则

Google Chat加载图片时会发起跨域请求,需为存储桶配置允许chat.google.com访问的CORS规则:

  1. 创建cors-config.json文件,内容如下:
[
  {
    "origin": ["https://chat.google.com"],
    "method": ["GET"],
    "responseHeader": ["Content-Type"],
    "maxAgeSeconds": 3600
  }
]
  1. 使用gsutil命令应用配置:
gsutil cors set cors-config.json gs://your-bucket-name

4. 验证卡片JSON格式

确保message_body的imageUrl字段为合法字符串,无语法错误(如残留注释、引号缺失)。示例正确的卡片结构:

message_body = {
    "cards": [
        {
            "header": {
                "title": "每日计算任务告警",
                "subtitle": "任务执行状态"
            },
            "sections": [
                {
                    "header": "计算结果可视化",
                    "widgets": [
                        {
                            "image": {
                                "imageUrl": "填入生成的签名URL"
                            }
                        }
                    ]
                }
            ]
        }
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:48:32