谷歌美国石油学会webhook后触发节点.js即使没有参数值也调用

2024-06-14 12:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正在工作的谷歌美国石油学会我所访问的项目,要求它打开一个组件,它将json发布到一个webhook URL,我的nodejs解析json,在raspberry上执行python脚本。问题是,很明显,仅仅调用欢迎意图就会触发json post并切换python脚本来打开组件。奇怪的是if语句决定调用哪个python脚本所需的组件状态在欢迎意向状态下为空。在

这是我的节点.js公司名称:

'use strict';
require('dotenv').config();

const PythonShell = require('python-shell');
const fs = require('fs');
const express = require('express');
const bodyParser= require('body-parser');
const path = require('path')
const app = express();

process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
app.use(bodyParser.json({type: 'application/json'}));

const GENERATE_ANSWER_ACTION = 'generate_answer';
const EXECUTE_HOME_COMMAND = 'execute_home_command';

const switches = [];

var readableStream = fs.createReadStream('saveState.json');
var data = ''

readableStream.on('data', function(chunk) {
    data+=chunk;
});

readableStream.on('end', function() {
  var parsed = JSON.parse(data);
  for (var i=0;i<parsed.switches.length;i++){
    switches.push(new Switch(parsed.switches[i]))
  }
});

function Switch(switchValues){
  this.id = switchValues.id || "sw"
  this.state = switchValues.state || "off"
  this.name = switchValues.name || "switch"
  this.toggle = function(){
    if(this.state === "on"){
      this.setState("off")
    } 
    else{
      this.setState("on");
    }
  }
  this.setState = function(state){
    var str = state === "on" ? onString(this.id[2]) : offString(this.id[2]);
    PythonShell.run(str, function (err) {
      if (!process.env.DEV){
        if (err) throw err;
      } 
    });
    this.state = state
  }
  this.setState(this.state);
}    

function onString(number){
  return './public/python/sw' + number + '_on.py'
}
function offString(number){
  return './public/python/sw' + number + '_off.py'
}

function getSwitch(string){
  return switches.filter(function(element){
    return element.id === string;
  })[0]
}

function saveState (){
  var formattedState = {
    switches: switches
  }
  fs.writeFile('./saveState.json', JSON.stringify(formattedState) )
}

app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.sendFile('index');
})

// Switch Routes for API
app.get('/api/switches', function(req, res){
  res.send(switches);
})

app.get('/api/switches/:id', function(req, res){
  var found = getSwitch(req.params.id);
  res.json(found);
})

app.post('/api/switches/:id', function(req, res){
   console.log('headers: ' + JSON.stringify(req.headers));
   console.log('body: ' + JSON.stringify(req.body));
   const assistant = new Assistant({request: req, response: res});
   let soc = assistant.getArgument('state-of-component')

   function generateAnswer(assistant) {
      console.log('genera answer');
      assistant.ask('I\'m thinking of a number from 0 and 100. What\'s your first guess?');
   }

   function executeHomeCommand(assistant) {
    console.log('revisear guess');
    console.log(soc);
    if (soc === "on") {
       console.log('SUCCESS soc=ON');
    } else {
        console.log('FAILUER soc=OFF');
    }
    }
//   //MAP ACTIONS to functions
      let actionMap = new Map();
      actionMap.set(GENERATE_ANSWER_ACTION, generateAnswer);
      actionMap.set(EXECUTE_HOME_COMMAND, executeHomeCommand);
      assistant.handleRequest(actionMap);

  if (req.query.password === process.env.PASS){
    var foundSwitch = getSwitch(req.params.id);

    if (soc === "on") {
        foundSwitch.setState("on");
        console.log('SWITCHING ON');
    } else {
        foundSwitch.setState("off");
        console.log('SWITCHING OFF');
    }

    saveState();
    console.log("postSwitch "+JSON.stringify(foundSwitch));
    res.json(foundSwitch);
  }
  else {
    console.log("invalid password")
    res.send("try again")
  }

})

app.listen(process.env.PORT, function(){
 console.log('Listening on port ' + process.env.PORT);
})

我以为是我的应用程序js代码发布在欢迎意向上,但我不太确定,因为在欢迎意向上,组件的状态是空的,没有值,所以soc是!=“on”,所以if语句工作正常。问题是:

^{pr2}$

代码也是出于欢迎的意图而被调用的,它不应该被调用。在


Tags: logidjsonappifonvarfunction
1条回答
网友
1楼 · 发布于 2024-06-14 12:15:40

好吧,真正的问题是你似乎在处理所有的意图,而不是基于特定意图的特定事物。与美国石油学会,您有两种方法来处理此问题:

  1. 对于特定的目的,您始终可以关闭webhook解析,而对于其他目的,您仍然可以保持启用状态。在本例中,您可以出于欢迎目的(这将发送问候提示等)而将其关闭,但对于其他命令处理,则将其打开。

  2. 一旦你的webhook被调用,googlelibrary上的操作将决定调用它所调用的操作的特定函数。这是通过assistant.handleRequest(actionMap);行来处理的。

在您的代码中,在调用assistant.handleRequest(actionMap);之后,会发生额外的处理。所以每次调用都会处理这个额外的代码。听起来这不是你想要的。在

您应该将此代码移到向actionMap注册的特定操作处理代码中。(我不知道您的操作是什么,但我假设将代码放在executeHomeCommand()函数中最有意义,假设其他所有操作都正确连接。)

相关问题 更多 >