Display adaptive card in facebook message, bot framework - c#

I have created an adaptive card with C# AdaptiveCard SDK. But, once I deployed to Facebook Messenger, it won't show the adaptive card.
The key part of code is like this: (including initialize IMessageActivity and set up its properties
var botActivity = (Microsoft.Bot.Connector.Activity)context.Activity;
IMessageActivity reply = botActivity.CreateReply();
reply.AttachmentLayout = AttachmentLayoutTypes.List;
reply.Attachments = new List<Attachment>();
AdaptiveCard adaptiveCard = new AdaptiveCard()
{
Body = new List<AdaptiveElement>
{
new AdaptiveColumnSet
{
Columns = new List<AdaptiveColumn>
{
new AdaptiveColumn
{
Items = new List<AdaptiveElement>
{
new AdaptiveTextBlock
{
Size = AdaptiveTextSize.Large,
Text = "*",
Color = AdaptiveTextColor.Warning
}
}
},
new AdaptiveColumn
{
Size = "1px",
Items = new List<AdaptiveElement>
{
new AdaptiveTextBlock
{
Text = "indicates mandatory fields",
Size = AdaptiveTextSize.Medium,
Wrap = true
}
}
}
}
},
new AdaptiveTextBlock()
{
Text = " ",
Spacing = AdaptiveSpacing.Medium,
}
},
Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Title = "Confirm",
DataJson = "{\"Type\": \"RequestBody\"}"
}
}
};
RenderedAdaptiveCard renderedAdaptiveCard = renderer.RenderCard(adaptiveCard);
Attachment plAttachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = renderedAdaptiveCard.OriginatingCard
};
reply.Attachments.Add(plAttachment);
await context.PostAsync(reply);
I also add the adaptive card to IMessageActivity attachment, and use context.PostAsync to post the reply with attachment back to user.
Anyone has any idea why I can't see the adaptive card in Facebook Messenger?

Related

Microsoft Graph upload large files

I am developing an aplication that send and email with one or multiple attachments via Microsoft Graph, but when try to upload file send me an error: ": Invalid total bytes specified in the Content-Range header"
i asume that i must specifi Range Value in same where, but no idea.
This is my code:
private static async void SenMailUsingMicrosoftGraph(List<String>Destinations, List<String>Cc, string HidenCopy, string Body, string Title, List<FileInfo>Filess);
{
ClientSecretCredential credential = new ClientSecretCredential("MyTenantID", "MyClientId", "MyClientSecret");
List<Recipient> recipientsDestinatarios = new List<Recipient>();
List<Recipient> recipientsCopias = new List<Recipient>();
foreach (var c in Destinations)
{
recipientsDestinatarios.Add(
new Recipient
{
EmailAddress = new EmailAddress
{
Address = c
}
});
}
foreach (var mail in Cc)
{
recipientsCopias.Add(
new Recipient
{
EmailAddress = new EmailAddress
{
Address = mail
}
});
}
#endregion
var message = new Microsoft.Graph.Message
{
Subject = Title,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = Body
},
ToRecipients = recipientsDestinatarios
,
CcRecipients = recipientsCopias
,
BccRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress=new EmailAddress{Address=Hiden}
}
}
};
GraphServiceClient graphClient = new GraphServiceClient(credential);
#endregion
#region adjuntar ficheros
var msgResult = await graphClient.Users["myemail#mycompany.com"].MailFolders.Drafts.Messages
.Request()
.WithMaxRetry(9)
.AddAsync(message);
foreach (var Archivo in Filess)
{
var attachmentContentSize = Archivo.Length;
var attachmentItem = new AttachmentItem
{
AttachmentType = AttachmentType.File,
Name = Archivo.Name,
Size = attachmentContentSize,
};
//initiate the upload session for large files
var uploadSession = await graphClient.Users["myemail#mycompany.com"].Messages[msgResult.Id].Attachments
.CreateUploadSession(attachmentItem)
.Request()
.PostAsync();
var maxChunkSize = 1024 * 320;
var allBytes = System.IO.File.ReadAllBytes(Archivo.FullName);
using (var stream = new MemoryStream(allBytes))
{
stream.Position = 0;
LargeFileUploadTask<FileAttachment> largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxChunkSize);
await largeFileUploadTask.UploadAsync();
}
}
await graphClient.Users["myemail#mycompany.com"].Messages[msgResult.Id].Send().Request().PostAsync();
}
I try something like this:
var content = new System.Net.Http.Headers.ContentRangeHeaderValue(0,MyFile.Length-1,MyFile.Length);
but i dont now how to asign this content variable, i think that must go in the uploadSession but dont know how.
------------------------------------EDIT------------------------------
included a Picture where see that the size of the attachment is not zero

How send money to paypal account from console app?

I use PayPal-NET-SDK for interact with PayPal system (sanbox). I have next code:
static void Main(string[] args)
{
try
{
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var payment = Payment.Create(apiContext, new Payment
{
intent = "order",
payer = new Payer
{
payment_method = "paypal"
},
transactions = new List<Transaction>
{
new Transaction
{
description = "Transaction description.",
invoice_number = "002",
amount = new Amount
{
currency = "USD",
total = "15.00",
},
payee = new Payee
{
email = "test1#gmail.com"
}
}
},
redirect_urls = new RedirectUrls
{
return_url = "site for redirect", // in my code there is normal url
cancel_url = "site for redirect""
}
});
var approval = payment.GetTokenFromApprovalUrl();
var url = payment.GetApprovalUrl();
payment.token = approval;
var response = payment.Execute(apiContext, new PaymentExecution {payer_id = "C598R54Q6P39G" });
}
catch (PaymentsException e)
{
Console.WriteLine(e.Response);
}
}
After executing this code i receive bad request error from PayPal ("Payer has not approved payment"). If go to link in url in debug, i get to PayPal confirm page, and after push continue button, payment executing withoue exceptions (but funds still same, money is not sending). How i can send money to other paypal wallet without redirect to PayPal aproving page?
Resolved by using payout (as i uderstand, payments use for client to merchant transfer).
static void Main(string[] args)
{
try
{
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var payout = Payout.Create(apiContext, new Payout
{
sender_batch_header = new PayoutSenderBatchHeader
{
email_subject = "Hello payout",
sender_batch_id = "ilab_Payout002",
recipient_type = PayoutRecipientType.EMAIL
},
items = new List<PayoutItem>
{
new PayoutItem
{
amount = new Currency
{
currency = "USD",
value = "17.5"
},
note = "Exchange is done!",
receiver = "ilab-test1#gmail.com",
recipient_type = PayoutRecipientType.EMAIL,
sender_item_id = "121341"
}
},
});
}
catch (PaymentsException e)
{
Console.WriteLine(e.Response);
}
}
}

Automatically video play in chat bot emulator

I am Adding a videos card to my chat bot.
var resultMessage = context.MakeMessage();
var bytes = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Videos/Cute.mp4"));
string videoData = Convert.ToBase64String(bytes);
resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
resultMessage.Attachments = new List<Microsoft.Bot.Connector.Attachment>();
VideoCard vc = new VideoCard()
{
// Title = $"hi",
// Subtitle = Address,
Media = new List<MediaUrl>()
{
new MediaUrl()
{
// Url = "https://i1.wp.com/thefreshimages.com/wp-content/uploads/2017/12/lord-shiva-hd-images.jpg?resize=3840%2C2160&ssl=1"
Url = "data:video/mp4;base64,"+ videoData
},
}
};
resultMessage.Attachments.Add(vc.ToAttachment());
await context.PostAsync(resultMessage);
It will play When user click the play button .But I want to play automatically.
Says here that Autostart property is true by default, so it should start playing automatically. You could try setting it to true and see if it works.
VideoCard vc = new VideoCard()
{
Media = new List<MediaUrl>()
{
new MediaUrl()
{
// Url = "https://i1.wp.com/thefreshimages.com/wp-content/uploads/2017/12/lord-shiva-hd-images.jpg?resize=3840%2C2160&ssl=1"
Url = "data:video/mp4;base64,"+ videoData
}
},
Autostart = true
};

Using Custom API bot can't post action card in Microsoft Teams channel using Bot framework

I have to send actionable card from bot when I call my API then that API will push action card throught Bot in microsoft teams channel where I will pass channel ID and service URL
Currently I am successfully able to send Simple message into Microsoft teams channel using custom API i.e. working for send simple messages.
But while sending action card it gives exception such as,
{"Activity resulted into multiple skype activities"}
public async Task<HttpResponseMessage> PostClause(ClauseRequest clauseRequest)
{
try
{
var channelId = "19:cf4306bb3aff49969b87420.......1#thread.skype";
var serviceURL = "https://smba.trafficmanager.net/apac-client-ss.msg/";
var connector = new ConnectorClient(new Uri(serviceURL));
var channelData = new Dictionary<string, string>();
channelData["teamsChannelId"] = channelId;
IMessageActivity newMessage = Activity.CreateMessageActivity();
newMessage.Type = ActivityTypes.Message;
newMessage.Text = "Hello channel.";
newMessage.Locale = "en-Us";
var attachment = GetHeroCard();
newMessage.Attachments = new List<Attachment>();
newMessage.Attachments.Add(attachment);
newMessage.SuggestedActions = new SuggestedActions()
{
Actions = new List<CardAction>()
{
new CardAction(){ Title = "Approve", Type=ActionTypes.ImBack, Value="Approve" },
new CardAction(){ Title = "Decline", Type=ActionTypes.ImBack, Value="Decline" }
// new CardAction(){ Title = "View in Google", Type=ActionTypes.OpenUrl, Value="https://www.google.co.in" }
}
};
ConversationParameters conversationParams = new ConversationParameters(
isGroup: true,
bot: null,
members: null,
topicName: "Test Conversation",
activity: (Activity)newMessage,
channelData: channelData);
MicrosoftAppCredentials.TrustServiceUrl(serviceURL, DateTime.MaxValue);
await connector.Conversations.CreateConversationAsync(conversationParams);
}
catch (Exception ex)
{
throw ex;
}
}
private static Attachment GetHeroCard()
{
List<CardAction> cardButtons = new List<CardAction>();
CardAction plButton = new CardAction()
{
Value = $"https://www.google.co.in",
Type = "openUrl",
Title = "View in Google"
};
cardButtons.Add(plButton);
var heroCard = new HeroCard
{
Title = "BotFramework Hero Card",
Subtitle = "Your bots — wherever your users are talking",
Text = "Build and connect intelligent bots to interact with your users naturally wherever they are, from text/sms to Skype, Slack, Office 365 mail and other popular services.",
Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
Buttons = cardButtons
};
return heroCard.ToAttachment();
}
As mentioned here in documentation :
Teams does not support SuggestedActions
So I update my code Its works now :)
public async Task<HttpResponseMessage> PostClause(ClauseRequest clauseRequest)
{
try
{
var channelId = "19:cf4306bb3aff4996.......#thread.skype";
var serviceURL = "https://smba.trafficmanager.net/apac-client-ss.msg/";
var connector = new ConnectorClient(new Uri(serviceURL));
var channelData = new Dictionary<string, string>();
channelData["teamsChannelId"] = channelId;
IMessageActivity newMessage = Activity.CreateMessageActivity();
newMessage.Type = ActivityTypes.Message;
var good = new CardAction("invoke", "Good", null, "{\"invokeValue\": \"Good\"}");
var bad = new CardAction("invoke", "Bad", null, "{\"invokeValue\": \"Bad\"}");
var card = new HeroCard("How are you today?", null, null, null, new List<CardAction> { good, bad }).ToAttachment();
newMessage.Attachments.Add(card);
ConversationParameters conversationParams = new ConversationParameters(
isGroup: true,
bot: null,
members: null,
topicName: "Test Conversation",
activity: (Activity)newMessage,
channelData: channelData);
MicrosoftAppCredentials.TrustServiceUrl(serviceURL, DateTime.MaxValue);
await connector.Conversations.CreateConversationAsync(conversationParams);
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
catch (Exception ex)
{
throw ex;
}
}
I think this would have worked as well:
new CardAction(){ Title = "Approve", Type="ImBack", Value="Approve" },
new CardAction(){ Title = "Decline", Type="ImBack", Value="Decline" }
according to this snippet in this example
CardAction plButton = new CardAction()
{
Value = $"https://en.wikipedia.org/wiki/{cardContent.Key}",
Type = "openUrl",
Title = "WikiPedia Page"
};

Microsoft Bot Framework : SigninCard not showing in telegram

I tried create Telegram bot client with Microsoft Bot Framework, when I create signincard with this framework, signincard created successfully and I can see buttons in Microsoft Bot Emulator but when I publish to server and test it with Telegram, signincard not showing in bot, please tell me how to fix it.
code :
Activity reply = null;
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl), "", "");
if (activity.Type == ActivityTypes.Message)
{
if (activity.Text == "/start")
{
reply = activity.CreateReply($"Welcome, please select an option");
reply.Recipient = activity.From;
reply.Type = ActivityTypes.Message;
reply.Attachments = new List<Attachment>();
List<CardAction> cardButtons = new List<CardAction>();
var helpAction = new CardAction()
{
Image = "",
Title = "Get Menu",
Type = "imBack",
Value = "help"
};
var contactAction = new CardAction()
{
Image = "",
Title = "Contact Us",
Type = "imBack",
Value = "contact"
};
cardButtons.Add(helpAction);
cardButtons.Add(contactAction);
var sc = new SigninCard()
{
Buttons = cardButtons,
Text = ""
};
Attachment attach = sc.ToAttachment();
reply.Attachments.Add(attach);
}
else
{
}
}
await connector.Conversations.ReplyToActivityAsync(reply);
sorry for bad english.
I think sign-in card type must be "signin", and the value should be url instead of string
working code:
replyActivity.Attachments = new List<Attachment>();
var cardButtons = new List<CardAction>();
var plButton = new CardAction
{
Value = auth.SessionUrl,
Type = "signin",
Title = "Connect"
};
cardButtons.Add(plButton);
var plCard = new SigninCard("You need to authorize to use Quick Book feature", cardButtons);
var plAttachment = plCard.ToAttachment();
replyActivity.Attachments.Add(plAttachment);
replyActivity.Text = "Should go to conversation, sign-in card";
screenshot:

Categories