Python如何使用Google Chat API无需卡片发送Google Drive中存储的图片
问题根源
- 授权范围缺失:仅配置了Chat Bot操作权限,未申请Drive文件访问权限,无法读取Drive内的图片资源
- 请求体参数错误:Google Chat API创建消息的请求体中不支持直接传入
attachment字段,该字段仅为API返回消息时的响应字段,不可作为请求参数使用
解决方案
前置调整
- 补充授权范围,新增Drive只读权限:
scopes = ['https://www.googleapis.com/auth/chat.bot', 'https://www.googleapis.com/auth/drive.readonly']
- 确认权限:将服务账号密钥文件中
client_email对应的邮箱,添加到目标Drive图片的共享查看者列表,避免权限拦截。
方案1:卡片消息嵌入Drive图片(最简便,适配绝大多数场景)
直接将Drive公开图片的直链填入卡片的图片组件参数中,直链格式为https://drive.google.com/uc?export=view&id=你的Drive文件ID
修改后的请求体示例:
respe = { "text": "from jjime", "cardsV2": [{ "cardId": "drive-img-card", "card": { "sections": [{ "widgets": [{ "image": { "imageUrl": "https://drive.google.com/uc?export=view&id=ID OF IMAGE IN DRIVE", "altText": "driveimgtest" } }] }] } }] }
方案2:作为消息附件上传(需要图片作为独立文件附件)
如果需要将图片作为消息的独立附件而非卡片内容,需要调用Chat API的多媒体上传接口,示例代码片段如下:
# 先从Drive读取图片内容 drive_service = discovery.build('drive', 'v3', http=creds.authorize(Http())) file_content = drive_service.files().get_media(fileId="ID OF IMAGE IN DRIVE").execute() # 多部分上传消息+附件 media = MediaIoBaseUpload(io.BytesIO(file_content), mimetype='image/png', resumable=True) CHAT.spaces().messages().create( parent=space, body={"text": "from jjime"}, media_body=media, uploadType="multipart" ).execute()
注意使用该方案需要额外导入io和googleapiclient.http.MediaIoBaseUpload依赖
内容的提问来源于stack exchange,提问作者Jason Jurotich
相关产品推荐
相关产品推荐

