机器人框架 - 在 Cron 回调函数中调用 turnContext.sendActivity 方法时出现意外错误



我在制作预定的Skype通知时遇到了一些麻烦。

错误:

(node:3720) UnhandledPromiseRejectionWarning: TypeError: Cannot perform 'get' on a proxy that has been revoked
at CronJob.<anonymous> (C:botscleanbot.js:101:43)
at CronJob.fireOnTick (C:botscleannode_modulescronlibcron.js:554:23)
at Timeout.callbackWrapper [as _onTimeout] (C:botscleannode_modulescronlibcron.js:621:10)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5)
(node:3720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 61)

我的代码:

await turnContext.sendActivity('Successful write to log.');        
var CronJob = require('cron').CronJob;
new CronJob('*/5 * * * * *', async function() {
    console.log('Executed');
    await turnContext.sendActivity('Executed'); //here is error
}, null, true, 'Europe/Riga');

sendActivity的第一个调用工作正常,但在 Cron 回调中的第二个调用则不然。

即使我尝试在 axios then()函数中调用它也可以工作.. :

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(async function (response) {
     await turnContext.sendActivity('Executed');
  })

有没有办法在 Cron 匿名函数中调用sendActivity

尝试将 async/await 方法与您的 Axios 请求一起使用,而不是 then/catch 方法。我过去在从回调函数调用 sendActivity 时见过这个问题。

const res = await axios.get('/user', { params: { ID: 12345 }});
await turnContext.sendActivity('Executed');

最好的选择是将 cron 作业设置为外部服务。然后,设置 cron 作业以按照您设置的计划对机器人进行 api 调用。当 api 被命中时,它将发送主动消息。

有多种

方法可以设置 cron 作业(或类似内容(,包括使用计时器触发器创建 Azure 函数(此处的文档(。

但是,您可以轻松构建基于节点的 JavaScript 服务,该服务可以对机器人进行 API 调用。

首先,您将首先创建目录并安装所需的节点模块。

mkdir cron-jobs-node cd cron-jobs-node
npm init -y
npm install express node-cron fs

接下来,生成项目。您可以进行 api 调用(例如,使用 Axios(来代替控制台.log((。您可以在此处阅读有关以下代码片段的更多信息。

// index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");
app = express();
// schedule tasks to be run on the server   
cron.schedule("* * * * *", function() {
    console.log("running a task every minute");
});
app.listen(3128);
[...]

Botbuilder-Samples 存储库中的 16.主动消息示例演示了如何创建 API 和设置基本的主动消息系统。

希望有帮助!

相关内容

最新更新