0

I am trying to save attachment uploaded by google chat app. I am handling two cases if user messages anything to google chat app, it will pop up a card with widgets which is perfectly fine but I am handling if user uploads attachment it will save into google drive but the code is not working. Can someone please help? I am new in coding.

function getByteStream(dataRef) {
 var blob = "";
 var driveFileName = "";
 var url = "https://chat.googleapis.com/v1/media/"+ dataRef +"?alt=media"

 var service = getOAuth2Service();
 var response = UrlFetchApp.fetch(url, {
   headers: {
     'Authorization': 'Bearer ' + service.getAccessToken(),
   },
   'muteHttpExceptions': true,
 });

 if(response.getResponseCode() != 200){
   return "Failed to get file content with error code: " + response.getResponseCode();
 }
 blob = response.getBlob();
 driveFileName = DriveApp.createFile(blob);
 return "The uploaded contents have been saved in a Google Drive file: "+ driveFileName;
}

function onMessage(event) {
if (event.message.attachment) {
var attachmentName = event.message.attachment[0].name;
var attachment = getByteStream(attachmentName);
console.log(attachment);
} else {
return {
"cards_v2": [{
"card_id": "addContact",
"card": {
"header": {
"title": "Hello" +" " + event.user.displayName + "!",
"subtitle": "Log your feedback!",
"imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
"imageType": "CIRCLE"
},
              "sections": [
                {
                  "widgets": [
                    {
                      "buttonList": {
                        "buttons": [
                          {
                            "text": "Start here",
                            "onClick": {
                              "action": {
                                "function": "openDialog",
                                "interaction": "OPEN_DIALOG"
                                }
                              }
                            }
                          ]
                        },
                            "horizontalAlignment": "CENTER"
                        }
                      ]
                      }
                     ]
                      }
                      }]
                      };
                      }
 }


  






  • You seem to have copied the sample in [the docs](https://developers.google.com/chat/how-tos/get-attachment), but this is just an example of how to access the REST API with user credentials. The `getOAuth2Service()` function is not an actual Apps Script function and it's just a placeholder for a function that would authenticate a user. It's not an example made for a chatbot. Also, to what Drive are you trying to upload this? The user's? Or the app's? – Daniel Jan 09 '23 at 16:01

0 Answers0