Node.js 团队机器人&引用;TypeError:source.on不是函数;在';创建对话&x27;方法

Node.js 团队机器人&引用;TypeError:source.on不是函数;在';创建对话&x27;方法,node.js,botframework,microsoft-teams,Node.js,Botframework,Microsoft Teams,我有一个TEAMS node.js bot在本地运行(使用ngrok)。我接收来自团队客户和echo works的消息 context.sendActivity(`You said '${context.activity.text}'`); 我需要发送一条主动消息,但创建对话pbject时出错 我的代码: ... await BotConnector.MicrosoftAppCredentials.trustServiceUrl(sServiceUrl); var credentials =

我有一个TEAMS node.js bot在本地运行(使用ngrok)。我接收来自团队客户和echo works的消息

context.sendActivity(`You said '${context.activity.text}'`);
我需要发送一条主动消息,但创建对话pbject时出错

我的代码:

...
await BotConnector.MicrosoftAppCredentials.trustServiceUrl(sServiceUrl);

var credentials = new BotConnector.MicrosoftAppCredentials({
    appId: "XXXXXXXXXXXX",
    appPassword: "YYYYYYYYYYYYY"
});

var connectorClient = new BotConnector.ConnectorClient(credentials, { baseUri: sServiceUrl });

const parameters = {
    members: [{ id: sUserId }],
    isGroup: false,
    channelData:
    {
        tenant: {
            id: sTenantId
        }
    }
};

// Here I get the error: "TypeError: source.on is not a function"
var conversationResource = await connectorClient.conversations.createConversation(parameters);

await connectorClient.conversations.sendToConversation(conversationResource.id, {
   type: "message",
   from: { id: credentials.appId },
   recipient: { id: sUserId },
   text: 'This a message from Bot Connector Client (NodeJS)'
});
字符串值正确,并且我有一个有效的connectorClient

提前感谢,


迭戈

我认为你很接近,但只需要做一些修改。很难说,因为我看不到你所有的代码

在这里,我将Teams中间件添加到
index.js
中的适配器中,并在
mainDialog.js
中的瀑布步骤中进行调用,以触发主动消息。只要您可以传入
context
,代码的位置就不重要了

另外,对于您的消息构造,仅发送文本就足够了。收件人已在参数表中指定,其余活动属性通过连接器指定。无需重建活动(除非您确实需要)

最后,确保信任
服务URL
。我是通过
mainBot.js
中的
onTurn
方法实现的

希望有帮助

index.js

const teams=require('botbuilder-teams');
const adapter=新的BotFrameworkAdapter({
appId:process.env.MicrosoftAppId,
appPassword:process.env.MicrosoftAppPassword
})
.use(new teams.TeamsMiddleware())
mainDialog.js

const{ConnectorClient,MicrosoftAppCredentials}=require('botframework-connector');
异步团队ProactiveMessage(stepContext){
const credentials=新的MicrosoftAppCredentials(process.env.MicrosoftAppId、process.env.MicrosoftAppPassword);
const connector=new ConnectorClient(凭据,{baseUri:stepContext.context.activity.serviceUrl});
const花名册=wait connector.conversations.getConversationMembers(stepContext.context.activity.conversation.id);
常数参数={
成员:[
{
id:花名册[0]。id
}
],
渠道数据:{
承租人:{
id:花名册[0]。租户id
}
}
};
const conversationResource=wait connector.conversations.createConversation(参数);
const message=MessageFactory.text('这是一条主动消息');
等待连接器.conversations.sendToConversation(conversationResource.id,message);
返回stepContext.next();
}
mainBot.js

this.onTurn(异步(上下文,下一步)=>{
if(context.activity.channelId==='msteams'){
MicrosoftAppCredentials.trustServiceUrl(context.activity.serviceUrl);
}
等待下一个();
});

我用Yeoman创建了我的机器人,因此我有一个运行示例,可以响应传入的消息。

有了它,我可以对传入的消息做出响应,并且它可以正常工作

我的完整代码:

index.js://自动创建,未修改

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');

// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');

// This bot's main dialog.
const { MyBot } = require('./bot');

// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });

// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
    console.log(`\nTo test your bot, see: https://aka.ms/debug-with-emulator`);
});

// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword
});

// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
    // This check writes out errors to console log .vs. app insights.
    console.error(`\n [onTurnError]: ${ error }`);
    // Send a message to the user
    await context.sendActivity(`Oops. Something went wrong!`);
};

// Create the main dialog.
const myBot = new MyBot();

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        // Route to main dialog.
        await myBot.run(context);
    });
});
我的机器人文件。bot.js//自动创建,修改为添加主动消息

   const { ConnectorClient, MicrosoftAppCredentials, BotConnector } = require('botframework-connector');
   const { ActivityHandler } = require('botbuilder');

   class MyBot extends ActivityHandler {

    constructor() {
        super();
        // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
        this.onMessage(async (context, next) => {
            //await context.sendActivity(`You said '${context.activity.text}'`); // It works
            var activity = context.activity;
            await MicrosoftAppCredentials.trustServiceUrl(activity.serviceUrl);
            var connectorClient = new ConnectorClient(credentials, { baseUri: activity.serviceUrl });
            const parameters = {
                members: [{ id: activity.from.id }],
                isGroup: false,
                channelData:
                {
                    tenant: {
                        id: activity.conversation.tenantId
                    }
                }
            };
        var conversationResource = await connectorClient.conversations.createConversation(parameters);  

    });
}

module.exports.MyBot = MyBot;
在“createConversation”中,我得到错误:

 [onTurnError]: TypeError: source.on is not a function
这段代码将在一个方法中,为了在需要时调用它,我将它放在“onMessage”中只是为了简化

我想我的代码和你的一样。。。但我恐怕我错过了什么或做错了什么

谢谢你的帮助


Diego

我有一个错误堆栈跟踪,它似乎与“延迟流”节点模块有关。由于评论太长,我添加以下内容作为回应:

(node:28248) UnhandledPromiseRejectionWarning: TypeError: source.on is not a function
        at Function.DelayedStream.create ([Bot Project Path]\node_modules\delayed-stream\lib\delayed_stream.js:33:10)
        at FormData.CombinedStream.append ([Bot Project Path]\node_modules\combined-stream\lib\combined_stream.js:45:37)
        at FormData.append ([Bot Project Path]\node_modules\form-data\lib\form_data.js:74:3)
        at MicrosoftAppCredentials.refreshToken ([Bot Project Path]\node_modules\botframework-connector\lib\auth\microsoftAppCredentials.js:127:20)
        at MicrosoftAppCredentials.getToken ([Bot Project Path]\node_modules\botframework-connector\lib\auth\microsoftAppCredentials.js:91:32)
        at MicrosoftAppCredentials.signRequest ([Bot Project Path]\node_modules\botframework-connector\lib\auth\microsoftAppCredentials.js:71:38)
        at SigningPolicy.signRequest ([Bot Project Path]\node_modules\@azure\ms-rest-js\dist\msRest.node.js:2980:44)
        at SigningPolicy.sendRequest ([Bot Project Path]\node_modules\@azure\ms-rest-js\dist\msRest.node.js:2984:21)
        at ConnectorClient.ServiceClient.sendRequest ([Bot Project Path]\node_modules\@azure\ms-rest-js\dist\msRest.node.js:3230:29)
        at ConnectorClient.ServiceClient.sendOperationRequest ([Bot Project Path]\node_modules\@azure\ms-rest-js\dist\msRest.node.js:3352:27)

我发现了我的问题。我必须按正确的顺序设置凭据/收件人/信任:

credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);

connectorClient = new ConnectorClient(credentials, { baseUri: activity.serviceUrl });

MicrosoftAppCredentials.trustServiceUrl(activity.serviceUrl);

我发现我在其他方法中也遇到了同样的错误,比如updateActivity…嗨,史蒂文,我现在看到你的消息了。今天我将尝试并告诉你。谢谢!!!嗨,史蒂文,我在周一看到了你的留言,但我在我的问题上添加了一条评论,而不是在你的回复上。也许你没看到。首先,非常感谢。此外,我添加了一个新的回复来添加更多信息。我真的很感激任何杰普,我对这个错误有点失望。。。