Channel data properties : Carousel? - c#

I want to get media from a website. That media should be listed something like Carousel card template.
With loop i want to store all the media in one object.
Have this :
resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
resultMessage.Attachments = new List<Attachment>();
var fbObject = new object[activities.Count];
while (!stop)
{
if (activities[counter].MediaTypeValue != (int)MediaTypeEnum.Video)
{
fbObject[counter] = new
{
type = "image",
payload = new object[]
{
new
{
url = activities[counter].DocumentPath
},
}
};
}
else
{
fbObject[counter] = new
{
type = "video",
buttons = new object[]
{
new
{
type = "web_url",
url = activities[counter].DocumentPath,
title = activities[counter].FirstName + " " + activities[counter].LastName + " posted " + BotHelper.UserPosted(activities[counter].MediaTypeValue),
webview_height_ratio = "compact",
messenger_extensions = true
}
}
};
}
counter--;
if (counter < 0)
stop = true;
}
resultMessage.ChannelData = JObject.FromObject(new { fbObject }); ;
await context.PostAsync(resultMessage);
But Facebook messenger does not render it as "carousel".
Any idea how to show object like Carousel type of card ?

Facebook will render the carousel if you have Attachments in your message. Your attachments collection is empty and you are sending channel data info, which won't be rendered as a carousel.
Both Image and Video are supported attachments in BotFramework and you can just use the available rich cards instead of using channel data to send them to the user.
Take a look to the RichCards sample to understand how to create each of the supported cards. Also, you might also want to review the Carousel sample.
Finally, it's always a good idea to review the documentation around attachments and Rich cards. See this and this.

Related

How to use Adaptive Cards on Teams Messaging Extension?

I'm developing a Teams Message Extension and I'm using ThumbnailCard to display my results, however I wanted to use a custom adaptive card. Is that possible?
var resultCardList = GetAttachments(title);
var response = new ComposeExtensionResponse(new ComposeExtensionResult("list", "result"));
response.ComposeExtension.Attachments = resultCardList.ToList();
return response;
foreach (var contract in contractItems)
{
var lastModified = (DateTime)contract["Modified"];
var justificativa = contract["JustificativaContrato"];
var card = new ThumbnailCard
{
Title = $"{contract.Client_Title} - {lastModified.ToShortDateString()} {lastModified.ToLongTimeString()}",
Text = $"Justificativa: {justificativa}",
Tap = new CardAction { Type = "openUrl", Value = $"{Tenant}{ContractList.DefaultEditFormUrl}?ID={contract.Id}" },
Images = new List<CardImage> { new CardImage("http://lorempixel.com/640/480?rand=" + DateTime.Now.Ticks.ToString()) }
};
cardList.Add(card
.ToAttachment()
.ToComposeExtensionAttachment());
}
return cardList;
I've tried to use the below method to generate the Adaptive Card and just add it to the list:
private static Microsoft.Bot.Connector.Attachment CreateAdaptiveCardAttachment()
{
// combine path for cross platform support
string[] paths = { ".", "Cards", "welcomeCard.json" };
string fullPath = Path.Combine(paths);
var adaptiveCard = System.IO.File.ReadAllText(#"Cards\welcomeCard.json");
return new Microsoft.Bot.Connector.Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(adaptiveCard),
};
}
The messaging extension does not allow sending adaptive cards like that.
It requires using the "MessagingExtensionResult" of the framework and just the card sent in the response. The documentation is a bit lacking here.
When you get a call from the messaging extension its action is of type "composeExtension/query"
Create the general "result" list like this:
var invokeResponse = new MessagingExtensionResponse();
var results = new MessagingExtensionResult
{
AttachmentLayout = "list",
Type = "result",
Attachments = new List<MessagingExtensionAttachment>(),
};
For each result in the list you need to create a MessagingExtensionAttachment like this: (Note: Cards need to have a preview!)
results.Attachments.Add(new MessagingExtensionAttachment
{
ContentType = "application/vnd.microsoft.teams.card.adaptive",
Content = JsonConvert.DeserializeObject(cardData),
Preview = new Attachment
{
ContentType = "application/vnd.microsoft.card.thumbnail",
Content = new AttachmentContent
{
text = "Project: " + task.ProjectName,
title = task.Name,
},
}
});
Finally send the result as "InvokeResponse"
return new InvokeResponse
{
Body = invokeResponse,
Status = 200,
};
While "content" of the attachment is the full adaptive card.
You can find an example for the response in json here:
https://learn.microsoft.com/de-de/microsoftteams/platform/concepts/messaging-extensions/search-extensions#response-example
You can freely mix card types based on that, but i never got that working tho...as of now you need to limit to one specific card type as far as i know.
All above is if you're using
Microsoft.Bot.Builder.Teams
Microsoft.Bot.Connector.Teams
Microsoft.Bot.Schema.Teams
in the latest versions.

How to call a AVPlayer in XAMARIN iOS during notification instead of 30 second max duration notification sound?

I need to play a audio file which is 3 minutes length. But default notification sound does not play more than 30 seconds. So my idea is Calling a Avplayer
which will play my desired audio. But i do not know how to call this. Can any one please help me. I will be very grateful.
I am attaching my notification method here.
public void AVPlayer()
{
NSUrl songURL;
if (!MusicOn) return;
//Song url from your local Resource
songURL = new NSUrl("azan.wav");
NSError err;
player = new AVAudioPlayer(songURL, "Song", out err);
player.Volume = MusicVolume;
player.FinishedPlaying += delegate {
// backgroundMusic.Dispose();
player = null;
};
//Background Music play
player.Play();
}
public void CreateRequest(JamatTime jamat)
{
// Create action
var actionID = "pause";
var title = "PAUSE";
var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);
// Create category
var categoryID = "message";
var actions = new UNNotificationAction[] { action };
var intentIDs = new string[] { };
var categoryOptions = new UNNotificationCategoryOptions[] { };
var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);
// Register category
var categories = new UNNotificationCategory[] { category };
UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories));
// Rebuild notification
var content = new UNMutableNotificationContent();
content.Title = " Jamat Time alert";
content.Badge = 1;
content.CategoryIdentifier = "message";`enter code here`
content.Sound = UNNotificationSound.GetSound("sample.wav");
var times = new string[] { jamat.Asr, jamat.Dhuhr, jamat.Faijr, jamat.Ishaa, jamat.Jumah, jamat.Maghib };
int id = 0;
foreach (var time in times)
{
var ndate = DateTime.ParseExact(time, "h:mm tt", null);
var date = new NSDateComponents()
{
Calendar = NSCalendar.CurrentCalendar,
Hour = ndate.Hour,
Minute = ndate.Minute,
Second = 0
};
content.UserInfo = new NSDictionary<NSString, NSString>(
new NSString[] {
(NSString)"time1",
(NSString)"time2"
},
new NSString[] {
(NSString)DateTime.Now.ToString("h:mm tt"),
(NSString)time
});
var trigger = UNCalendarNotificationTrigger.CreateTrigger(date, true);
// ID of Notification to be updated
var request = UNNotificationRequest.FromIdentifier(id++.ToString(), content, trigger);
// Add to system to modify existing Notification
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err1) =>
{
if (err1 != null)
{
Console.WriteLine("Error: {0}", err1);
}
Console.WriteLine($"Success: {request}");
});
}
}
You can't play an audio file instead of the UNNotificationSound.
There's no way to trigger the player's play method when the local notification comes. You could only configure the sound property using the code you post above. And the file should be embedded in the bundle resource.
It seems you are aware of UNNotificationSound: https://developer.apple.com/documentation/usernotifications/unnotificationsound?language=objc. But I still want to remind you of the file's format and length limitations.
Finally I have solved my problem.
When a notification fires then WillPresentNotification() method hits and I simply call the AVplayer there and perfectly working. If u want to play sound via UNNotificationSound then not possible because that is limited by 30 second duration..but problem this works only in foreground.

Botframework V4: Video attachment on messenger

Hi i tried all these methods of attaching a video to a bot. All of them are working fine in bot emulator. But when i publish it to messenger it is throwing an exception . (I can't see the exception by the way i just know because of the message. Is there a way to see or log exceptions?). Is video card not supported in messenger? Or is youtube not supported as an url link?
Here are the codes:
AddStep(async (stepContext, cancellationToken) =>
{
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>();
reply.Attachments.Add(GetVideoCard().ToAttachment());
await stepContext.Context.SendActivityAsync(reply, cancellationToken);
return await stepContext.NextAsync();
});
////////////////
private static VideoCard GetVideoCard()
{
var videoCard = new VideoCard
{
Title = "Budgeting Introduction",
Subtitle = "by Finko",
Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = "https://www.youtube.com/watch?v=XLo1geVokhA",
},
},
Buttons = new List<CardAction>
{
new CardAction()
{
Title = "Learn More at Finko.PH",
Type = ActionTypes.OpenUrl,
Value = "https://m-moreno.wixsite.com/finkoph?fbclid=IwAR1NVtlyKfzZ0mYFIWva8L-d8TUv4KFpt_m1i1ij3raT-pbWr2c3-kqzB2Q",
},
},
};
return videoCard;
}
and
AddStep(async (stepContext, cancellationToken) =>
{
var activity = stepContext.Context.Activity;
await stepContext.Context.SendActivityAsync(CreateResponse(activity, CreateVideoCardAttacment()));
return await stepContext.NextAsync();
});
////////////////////////
private Activity CreateResponse(Activity activity, Attachment attachment)
{
var response = activity.CreateReply();
response.Attachments = new List<Attachment>() { attachment };
return response;
}
private Attachment CreateVideoCardAttacment()
{
return new VideoCard()
{
Title = "Are you a Seafarer? OFW? FREE PERSONAL FINANCIAL ADVICE HERE!!",
Media = new List<MediaUrl>()
{
new MediaUrl("https://www.youtube.com/watch?v=XLo1geVokhA")
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Type = ActionTypes.OpenUrl,
Title = "Learn More at Finko.PH",
Value = "https://m-moreno.wixsite.com/finkoph?fbclid=IwAR1NVtlyKfzZ0mYFIWva8L-d8TUv4KFpt_m1i1ij3raT-pbWr2c3-kqzB2Q"
}
},
Subtitle = "by Finko.Ph",
Text = "Are you tired of getting bogus financial advice? Tired of having 'kape' just to find out it was networking, or a pyramid scheme? Tired of scouring the internet for HOURS but not finding what you're looking for? We're here to help! We give financial advice and will educate you on financial literacy topics, ABSOLUTELY FREE!!"
}.ToAttachment();
}
and
Activity reply = stepContext.Context.Activity.CreateReply();
var card = new VideoCard
{
Title = "Finko.ph",
Media = new List<MediaUrl>()
{
new MediaUrl("https://www.youtube.com/watch?v=XLo1geVokhA")
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Type = ActionTypes.OpenUrl,
Title = "Learn More at Finko.PH",
Value = "https://m-moreno.wixsite.com/finkoph?fbclid=IwAR1NVtlyKfzZ0mYFIWva8L-d8TUv4KFpt_m1i1ij3raT-pbWr2c3-kqzB2Q"
}
},
};
reply.Attachments.Add(card.ToAttachment());
await stepContext.Context.SendActivityAsync(reply);
return await stepContext.NextAsync();
and
var reply1 = stepContext.Context.Activity.CreateReply();
var attachment1 = new Attachment
{
ContentUrl = "https://www.youtube.com/watch?v=XLo1geVokhA",
ContentType = "video/mp4",
Name = "imageName1",
};
reply1.Attachments = new List<Attachment>() { attachment1 };
await stepContext.Context.SendActivityAsync(reply1, cancellationToken);
return await stepContext.NextAsync();
All of these codes are working in bot emulator but not in messenger. Any help would be appreciated thank you.
The BotFramework converts Video Cards into Media Templates for Facebook Messenger, and per Facebook's Developer documentation, media templates do not allow any external URLs, only those on Facebook. You must either upload the video to Facebook or provide a URL directly to the mp4 file which, unfortunately, YouTube doesn't make readily available.
For more details, take a look at Facebooks documentation regarding Media Templates.

C# - Change Streams in MongoDB with $match

I'm trying to narrow down the Change streams in MongoDB to a specific document matching on the document's _id as I have many documents in one collection. Anyone know how to do this in C#? Here's the latest that I've tried to no avail:
{
var userID = "someIdHere";
var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"_id", userID}
}
}
};
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Class>>().Match(match);
var options = new ChangeStreamOptions { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
var cursor = collection.Watch(pipeline, options).ToEnumerable();
foreach (var change in cursor)
{
Debug.WriteLine(change.FullDocument.ToJson());
Debug.WriteLine(change.ResumeToken + " " + change.OperationType);
}
}
If I change the cursor to what you see below, it works but it returns the world and returns the change stream when there's activity on any of the _id's present in the document. That's not what I'm going for.
var cursor = collection.Watch().ToEnumerable();
After searching near and far, I was able to piece together bits and pieces of information from other issues I found online and came up with the solution below. It works like a charm!
Not only was I able to filter Change Stream so that it only recognizes updates but I was able to narrow down the stream to a SPECIFIC document _id AND made it even more granular finding a specific change to a field called LastLogin for that _id. This is what I desired as the default Change stream returned any update that happened on the collection.
I hope this helps someone that come across the same issue I did. Cheers.
{
var db = client.GetDatabase(dbName);
var collectionDoc = db.GetCollection<BsonDocument>(collectionName);
var id = "someID";
//Get the whole document instead of just the changed portion
var options = new ChangeStreamOptions
{
FullDocument = ChangeStreamFullDocumentOption.UpdateLookup
};
//The operationType of update, where the document id in collection is current one and the updated field
//is last login.
var filter = "{ $and: [ { operationType: 'update' }, " +
"{ 'fullDocument._id' : '" + id + "'}" +
"{ 'updateDescription.updatedFields.LastLogin': { $exists: true } } ] }";
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<BsonDocument>>().Match(filter);
var changeStream = collectionDoc.Watch(pipeline, options).ToEnumerable().GetEnumerator();
try
{
while (changeStream.MoveNext())
{
var next = changeStream.Current;
Debug.WriteLine("PRINT-OUT:" + next.ToJson());
}
}
catch (Exception ex)
{
Debug.WriteLine("PRINT-OUT: " + ex);
}
finally
{
changeStream.Dispose();
}
}

How to use Microsoft bot framework to send audio to user through facebook messenger (C#)

How to use microsoft bot framework to send audio to user through facebook messenger. I cannot use the richcard to send it out, or I did something wrong, please help me solve the problems.
In Bot Framework Rich cards can be used to send audio card. They can be send as an attachment to the user.
Root Dialog
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var reply = context.MakeMessage();
reply.Attachments.Add(GetAudioCard());
await context.PostAsync(reply);
context.Wait(MessageReceivedAsync);
}
private static Attachment GetAudioCard()
{
var audioCard = new AudioCard
{
Title = "Havana",
Subtitle = "Camila Cabello",
Image = new ThumbnailUrl
{
Url = "https://en.wikipedia.org/wiki/Havana_(Camila_Cabello_song)#/media/File:Havana_(featuring_Young_Thug)_(Official_Single_Cover)_by_Camila_Cabello.png"
},
Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = "http://213.32.113.82/music/Now%20Thats%20What%20I%20Call%20Running%20(2018)/CD1/02.%20Camila%20Cabello%20feat.%20Young%20Thug%20-%20Havana.mp3"
}
},
Buttons = new List<CardAction>
{
new CardAction()
{
Title = "Read More",
Type = ActionTypes.OpenUrl,
Value = "https://en.wikipedia.org/wiki/Havana_(Camila_Cabello_song)"
}
}
};
return audioCard.ToAttachment();
}

Categories

Resources