Reputation: 35
Context: I am creating a simple Teamsbot
(The complete stripped down version template, that simply echoes back what it gets as message), with JavaScript
.
The JavaScript (Node.js Backend
) server is hosted on Azure
and I have my default domain URL (which works as I can test some API endpoints through Postman).
The issue: when I upload my appPackage.zip
file and do "Preview in Teams", It does not echoes back anything, neither does the onMessage()
gets triggered at all. After logging I can see that the endpoint "/api/messages" is not getting hit at all.
Question: How do I make my teams app hit the endpoint /api/messages
and trigger TeamsBot.onMessage()
Below is my index.js
.
const restify = require("restify");
const {
CloudAdapter,
ConfigurationServiceClientCredentialFactory,
ConfigurationBotFrameworkAuthentication,
} = require("botbuilder");
const {TeamsBot} = require("./teamsBot");
const config = require("./config");
// Create adapter
const credentialsFactory = new ConfigurationServiceClientCredentialFactory(
config
);
const botFrameworkAuthentication = new ConfigurationBotFrameworkAuthentication(
{},
credentialsFactory
);
const adapter = new CloudAdapter(botFrameworkAuthentication);
adapter.onTurnError = async (context, error) => {
console.error(`\n [onTurnError] unhandled error: ${error}`);
// Only send error message for user messages, not for other message types so the bot doesn't spam a channel or chat.
if (context.activity.type === "message") {
// Send a message to the user
await context.sendActivity(
`The bot encountered an unhandled error:\n ${error.message}`
);
await context.sendActivity(
"To continue to run this bot, please fix the bot source code."
);
}
};
// Create the bot that will handle incoming messages.
const bot = new TeamsBot();
// Create HTTP server.
const server = restify.createServer();
server.use(restify.plugins.bodyParser());
const port = 443;
// Listen on proper port
server.listen(port, () => {
console.log(`\nBot server listening on port ${port}`);
});
// Main bot message endpoint
server.post("/api/messages", async (req, res) => {
console.log("Received request at /api/messages:", {
type: req.body.type,
text: req.body.text,
timestamp: new Date().toISOString(),
});
try {
await adapter.process(req, res, async (context) => {
await bot.run(context);
});
} catch (error) {
console.error("Error processing message:", error);
res.status(500).json({
error: "Error processing message",
details: error.message,
});
}
});
// Health check endpoint
server.get("/health", async (req, res) => {
res.json({
status: "healthy",
timestamp: new Date().toISOString(),
});
});
// Diagnostic endpoint
server.get("/api/config", async (req, res) => {
res.json({
botId: process.env.BOT_ID ? "Configured" : "Missing",
tenantId: process.env.BOT_TENANT_ID ? "Configured" : "Missing",
appType: process.env.BOT_TYPE ? "Configured" : "Missing",
port: port,
nodeVersion: process.version,
});
});
// Gracefully shutdown HTTP server
[
"exit",
"uncaughtException",
"SIGINT",
"SIGTERM",
"SIGUSR1",
"SIGUSR2",
].forEach((event) => {
process.on(event, () => {
server.close();
});
});
Below is my teamsBot.js
.
const {TeamsActivityHandler, TurnContext} = require("botbuilder");
class TeamsBot extends TeamsActivityHandler {
constructor() {
super();
this.onMessage(async (context, next) => {
console.log("Running with Message Activity.");
console.log("Message received:", context.activity.text); // Log the incoming message
const removedMentionText = TurnContext.removeRecipientMention(
context.activity
);
const txt = removedMentionText
.toLowerCase()
.replace(/\n|\r/g, "")
.trim();
await context.sendActivity(`Echo: ${txt}`);
// By calling next() you ensure that the next BotHandler is run.
await next();
});
// Listen to MembersAdded event, view https://docs.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bots-notifications for more events
this.onMembersAdded(async (context, next) => {
const membersAdded = context.activity.membersAdded;
for (let cnt = 0; cnt < membersAdded.length; cnt++) {
if (membersAdded[cnt].id) {
await context.sendActivity(
`Hi there! I'm a Teams bot that will echo what you said to me.`
);
break;
}
}
await next();
});
}
}
module.exports.TeamsBot = TeamsBot;
As part of my manifest.json
in appPackage zip file, here is the configuration.
{
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.17/MicrosoftTeams.schema.json",
"version": "1.0.0",
"manifestVersion": "1.17",
"id": "<some_id>",
"name": {
"short": "testbot2",
"full": "testbot2"
},
"staticTabs": [
{
"entityId": "conversations",
"scopes": ["personal"]
},
{
"entityId": "about",
"scopes": ["personal"]
}
],
"bots": [
{
"botId": "<bot_id_here>",
"scopes": ["personal", "team", "groupChat"],
"isNotificationOnly": false,
"supportsCalling": false,
"supportsVideo": false,
"supportsFiles": false
}
],
"validDomains": [
"<azure_domain_url_without_https>"
],
"webApplicationInfo": {
"id": "<microsoft_client_(app)_id_here>",
"resource": "<azure_hosted_domain_url_with_https>"
},
"devicePermissions": ["notifications"],
"defaultGroupCapability": {
"team": "bot",
"groupchat": "bot",
"meetings": "bot"
}
}
Also I have added other permissions in the manifest.json. Thank you.
Question: How do I make my teams app hit the endpoint /api/messages
and trigger TeamsBot.onMessage()
?
Upvotes: 0
Views: 37