Gmail 插件将参数传递给由卡操作触发的函数

uck*_*ckc 2 google-apps-script gmail-addons

我正在构建一个 Gmail 插件,它可以创建一张只有一个表单按钮的卡片。单击后,我希望该按钮触发一个功能,将打开的电子邮件的内容发送到外部 API。

到目前为止,我有这样的事情:

function createCard(event) {
  var currentMessage = getCurrentMessage(event).getBody();
  var section = CardService.newCardSection();

  var submitForm = CardService.newAction()
    .setFunctionName('callAPI');

  var submitButton = CardService.newTextButton()
    .setText('Submit')
    .setOnClickAction(submitForm);

  section.addWidget(CardService.newButtonSet()
    .addButton(submitButton));

  var card = CardService.newCardBuilder()
    .setHeader(CardService.newCardHeader()
    .setTitle('Click this button'))
    .addSection(section)
    .build();

  return [card];
}

function callAPI(event) {
  var payload = { "msg": msg }; // msg is the parameter I need to get from the function call
  var options = {
        "method"  : "POST",
        "contentType": "application/json",
        "payload" : JSON.stringify(payload),
        "followRedirects" : true,
        "muteHttpExceptions": true
  };

  return UrlFetchApp.fetch('https://www.someAPI.com/api/endpoint', options);
}
Run Code Online (Sandbox Code Playgroud)

如何将currentMessage变量传递到函数中callAPI?根据文档,我们可以从操作函数获取的唯一参数似乎event只有表单字段数据。如果没有办法传递其他参数,是否有办法让该函数直接在函数内部获取消息的上下文数据?

谢谢!

小智 6

我相信将 currentMessage 内容传递给 callAPI 函数的正确方法是使用 setParameters,如本文档中所述

你的代码看起来像这样:

var submitForm = CardService.newAction()
    .setFunctionName('callAPI')
    .setParameters({message: currentMessage});
Run Code Online (Sandbox Code Playgroud)

在回调中,您可以使用以下方式获取消息:

function callAPI(event) {
    var payload = event.parameters.message; 
    ...
Run Code Online (Sandbox Code Playgroud)

提醒一下,键(消息)和值(currentMessage)都必须是字符串。