Proactive messaging bot in Teams without mentioning the bot beforehand - node.js

I'm using the Microsoft bot-framework to create a bot and integrate it into teams.
Part of the bot's requirements include proactively messaging users once per day. From what I understand, I can only message users that has been added to the team/groupChat after the bot, or that have messaged the bot directly.
My question is - can I somehow bypass this limitation?
A friend of my referred me to a new feature of graphAPI, as part of the new beta version - https://learn.microsoft.com/en-us/graph/api/user-add-teamsappinstallation?view=graph-rest-beta&tabs=http.
To me it doesn't seem like it could be related to the solution since I'm not getting any data back in the response, so if I have no conversationReference object I still can't message the user.
At the moment my solution is to simply broadcast a message in the channel when it's added, asking users to "register" with it by messaging it. Anyone has any other suggestion?

The easiest way is to:
Install the bot for the team
Query the Team Roster -- The link in Step 3 has an alternative way to do this towards the bottom
Create a conversation with the user and send a proactive message
There's a lot of code in those links and it's better to just visit them than to copy/paste it here.
The end of Step 3 also mentions trustServiceUrl, which you may find handy if you run into permissions/auth issues when trying to send a proactive message.
Edit for Node:
Install Necessary Packages
npm i -S npm install botbuilder-teams#4.0.0-beta1 botframework-connector
Note: The #<version> is important!
Prepare the Adapter
In index.js
const teams = require('botbuilder-teams');
adapter.use(new teams.TeamsMiddleware());
Get the Roster
// Get Team Roster
const credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
const connector = new ConnectorClient(credentials, { baseUri: context.activity.serviceUrl });
const roster = await connector.conversations.getConversationMembers(context.activity.conversation.id);
Send the Proactive Message
const { TeamsContext } = require('botbuilder-teams');
// Send Proactive Message
const teamsCtx = TeamsContext.from(context);
const parameters = {
members: [
roster[0] // Replace with appropriate user
],
channelData: {
tenant: {
id: teamsCtx.tenant.id
}
}
};
const conversationResource = await connector.conversations.createConversation(parameters);
const message = MessageFactory.text('This is a proactive message');
await connector.conversations.sendToConversation(conversationResource.id, message);
Trust the ServiceUrl, as Necessary
Read about it. You'd want this before the message is sent.
MicrosoftAppCredentials.trustServiceUrl(context.activity.serviceUrl);

EDIT: The Graph API you've referenced is only necessary if you wish to proactively message a user who is not in a channel/groupChat where the bot is installed. If you need to proactively message only people who are in context where the bot is installed already, the answer from mdrichardson is the easiest possible method.
We've identified a couple of issues with the Graph API beta endpoint you referenced that should be fixed in the near term. In the meantime workarounds are as follows:
Calling:
POST https://graph.microsoft.com/beta/me/teamwork/installedApps/
{"teamsapp#odata.bind":"https://graph.microsoft.com/beta/appcatalogs/teamsapps/APP-GUID"}
Will install an app in the personal scope of a user.
Known issue: Currently, if the app contains a bot, then installation will not lead to creation of thread between the bot and the user. However to ensure that any missing chat threads, get created, call:
GET https://graph.microsoft.com/beta/me/chats?$filter=installedApps/any(x:x/teamsApp/id eq 'APP-GUID')
Calling:
GET https://graph.microsoft.com/beta/me/chats?$filter=installedApps/any(x:x/teamsApp/id eq 'APP-GUID')
Gets the chat between a user and an app containing a bot.
Known issue: Calling this API will lead to sending a conversation update event to the bot even though there were no updates to the conversation. Your bot will essentially get two install events and you'll need to make sure you don't send the welcome message twice.
We'll also be adding more detailed documentation for the proactive messaging flow using these Graph APIs

Related

Shopify Webhook Real Time changing

is there an api on shopify where I can see real time when data changes ? Maybe I have a node server and I use sockets to see when anyone has bought anything from my shop that I get a notification via nodejs on my backend. is it possible ? a few websites has this, they offers you to sell on their site and you can see real time changes data when anything was bought
Yes, you can subscribe to multiple Webhooks to get notified when a change occurs on your shop. Using the REST Admin API, available webhook event topics include:
orders/create: occurs whenever an order is created / someone buys from your shop.
orders/paid: occurs whenever an order is paid.
orders/fulfilled: occurs whenever an order is fulfilled.
orders/cancelled: occurs whenever an order is cancelled.
Use the /admin/api/2023-01/webhooks.json endpoint to subscribe to a webhook:
// Node.js - Session is built by the OAuth process
const webhook = new shopify.rest.Webhook({session: session});
webhook.topic = "orders/create";
webhook.address = "https://example.hostname.com/";
// format you want to receive the event data in
webhook.format = "json"; // or XML
// fields you want to receive
webhook.fields = [
"id",
"note"
];
await webhook.save({
update: true,
});
You can also use the GraphQL Admin API for the same purpose.

Dsharp GetAllMembersAsync() psermison needed

I am trying to get all the members of a guild. When i use GetAllMembersAsync() i get an exception of unauthorized 403. I tried to give the bot all permissions but I am still getting the exception.
Minimum reproducible example of code that may return this issue
private static async Task<IReadOnlyCollection<DiscordMember>>
GetEveryone(DiscordClient client, DiscordGuild guild)
{
DiscordGuild myGuild = await client.GetGuildAsync(guild);
var members = myGuild.GetAllMembersAsync();
return members;
}
Thx for your help
It's been a while since the question was asked but I wanted to answer for anyone who comes here in the future.
When creating your client you must declare your intentions with DiscordConfiguration() and not just by giving the bot permission in Discord's developer portal. To be clear, both your bot and Discord's developer portal must have matching configurations to avoid an HTTP 403 or 401 error. In the main method for creating your discord client you likely have something like this set up:
var discord = new DiscordClient(new DiscordConfiguration()
{
Token = tokenHere,
TokenType = TokenType.Bot
});
To declare this intention you must set the Intents configuration as well:
var discord = new DiscordClient(new DiscordConfiguration()
{
Token = tokenHere,
TokenType = TokenType.Bot,
Intents = DiscordIntents.All
});
The minimum Intent for your purpose is DiscordIntents.GuildMembers, however, there are many Intents and you can declare them individually. Be sure to check out the examples from DSharp+.
Important: Server Member intents are a part of the Privileged Gateway Intents set. You must set the SERVER MEMBERS INTENT configuration in the Discord Developer Portal Bot tab to true to act upon any Discord members in any way. Not all bots will have this access immediately but generally, most developers will be able to declare this intent after a short time.

Microsoft Teams Bot: replyToId seems to be ignored

i am using the microsoft bot sdk in combination with an restify server (In package.json: "botbuilder": "^4.11.0"). I start a waterfall dialog that triggers a long running API. I save the the conversation reference and the id of the sent message to create an reply after the API call is completed:
replyToId = (await stepContext.context.sendActivity({ attachments: [ac]})).id; (in Dialog)
this.conversationReference = TurnContext.getConversationReference(context.activity); (in bot.ts)
After the completion of the API call, I want to create a reply to the last message of the dialog:
await this.adapter.continueConversation(this.conversationReference, async turnContext => {
await turnContext.sendActivity(newMessage);
});
newMessage is the Activity-object that contains further information for the user about the result of the API call.
The problem is that newMessage is not displayed as an reply to the existing message but as a separate message, although newMessage.replyToId is set to this.replyToId:
Additional information: Both messages, the last of the dialog and the "reply" are adaptive cards, but it does not make a difference if I send just simple text, same behaviour.
Would be grateful for any help :)
Instead of using "replyToId", put the id of the message you want to reply to, at the end of the conversation reference. As an example, if your conversationReference has a conversationId of 19:ac....cf#thread.skype, change it to: 19:ac...cf#thread.skype;messageid=12345678, where 12345678 is what you are currently using for "replyToId"

Botframework LUIS Slack bot only reply when name is mentioned

I'm creating a bot in slack using Microsoft's botframework and LUIS and in Node.js. Currently my bot will reply every time someone says something in the channel, however I want my bot to only reply when its name is mentioned in my slack channel. i.e. #my-bot do this
How would I approach this? Would I have to add slack api in order to do this?
One way I'm thinking is to create an entity to check for if #my-bot is mentioned, and if it is then reply and if not then don't. However, I feel there are better ways in doing this.
Thanks.
Edit:
dialog.onDefault(function (session) {
var msg = new builder.Message(session).entities();
console.log(msg);
console.log(session);
session.endDialog('Default Dialog');
});
I've looked through both msg and session and the Entities of both are empty.
I was able to use session.message.entities to use mentioned to know whenever the bot was mentioned.

How to detect when bot was added to conversation and other events?

I am testing a bot that I am building using the Bot Framework. The emulator for local testing that Microsoft created has several events that can be provided to the bot to solicit a response.
I looked at the GitHub samples provided for Node.js here, but I can not find any example that responds to the different events within the Bot Framework Emulator.
The states are:
Bot Added to Conversation
Bot Removed from Conversation
User Added to Conversation
User Removed from Conversation
End of Conversation
Ping
Delete User Data
The API also does not make it clear how to achieve any of these actions.
Does anyone have any insight on where I should be looking for a example, or the API entries that I should be using?
In response to one of the answers, I did try code -
.onDefault(function (session) { console.log(session.message.type); }
But it only ever display "message" if a message was sent by the user.
The incoming message.type field will have "BotAddedToConversation" etc.
For the Node SDK, the botConnectorBot is able to trigger custom listeners on events using the on() handler.
Example
var builder = require('botbuilder');
var bot = new builder.BotConnectorBot({ appId: 'APPID', appSecret: 'APPSECRET' });
bot.on('DeleteUserData', function(message) {
// Handle Deleting User Data
});
More information can be found here.
You are also able to configure some standard messages using the configure() method.
Example
bot.configure({
userWelcomeMessage: "Hello... Welcome to the group.",
goodbyeMessage: "Goodbye..."
});
More information on what can be configured through options is located here.
Concerns
This is not part of the question, as the question was to identify how to listen to these events. But as a general concern, the event listener does not return a session object. It is unclear how to act once you handle the event.

Resources