Если вы хотите предоставить API для отправки сообщений на конкретный разговор из внешних служб, вы можете использовать для этого такие способы, как уведомление / упреждающее сообщение.Это официальная демонстрация . Но если вы хотите отправлять сообщения в конкретный диалог, вам следует внести некоторые изменения: заменить содержимое в index.js следующим кодом:
const path = require('path');
const restify = require('restify');
const restifyBodyParser = require('restify-plugins').bodyParser;
// 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 { ProactiveBot } = require('./bots/proactiveBot');
// Note: Ensure you have a .env file and include the MicrosoftAppId and MicrosoftAppPassword.
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about adapters.
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
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError]: ${ error }`);
// Send a message to the user
await context.sendActivity(`Oops. Something went wrong!`);
};
// Create the main dialog.
const conversationReferences = {};
const bot = new ProactiveBot(conversationReferences);
// Create HTTP server.
const server = restify.createServer();
server.use(restifyBodyParser());
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
});
// Listen for incoming activities and route them to your bot main dialog.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (turnContext) => {
// route to main dialog.
await bot.run(turnContext);
});
});
// Listen for incoming notifications and send proactive messages to users.
server.post('/api/notify', async (req, res) => {
const conversationId = req.body.conversationId;
const message = req.body.message;
for (const conversationReference of Object.values(conversationReferences)) {
if (conversationReference.conversation.id === conversationId) {
await adapter.continueConversation(conversationReference, async turnContext => {
await turnContext.sendActivity(message);
});
}
}
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write('<html><body><h1>Proactive messages have been sent.</h1></body></html>');
res.end();
});
Запустите демонстрацию и отправьте сообщение почтальоном или restclient, как показано ниже: ![enter image description here](https://i.stack.imgur.com/zuJkN.png)
Как видите, я открыл две беседы, но только беседа, указанная мной, получила сообщение: ![enter image description here](https://i.stack.imgur.com/s3Xas.png)
Это только демонстрационная демонстрация, вы можете изменить запрос и логику, исходя из ваших выигранных требований, таких как изменение URL-адреса как /api/route_messages
.
OfПожалуйста, отметьте меня, если это полезно:)