// Create Conversation public ConversationResourceResponse CreateConversation(string channelId, ChannelAccount userAccount, ChannelAccount botAccount, string serviceUrl, CancellationToken cancellationToken = default(CancellationToken)) { return(CreateConversation(new Activity() { From = userAccount, Recipient = botAccount, ChannelId = channelId, ServiceUrl = serviceUrl })); }
private async Task AddUserTeamMembershipAsync(string teamId, ChannelAccount member) { var userMembership = new UserTeamMembership { TeamId = teamId, UserTeamsId = member.Id, }; await this.userManagementHelper.AddUserTeamMembershipAsync(userMembership); }
/// <summary> /// Gets the user AAD id /// </summary> /// <param name="this">this</param> /// <returns>the id</returns> public static string GetUserId(this ChannelAccount @this) { var teamsChannelAccount = @this.AsTeamsChannelAccount(); // ObjectId == null when the ChannelAccount is from the activity // and not from Conversations.GetConversationMembersAsync return(string.IsNullOrEmpty(teamsChannelAccount.ObjectId) ? teamsChannelAccount.Properties["aadObjectId"].ToString() : teamsChannelAccount.ObjectId); }
private IMessageActivity GetMessageActivity(ChannelAccount from) { var activity = DialogTestBase.MakeTestMessage(); activity.From = from ?? new ChannelAccount { Id = this.userId }; return(activity); }
private Activity GetPairMeetActivity(ChannelAccount directlyTextedPerson, ChannelAccount selectedPartner) { var activity = MessageFactory.Text("Hello "); activity.AddMentionToText(directlyTextedPerson, MentionTextLocation.AppendText, directlyTextedPerson.Name); activity.Text += "! Your buddy for this session is "; activity.AddMentionToText(selectedPartner, MentionTextLocation.AppendText, selectedPartner.Name); activity.Text += "! Have fun!"; return(activity); }
public static async Task SendWelcomeBackMessage(ChannelAccount member, ITurnContext turnContext, CancellationToken cancellationToken) { if (member.Id != turnContext.Activity.Recipient.Id) { await turnContext.SendActivitiesAsync(new[] { MessageFactory.Text($"Welcome back to the group, {member.Name}! I'm glad to see you again."), MessageFactory.Text(Constants.WelcomeMessages.WelcomeBackReminderMessage) }, cancellationToken); } }
public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity) { //cache the serviceUrl and bot account MessagesServiceUrl = activity.ServiceUrl; BotAccount = activity.Recipient; Log.Info(new CallerInfo(), LogContext.FrontEnd, $"Received chat message.. checking if there is an active media call for this thread"); await RealTimeMediaCall.SendUrlForConversationId(activity.Conversation.Id); return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted)); }
public ServicioBotDirectLine(string nombre) { var tokenResponse = new DirectLineClient(Constantes.DirectLineSecret).Tokens.GenerateTokenForNewConversation(); ClienteDL = new DirectLineClient(tokenResponse.Token); Conversacion = ClienteDL.Conversations.StartConversation(); Cuenta = new ChannelAccount { Id = nombre, Name = nombre }; }
public void AsTeamsChannelAccount_ParsesAADIdCorrectlyFromMessage() { Activity sampleActivity = JsonConvert.DeserializeObject <Activity>(File.ReadAllText(@"Jsons\SampleActivityMessageWithAADObjectId.json")); ChannelAccount user = sampleActivity.From; TeamsChannelAccount teamsUser = user.AsTeamsChannelAccount(); Assert.IsNotNull(teamsUser); Assert.IsNotNull(teamsUser.ObjectId); }
static void Main(string[] args) { var appId = "<Microsoft App ID>"; var appPassword = "******"; //Emulator var fromId = "default - user"; var recipientId = "95i2nkda1dd4"; var serviceUrl = "http://*****:*****@dTuM__gWAS0"; //var serviceUrl = "https://webchat.botframework.com/"; //var conversationId = "fd8a04848c4744ddbbcce046f6086967"; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); var connector = new ConnectorClient(new Uri(serviceUrl), appId, appPassword); var botAccount = new ChannelAccount(id: recipientId); var userAccount = new ChannelAccount(id: fromId); IMessageActivity message = Activity.CreateMessageActivity(); message.Conversation = new ConversationAccount(id: conversationId); message.From = botAccount; message.Recipient = userAccount; message.Locale = "ja-jp"; message.Text = $@"Chatbotからのお知らせです。 本日のおすすめは、季節のフルーツとれたてのあまーいいちごです。"; var cardImage = new CardImage { Url = "https://chatbot201707.azurewebsites.net/img/strawberry.jpg" }; var heroCard = new HeroCard { Title = "季節のフルーツ", Images = new List <CardImage> { cardImage } }; message.Attachments.Add(heroCard.ToAttachment()); connector.Conversations.SendToConversation((Activity)message); }
public static async Task SendWelcomeMessage(ChannelAccount member, ITurnContext turnContext, CancellationToken cancellationToken) { if (member.Id != turnContext.Activity.Recipient.Id) { await turnContext.SendActivitiesAsync(new[] { MessageFactory.Text($"Welcome, {member.Name}! We're always excited to have a new trainer join our community! Our group guidelines and FAQs can be found here: {VariableResources.WelcomePacketUrl}"), MessageFactory.Text(Constants.WelcomeMessages.FirstTimeNameFormatMessage), MessageFactory.Text(string.Format(Constants.WelcomeMessages.ParameterizedFirstTimeBotTutorialMessage, VariableResources.GymNameExamples.First())) }, cancellationToken); } }
private void Start() { account = new ChannelAccount(); client = new DirectLineClient(secretOrToken: secret); client.BaseUri = new Uri(Domain); if (AutoStart) { Task.Run(() => StartConversation()).ConfigureAwait(false); } }
public static Command CreateAcceptOrRejectConnectionRequestCommand( ConnectionRequest connectionRequest, bool doAccept, string botName = null) { ChannelAccount requestorChannelAccount = RoutingDataManager.GetChannelAccount(connectionRequest.Requestor); return(new Command( doAccept ? Commands.AcceptRequest : Commands.RejectRequest, new string[] { requestorChannelAccount?.Id, connectionRequest.Requestor.Conversation?.Id }, botName)); }
/// <summary> /// returns conversation id to initiate the connection between user and bot. /// </summary> /// <param name="tenantId">Tenant Id</param> /// <param name="userTeamsId">teamsId of user.</param> /// <returns>conversationId.</returns> public string CreateOrGetConversationIdAsync(string tenantId, string userTeamsId) { ChannelAccount bot = new ChannelAccount { Id = Common.GetTeamsBotId() }; ChannelAccount user = new ChannelAccount { Id = userTeamsId }; return(this.connectorClient.Conversations.CreateOrGetDirectConversation(bot, user, tenantId).Id); }
public static bool IsExpectedUser(UserDetails user, ChannelAccount fromUser, bool useTeams) { if (useTeams && user.TeamsUserInfo != null) { return(string.Equals(user.TeamsUserInfo.Id, fromUser.Id, StringComparison.InvariantCultureIgnoreCase)); } else { return(true); } }
// Send archive messages file to user. public static async Task SendGroupChatMessage(ITurnContext turnContext, long fileSize, string microsoftAppId, string microsoftAppPassword, CancellationToken cancellationToken) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } try { string filename = "chat.txt"; var member = new ChannelAccount { AadObjectId = turnContext.Activity.From.AadObjectId, Name = turnContext.Activity.From.Name, Id = turnContext.Activity.From.Id }; ConversationReference conversationReference = null; var conversationParameters = new ConversationParameters { IsGroup = false, Bot = turnContext.Activity.Recipient, Members = new ChannelAccount[] { member }, TenantId = turnContext.Activity.Conversation.TenantId, }; var credentials = new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword); var serviceUrl = turnContext.Activity.ServiceUrl; // Creates a conversation on the specified groupchat and send file consent card on that conversation. await((BotFrameworkAdapter)turnContext.Adapter).CreateConversationAsync( turnContext.Activity.ChannelId, serviceUrl, credentials, conversationParameters, async(conversationTurnContext, conversationCancellationToken) => { conversationReference = conversationTurnContext.Activity.GetConversationReference(); await((BotFrameworkAdapter)turnContext.Adapter).ContinueConversationAsync( microsoftAppId, conversationReference, async(conversationContext, conversationCancellation) => { var replyActivity = SendFileCardAsync(turnContext, filename, fileSize); await conversationContext.SendActivityAsync(replyActivity, conversationCancellation); }, cancellationToken); }, cancellationToken); } catch (ServiceException ex) { throw ex; } }
public static void Add(string subjectName, ChannelAccount asker, List <ChannelAccount> recipients, int experts) { m_currentBroadcasts.Add(new Broadcast { SubjectName = subjectName, Asker = asker, Status = BroadcastStatus.WaitingForQuestion, Answers = new Queue <BroadcastAnswer>(), Recipients = recipients, Experts = experts }); }
internal static IList <Activity> CreateActivitySetWithOneActivityThatHasSetProperties(string id = null, string conversationId = null, DateTime?created = null, string fromProperty = null, string text = null, object channelData = null, IList <Attachment> attachments = null, string eTag = null) { var conversation = new ConversationAccount(id: conversationId); var from = new ChannelAccount(name: fromProperty); var matchingActivity = new Activity(id: id, conversation: conversation, timestamp: created ?? DateTime.UtcNow, fromProperty: from, text: text, channelData: channelData, attachments: attachments); var activities = CreateRandomActivities(); activities.Add(matchingActivity); return(activities); }
private async Task <Activity> HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id)) { if (message.ChannelId == "directline") { return(null); } var RootDialog_Welcome_Message = "您好,我是 **Zimbra** 小秘書。\n\n 您可以透過我來操作您的 Mail or Schedules "; var reply = message.CreateReply(RootDialog_Welcome_Message); var connector = new ConnectorClient(new Uri(message.ServiceUrl)); //await connector.Conversations.ReplyToActivityAsync(reply); //Send a (non-reply) message //await connector.Conversations.SendToConversationAsync(reply); var userAccount = new ChannelAccount(message.From.Id); var botAccount = new ChannelAccount(message.Recipient.Id); var replyConversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount); var replyMsg = Activity.CreateMessageActivity(); replyMsg.From = botAccount; replyMsg.Recipient = userAccount; replyMsg.Conversation = new ConversationAccount(id: replyConversation.Id); replyMsg.Text = RootDialog_Welcome_Message; await connector.Conversations.SendToConversationAsync((Activity)replyMsg); } } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing tha the user is typing } else if (message.Type == ActivityTypes.Ping) { var reply = message.CreateReply(); reply.Type = ActivityTypes.Ping; return(reply); } return(null); }
private static Activity GetInitActivity(ChannelAccount channelAccount, string locale, object channelData) { var activity = new Activity { From = channelAccount, Type = ActivityTypes.Event, Locale = locale, ChannelData = channelData }; return(activity); }
// TODO: Pending review // Forward message to Slack private async Task <bool> SendSlackMessageAsync(User recipient, object messageContent) { if (recipient == null || messageContent == null) { return(false); } var isSuccess = false; try { var toId = recipient.Id; var toName = recipient.Name; var fromId = recipient.BotId; var fromName = recipient.BotName; var serviceUrl = recipient.ServiceUrl; var userAccount = new ChannelAccount(toId, toName); var botAccount = new ChannelAccount(fromId, fromName); var message = Activity.CreateMessageActivity(); message.From = botAccount; message.Recipient = userAccount; message.ChannelData = messageContent; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); var account = new MicrosoftAppCredentials(_appId, _password); var client = new ConnectorClient(new Uri(serviceUrl), account); // Reuse existing conversation if recipient is a channel string conversationId; if (recipient.IsGroupChannel) { conversationId = recipient.SlackConversationId; } else { var conversation = client.Conversations.CreateDirectConversation(botAccount, userAccount); conversationId = conversation.Id; } message.Conversation = new ConversationAccount(id: conversationId); var response = await client.Conversations.SendToConversationAsync((Activity)message); _logger.LogInformation($"Response id: {response.Id}"); isSuccess = true; } catch (Exception ex) { _logger.LogError(ex.Message); } return(isSuccess); }
public static ChatUser GetOrCreateUser(Mention userMention, ChannelAccount from) { if (!Users.TryGetValue(userMention.Text, out var user)) { var additionalMessages = CreateUserMessages(userMention, from.Id); var newUser = new ChatUser(userMention, from.Id, additionalMessages); Users.Add(userMention.Text, newUser); return(newUser); } return(user); }
/// <summary> /// Notifies the user. /// </summary> /// <param name="connectorClient">The connector client.</param> /// <param name="user">The user that joined the team.</param> /// <param name="attachmentToAppend">The attachment to send.</param> /// <param name="botId">The bot Id.</param> /// <param name="tenantId">The tenantId.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A unit of execution that contains a boolean value.</returns> private async Task <bool> NotifyUser( ConnectorClient connectorClient, ChannelAccount user, Attachment attachmentToAppend, string botId, string tenantId, CancellationToken cancellationToken) { if (connectorClient is null) { throw new ArgumentNullException(nameof(connectorClient)); } try { // ensure conversation exists var bot = new ChannelAccount { Id = botId }; var conversationParameters = new ConversationParameters() { Bot = bot, Members = new List <ChannelAccount>() { user, }, TenantId = tenantId, }; var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters, cancellationToken).ConfigureAwait(false); var conversationId = response.Id; var activity = new Activity() { Type = ActivityTypes.Message, Attachments = new List <Attachment>() { attachmentToAppend, }, }; await connectorClient.Conversations.SendToConversationAsync(conversationId, activity).ConfigureAwait(false); return(true); } catch (Exception ex) { this.telemetryClient.TrackException(ex); throw; } }
private static Activity BuildMessageActivity(ChannelAccount channelAccount, string utterance, string locale, object channelData) { var activity = new Activity { From = channelAccount, Type = ActivityTypes.Message, Text = utterance, Locale = locale, ChannelData = channelData }; return(activity); }
public BotHubRoute(Activity activity) { _channelId = activity.ChannelId; _conversationId = activity.Conversation.Id; _service = activity.ServiceUrl; _serviceUri = new Uri(activity.ServiceUrl); _locale = activity.Locale; _botAccount = activity.Recipient; _botPostBack = new BotPostBack(this); _queue = new BotQueue(); }
static async Task TriggerAsync() { string fromId; string fromName; string toId; string toName; string serviceUrl; string channelId; string conversationId; string date; string status; butterChicken.Models.Database3Entities DB = new butterChicken.Models.Database3Entities(); var members = (from UserLog in DB.UserLogs where UserLog.conID != string.Empty select UserLog) .ToList(); foreach (var member in members) { fromId = member.FrmID; fromName = member.FrmName; toId = member.toId; toName = member.toName; serviceUrl = member.svcURL; channelId = member.Channel; conversationId = member.conID; date = member.Date; status = member.Status; var userAccount = new ChannelAccount(toId, toName); var botAccount = new ChannelAccount(fromId, fromName); var connector = new ConnectorClient(new Uri(serviceUrl)); IMessageActivity message = Activity.CreateMessageActivity(); if (!string.IsNullOrEmpty(conversationId) && !string.IsNullOrEmpty(channelId)) { message.ChannelId = channelId; } else { conversationId = (await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount)).Id; } message.From = botAccount; message.Recipient = userAccount; message.Conversation = new ConversationAccount(id: conversationId); message.Text = "Delivery Date: " + date + ". Status:" + status; message.Locale = "en-Us"; await connector.Conversations.SendToConversationAsync((Activity)message); } }
/// <summary> /// Creates a large connection request card. /// </summary> /// <param name="connectionRequest">The connection request.</param> /// <param name="botName">The name of the bot (optional).</param> /// <returns>A newly created request card.</returns> public static HeroCard CreateConnectionRequestCard( ConnectionRequest connectionRequest, string botName = null) { if (connectionRequest == null || connectionRequest.Requestor == null) { throw new ArgumentNullException("The connection request or the conversation reference of the requestor is null"); } ChannelAccount requestorChannelAccount = RoutingDataManager.GetChannelAccount(connectionRequest.Requestor); if (requestorChannelAccount == null) { throw new ArgumentNullException("The channel account of the requestor is null"); } string requestorChannelAccountName = string.IsNullOrEmpty(requestorChannelAccount.Name) ? StringConstants.NoUserNamePlaceholder : requestorChannelAccount.Name; string requestorChannelId = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(connectionRequest.Requestor.ChannelId); Command acceptCommand = Command.CreateAcceptOrRejectConnectionRequestCommand(connectionRequest, true, botName); Command rejectCommand = Command.CreateAcceptOrRejectConnectionRequestCommand(connectionRequest, false, botName); HeroCard card = new HeroCard() { Title = Strings.ConnectionRequestTitle, Subtitle = string.Format(Strings.RequestorDetailsTitle, requestorChannelAccountName, requestorChannelId), Text = string.Format(Strings.AcceptRejectConnectionHint, acceptCommand.ToString(), rejectCommand.ToString()), Buttons = new List <CardAction>() { new CardAction() { Title = Strings.AcceptButtonTitle, Type = ActionTypes.ImBack, Value = acceptCommand.ToString() }, new CardAction() { Title = Strings.RejectButtonTitle, Type = ActionTypes.ImBack, Value = rejectCommand.ToString() } } }; return(card); }
private static async Task NotifyUser(string serviceUrl, string cardToSend, ChannelAccount user, string tenantId) { var me = new ChannelAccount() { Id = CloudConfigurationManager.GetSetting("MicrosoftAppId"), Name = "MeetupBot" }; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); // Create 1:1 with user using (var connectorClient = new ConnectorClient(new Uri(serviceUrl))) { // ensure conversation exists var response = connectorClient.Conversations.CreateOrGetDirectConversation(me, user, tenantId); // construct the activity we want to post var activity = new Activity() { Type = ActivityTypes.Message, Conversation = new ConversationAccount() { Id = response.Id, }, Attachments = new List <Attachment>() { new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardToSend), } } }; var isTesting = Boolean.Parse(CloudConfigurationManager.GetSetting("Testing")); if (!isTesting) { // shoot the activity over // added try catch because if user has set "Block conversations with bots" try { await connectorClient.Conversations.SendToConversationAsync(activity, response.Id); } catch (UnauthorizedAccessException uae) { System.Diagnostics.Trace.TraceError($"Failed to notify user due to error {uae.ToString()}"); } } } }
public ActionResult manualTeleSend(string userName) { DateTime now = DateTime.UtcNow + TimeSpan.FromHours(3); List <Bet> allbets = db.Bets.Where(b => b.ApplicationUser.TelegramUserName == userName & b.Program.TvDate == now.Date).ToList(); string allbetsstr = allbets.Count().ToString() + "; "; List <ConversationStarter> css = db.CSs.ToList(); if (css.Count() > 0) { foreach (ConversationStarter cs in css) { if (cs.ChannelId == "telegram" & cs.ApplicationUser.TelegramUserName == userName) { ApplicationUser curUser = cs.ApplicationUser; var userAccount = new ChannelAccount(cs.ToId, cs.ToName); var botAccount = new ChannelAccount(cs.FromId, cs.FromName); var connector = new ConnectorClient(new Uri(cs.ServiceUrl)); Activity activity = new Activity(); activity.From = botAccount; activity.Recipient = userAccount; activity.Conversation = new ConversationAccount(id: cs.ConversationId); activity.Id = "1"; string text = "Нужно сделать ставки!"; activity.ChannelData = new TelegramChannelData() { method = "sendMessage", parameters = new TelegramParameters() { text = text } }; allbetsstr += activity.Recipient.Name.ToString() + "-" + activity.Recipient.Id.ToString() + ". "; try { //connector.Conversations.ReplyToActivity(activity); connector.Conversations.SendToConversation(activity); } catch (Exception ex) { allbetsstr = ex.Message; } } } } return(Content(allbetsstr)); }
private Message BroadcastAccept(Message message) { Broadcast broadcast = Broadcast.GetAll().FirstOrDefault(b => b.Asker.Id == message.From.Id && b.Status == BroadcastStatus.WaitingForApproval && b.Answers.Count > 0 ); if (broadcast == null) { return(message.CreateReplyMessage(Reply.GetReply(ReplyType.None).Text, "en")); } Subject subject = Subject.GetAll().FirstOrDefault(s => s.Name == broadcast.SubjectName); if (subject == null) { subject = new Subject { Id = Guid.NewGuid().ToString(), Name = broadcast.SubjectName }; Subject.Add(subject); Subject.Save(); } Person person = Person.GetAll().FirstOrDefault(p => p.Id == broadcast.Answers.First().Answerer.Id); if (person == null) { return(message.CreateReplyMessage("Something went horibly wrong, put the laptop down and run away!", "en")); } Matrix.SetPoints(person, subject, Matrix.GetPoints(person, subject) + 1); Matrix.Save(); Broadcast.Remove(broadcast); ChannelAccount answererAccount = accountsForId.ContainsKey(person.Id) ? accountsForId[person.Id] : null; if (answererAccount != null) { var connector = new ConnectorClient(); var ackMessage = new Message(); ackMessage.From = message.To; ackMessage.To = answererAccount; ackMessage.Text = string.Format(Reply.GetReply(ReplyType.AnswererFeedbackPositive).Text, "@" + broadcast.Asker.Name); ackMessage.Language = "en"; connector.Messages.SendMessage(ackMessage); } return(message.CreateReplyMessage(Reply.GetReply(ReplyType.AcceptedAnswer).Text, "en")); }