Unable to initiate a new conversation with botframework and Microsoft teams - botframework

I am trying to follow the steps here: https://github.com/getazureready/teamsdev/blob/main/Lab%204%20-%20Conversational%20Bots.md (Exercise 3). I am running this as instructed:
await adapter.continueConversation(conversationReference, async turnContext => {
await turnContext.sendActivity(message);
});
However, this is not starting a new conversation in the channel, it replies to the same conversation initiated by the user. How do we start a new conversation in the channel?

conversationReference has an id property inside there, which has the actual main chat id, and can also have a reference to a specific message on the end, e.g.:
[long string] = conversation itself, vs
[long string];messageid=[short string]
if you use option 2, it will reply to an existing thread, but without that it will start a new thread.
So, in your context, modify the conversationReference's ID and remove the ;messageid=[short string] part

Related

Fetch the message sent by the bot before restarting the session

I know that I can get a message object using await ctx.fetch_message(mesId). Although If I send a message, and then start the bot's session (Restart the Client). The script cannot see the message. Is there any way to get rid of this problem?
Also, it's worth mentioning that I use discord.Bot type user not discord.Client
First of all there is no ctx.fetch_message ref
It should be ctx.channel.fetch_message Keep in mind you can get another channel by using await bot.get_channel(ID) and then fetch the message.
Your code should look like this:
# using another channel
channel = await bot.get_channel(123456)
message = await channel.fetch_message(123456)
# or using ctx
message = await ctx.channel.fetch_message(123456)
Docs

How to detected dead conversation references when using proactive conversations

We are using ContinueConversationAsync to send a Proactive Message to existing conversations which is working, what we want it a way to detect if that conversation is still active for instance if the conversation channel is webchat that session may no longer exists or a teams channel and the user has now left the organisation. Otherwise our ConversationReference table will just grow indefinably. At the moment SetProactiveMessage still just continues with no error even if there is no longer a user on the other end.
var conversationReference = botProactiveMessageConversation.ConversationReferenceJson.FromJson<ConversationReference>();
conversationReference.ActivityId = null;
MicrosoftAppCredentials.TrustServiceUrl(conversationReference.ServiceUrl);
await defaultAdapter.ContinueConversationAsync(botProactiveMessageConversation.BotAppId, conversationReference, async (ITurnContext turnContext, CancellationToken cancellationToken) =>
{
turnContext.SetProactiveMessage(botProactiveMessageConversation.ProactiveMessageData);
await dialogBot.OnTurnAsync(turnContext, cancellationToken);
}, default);
Unfortunately, there is no concept of a dead conversation in Direct Line. Subsequently, there is no method you can rely upon that is built in. A conversation's Conversation.Id is stored by the service for 14 days (subject to change, so don't rely on this as a rule) at which point it is purged. When storing your conversation reference, you can append a lastAccessed date and, when your time threshold is reached, it is purged from your store.
As for determining if a member is still part of a team or in an org, you will need to rely on a separate service call. Your best bet would be to use Microsoft's Graph API to check statuses.
Hope of help!

onTurn error for Teams bot on certain Teams system messages

I have a bot (based on the old core-bot-sample) that is deployed to Microsoft Teams. Sometimes, when there is a notification event in Teams such as New Channel Added or Channel Deleted (or possible User Added/Removed), I am getting the following onTurn Error: "error":"Cannot read property 'length' of undefined". By looking at the code, it seems the Welcome Message code is to blame. The only length property is on context.activity.membersAdded, so that must be causing the issue. But I don't understand exactly what is happening. Based on the statement below, the event must be triggering a ConversationUpdate activity, but without the membersAdded property. Can anyone shed some light on what this activity is that Teams is triggering, and what I should add to this welcome message statement to prevent the error message from occuring? To clarify, the error message is coming in the Posts channel of the Team/Channel where the event such as channel removal message is coming.
Code section where I think the error is occurring:
} else if (context.activity.type === ActivityTypes.ConversationUpdate) {
// Handle ConversationUpdate activity type, which is used to indicates new members add to
// the conversation.
// see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
// Do we have any new members added to the conversation?
if (context.activity.membersAdded.length !== 0) {
// Iterate over all new members added to the conversation
for (var idx in context.activity.membersAdded) {
// Greet anyone that was not the target (recipient) of this message
// the 'bot' is the recipient for events from the channel,
// context.activity.membersAdded == context.activity.recipient.Id indicates the
// bot was added to the conversation.
if (context.activity.membersAdded[idx].id === context.activity.recipient.id) {
// Welcome user.
await context.sendActivity('Hi! I\'m the IT Innovation Bot. I can answer questions about the innovation team and capture your innovation ideas. Let me know how I can help!')
}
}
}
}
It looks like that would fail for any activity where the type was ConversationUpdate, but the JSON payload doesn't contain the membersAdded object. The list of those events can be found here:
https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/subscribe-to-conversation-events?tabs=json
You could test this by firing one of the non-membersAdded events (for example, add a new channel to the team, or remove a member). You could probably fix this by doing a null check on the membersAdded object.

Responding to Conversations async: Graph or Bot?

I have a Teams Message extension that returns a Task response which is a medium sized embedded web view iFrame
This is working successfully; including added a custom Tab within the channel and other nice magic calls to Microsoft Graph.
What I am confused about is how to do (and this is probably my not understanding the naming of things)
insert "something" Back into the Message/Post stream which is a link to newly created Tab ... like the what you get when you have a "configureTabs" style Tab created -- there is a friendly Message (Post) in the chat pointing to this new Tab.
do I do this with Microsoft Graph or back through the Bot?
the code that does the communication may be a different service elsewhere that is acting async ... so it needs to communicate with something somewhere with context. Confused if this is the Bot with some params or Microsoft Graph with params.
how to insert an image (rather than a link to the tab) into the Message/Post stream -- but showing the image not a link off to some random URL (ie: )
could not find any samples that do this; again, will be async as per above; but the format of the message will be a Card or something custom?
So just to be clear, a Task Response is NOT the same as a Tab, albeit that they might end up hosted in the same backend web application (and also albeit that your TAB can actual bring up your Task Response popup/iframe using the Teams javascript library).
Aside from that, in order to post something back to the channel, like when the Tab is created, there are two ways to do so:
First is to use Graph Api's Create ChatMessage option (this link is just for a channel though - not sure if your tab/task apply to group chats and/or 1-1 chats as well).
2nd Option is to have a Bot be part of your application as well. Then, when you're ready to send something to the channel, you'd effectively be sending something called a "pro-active messaging". You need to have certain reference data to do this, which you would get when the bot is installed into the channel ("conversation reference", "ServiceUrl", and so on). I describe this more in my answer at Programmatically sending a message to a bot in Microsoft Teams
With regards sending the image, either of the above would work here too, in terms of how to send the image. As to the sending of an image, you'd need to make use of one of the kinds of "Cards" (basically "richer" messages than just raw text). You can learn more about this at Introducing cards and about the types of cards for Teams at Card reference. There are a few that can be used to send an image, depending on perhaps what else you want the card to do. For instance, an Adaptive Card can send an image, some text, and an action button of some sort.
Hope that helps
To close the loop for future readers.
I used the following Microsoft Graph API docs, and the posting above, and this is working: Create chatMessage in a channel and Creating a Custom Microsoft Graph call from the SDK
The custom graph call (as it is not implemented in the .NET SDK at the time of this response) looks something like:
var convoReq = $"https://graph.microsoft.com/beta/teams/{groupId}/channels/{channelId}/messages";
var body = this.TeamsMessageFactory(newCreatedTabUrl, anotherstring).ToJson();
var postMessage = new HttpRequestMessage(HttpMethod.Post, convoReq)
{
Content = new StringContent(body, System.Text.Encoding.UTF8, "application/json")
};
await _graphClient.CurrentGraphClient.AuthenticationProvider.AuthenticateRequestAsync(postMessage);
var response = await _graphClient.CurrentGraphClient.HttpProvider.SendAsync(postMessage);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return true;
}
The groupId and channelId are found elsewhere; and the TeamsMessageFactory is just some boilerplate that serialized the C# object graph for the POST request, as detailed in Create chatMessage in a channel

Azure, SubscriptionClient.OnMessage, and Sessions

Does the Azure Service Bus Subscription client support the ability to use OnMessage Action when the subscription requires a session?
I have a subscription, called "TestSubscription". It requires a sessionId and contains multipart data that is tied together by a SessionId.
if (!namespaceManager.SubscriptionExists("TestTopic", "Export"))
{
var testRule = new RuleDescription
{
Filter = new SqlFilter(#"(Action='Export')"),
Name = "Export"
};
var subDesc = new SubscriptionDescription("DataCollectionTopic", "Export")
{
RequiresSession = true
};
namespaceManager.CreateSubscription(sub`enter code here`Desc, testRule);
}
In a seperate project, I have a Service Bus Monitor and WorkerRole, and in the Worker Role, I have a SubscriptionClient, called "testSubscriptionClient":
testSubscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, _topicName, CloudConfigurationManager.GetSetting("testSubscription"), ReceiveMode.PeekLock);
I would then like to have OnMessage triggered when new items are placed in the service bus queue:
testSubscriptionClient.OnMessage(PersistData);
However I get the following message when I run the code:
InvalidOperationException: It is not possible for an entity that requires sessions to create a non-sessionful message receiver
I am using Azure SDK v2.8.
Is what I am looking to do possible? Are there specific settings that I need to make in my service bus monitor, subscription client, or elsewhere that would let me retrieve messages from the subscription in this manner. As a side note, this approach works perfectly in other cases that I have in which I am not using sessioned data.
Can you try this code:
var messageSession=testSubscriptionClient.AcceptMessageSession();
messageSession.OnMessage(PersistData);
beside of this:
testSubscriptionClient.OnMessage(PersistData);
Edit:
Also, you can register your handler to handle sessions (RegisterSessionHandler). It will fire your handle every new action.
I think this is more suitable for your problem.
He shows both way, in this article. It's for queue, but I think you can apply this to topic also.

Resources