/// <summary> /// Simplified message to a user /// </summary> /// <param name="Message">String :"Message"</param> /// <param name="client">client</param> /// <param name="userchannelid">userchannelid</param> void MessageTo(string Message, SlackSocketClient client, DirectMessageConversation userchannelid, MessageType type) { Connected = null; client.Connect(Connected => { if (type != MessageType.Crash) { client.SendMessage(null, userchannelid.id, Message); } else { client.SendMessage(null, userchannelid.id, "Crash :" + Message); } }); }
/// <inheritdoc /> /// <summary> /// Sends a text message /// </summary> /// <param name="chat">Chat where the message will be sent</param> /// <param name="message">Message to send</param> /// <param name="parseMode">Message parse mode</param> /// <returns>Async task</returns> public Task SendTextMessageAsync(BotChat chat, string message, MessageParseMode parseMode = MessageParseMode.Default) { var taskSource = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); _client.SendMessage(received => taskSource.TrySetResult(true), chat.Id, message); return(taskSource.Task); }
/// <summary> /// Used to connect task mail bot and to capture task mail /// </summary> public void TaskMailBot() { _logger.Info("TaskMailAccessToken : " + _environmentVariableRepository.TaskmailAccessToken); SlackSocketClient client = new SlackSocketClient(_environmentVariableRepository.TaskmailAccessToken); // assigning bot token on Slack Socket Client // Creating a Action<MessageReceived> for Slack Socket Client to get connect. No use in task mail bot MessageReceived messageReceive = new MessageReceived(); messageReceive.ok = true; Action <MessageReceived> showMethod = (MessageReceived messageReceived) => new MessageReceived(); // Telling Slack Socket Client to the bot whose access token was given early client.Connect((connected) => { }); try { _logger.Info("Task mail bot connected"); // Method will hit when someone send some text in task mail bot client.OnMessageReceived += (message) => { _logger.Info("Task mail bot receive message : " + message.text); var user = _slackUserDetailsRepository.GetByIdAsync(message.user).Result; _logger.Info("User : "******"Task Mail process start - StartTaskMailAsync"); replyText = _taskMailRepository.StartTaskMailAsync(user.UserId).Result; _logger.Info("Task Mail process done : " + replyText); } else { _logger.Info("Task Mail process start - QuestionAndAnswerAsync"); replyText = _taskMailRepository.QuestionAndAnswerAsync(text, user.UserId).Result; _logger.Info("Task Mail process done : " + replyText); } } else { replyText = _stringConstant.NoSlackDetails; _logger.Info("User is null : " + replyText); } // Method to send back response to task mail bot client.SendMessage(showMethod, message.channel, replyText); _logger.Info("Reply message sended"); }; } catch (Exception ex) { _logger.Error(_stringConstant.LoggerErrorMessageTaskMailBot + _stringConstant.Space + ex.Message + Environment.NewLine + ex.StackTrace); throw ex; } }
public void SendMessage(string text, IChannel target) { if (target is SlackChannel) { client.SendMessage((onSent) => { }, target.ID, text); } else { return; } }
/// <summary> /// Processes the message sent to the bot and runs the command if it's valid. /// </summary> /// <param name="msg"></param> private void ParseBotMessage(NewMessage msg) { string text = msg.text.ToLower().Trim(); var words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string command = ""; if (words.Any()) { command = words[0]; string userId = "<@" + _loginResponse.self.id.ToLower() + ">"; command = command.Replace(userId + ":", ""); command = command.Replace(userId, ""); if (command.Length == 0) { words = words.Skip(1).ToArray(); } if (words.Any()) { command = words[0]; } } command = command.Trim(); string[] args = null; if (words.Count() > 1) { args = words.Skip(1).ToArray(); } string targetUser = "******" + msg.user + ">"; string answer = targetUser + ": "; if (_restaurantManager.ContainsRestaurant(command)) { answer += _restaurantManager.GetMenu(command); } else if (IsCommandKnown(command)) { answer += RunCommand(command, args); } else { StatisticsCollector.GetInstance().IncrementUnknownCommandCount(); answer = GetRandomUnknownCommandAnswer(targetUser); } if (answer.Length > 0) { _slackClient.SendMessage(received => { }, msg.channel, answer); } }
public override MessageSendResult SendMessage(ChatChannel target, string message) { var ev = new ManualResetEvent(false); var success = false; socketClient.SendMessage(received => { ev.Set(); success = received.ok; }, target.Identifier, message); ev.WaitOne(TimeSpan.FromSeconds(10)); return(success ? MessageSendResult.Success : MessageSendResult.Failure); }
/// <summary> /// Sends out a message to the servercrashbot channel. /// </summary> /// <param name="Message"> The message that is going to be sent</param> /// <param name="client"> The SlackSocketClient that is used to connect</param> /// <param name="Channelname">Name of the channel you want to send it to</param> void SendToLogChat(string Message, SlackSocketClient client, MessageType type) { Connected = null; client.Connect(Connected => { var c = client.Channels.Find(x => x.name.Equals(DefaultChannel)); switch (type) { case MessageType.Crash: client.SendMessage(null, c.id, "Crash : " + Message); for (int i = 0; i < userbase.Length; i++) { var user = client.Users.Find(x => x.name.Equals(userbase[i])); // everyone is the userbase if (user != null) { var dmchannel = client.DirectMessages.Find(x => x.user.Equals(user.id)); if (user != null && dmchannel != null) { MessageTo(Message, client, dmchannel, type); } } } break; case MessageType.Error: client.SendMessage(null, c.id, "Error : " + Message); break; case MessageType.Info: client.SendMessage(null, c.id, "Info : " + Message); break; case MessageType.Warning: client.SendMessage(null, c.id, "Warning : " + Message); break; } }); }
/// <summary> /// Used to connect task mail bot and to capture task mail /// </summary> /// <param name="container"></param> public static void Main(IComponentContext container) { _logger = container.Resolve <ILogger>(); _stringConstant = container.Resolve <IStringConstantRepository>(); try { _taskMailRepository = container.Resolve <ITaskMailRepository>(); _slackUserDetails = container.Resolve <ISlackUserRepository>(); _environmentVariableRepository = container.Resolve <IEnvironmentVariableRepository>(); // assigning bot token on Slack Socket Client string botToken = _environmentVariableRepository.TaskmailAccessToken; SlackSocketClient client = new SlackSocketClient(botToken); // Creating a Action<MessageReceived> for Slack Socket Client to get connect. No use in task mail bot MessageReceived messageReceive = new MessageReceived(); messageReceive.ok = true; Action <MessageReceived> showMethod = (MessageReceived messageReceived) => new MessageReceived(); // Telling Slack Socket Client to the bot whose access token was given early client.Connect((connected) => { }); try { // Method will hit when someone send some text in task mail bot client.OnMessageReceived += (message) => { var user = _slackUserDetails.GetById(message.user); string replyText = ""; var text = message.text; if (text.ToLower() == _stringConstant.TaskMailSubject.ToLower()) { replyText = _taskMailRepository.StartTaskMail(user.Name).Result; } else { replyText = _taskMailRepository.QuestionAndAnswer(user.Name, text).Result; } // Method to send back response to task mail bot client.SendMessage(showMethod, message.channel, replyText); }; } catch (Exception) { client.CloseSocket(); } } catch (Exception ex) { _logger.Error(_stringConstant.LoggerErrorMessageTaskMailBot + " " + ex.Message + "\n" + ex.StackTrace); throw ex; } }
public void SendMessage(string destinationRoom, ChatMessage message) { try { string messageText = $"*{message.User}[{message.ServerId}]*: {message.Text}"; string formattedMessage = FormatOutgoingMessage(messageText); string channelId = channelNameLookup[destinationRoom].id; client.SendMessage(null, channelId, formattedMessage); } catch (Exception ex) { Console.WriteLine($"{serverConfig.ServerId}|EXCEPTION: {ex}"); } }
/// <summary> /// Used for Scrum meeting bot connection and to conduct scrum meeting /// </summary> /// <param name="container"></param> public static void ScrumMain(IComponentContext container) { _logger = container.Resolve <ILogger>(); _stringConstant = container.Resolve <IStringConstantRepository>(); try { _environmentVariableRepository = container.Resolve <IEnvironmentVariableRepository>(); string botToken = _environmentVariableRepository.ScrumBotToken; SlackSocketClient client = new SlackSocketClient(botToken);//scrumBot _scrumBotRepository = container.Resolve <IScrumBotRepository>(); // Creating a Action<MessageReceived> for Slack Socket Client to get connected. MessageReceived messageReceive = new MessageReceived(); messageReceive.ok = true; Action <MessageReceived> showMethod = (MessageReceived messageReceived) => new MessageReceived(); //Connecting the bot of the given token client.Connect((connected) => { }); // Method will be called when someone sends message client.OnMessageReceived += (message) => { _logger.Info("Scrum bot got message :" + message); try { _logger.Info("Scrum bot got message, inside try"); string replyText = _scrumBotRepository.ProcessMessages(message.user, message.channel, message.text).Result; if (!String.IsNullOrEmpty(replyText)) { _logger.Info("Scrum bot got reply"); client.SendMessage(showMethod, message.channel, replyText); } } catch (Exception ex) { _logger.Error("\n" + _stringConstant.LoggerScrumBot + " " + ex.Message + "\n" + ex.StackTrace); client.CloseSocket(); throw ex; } }; //ChannelCreated channel = new ChannelCreated(); //client.HandleChannelCreated(channel); } catch (Exception ex) { _logger.Error("\n" + _stringConstant.LoggerScrumBot + " " + ex.Message + "\n" + ex.StackTrace); throw ex; } }
private static DateTime PostMessage(SlackSocketClient client, string channel) { MessageReceived sendMessageResponse = null; using (var sync = new InSync(nameof(SlackSocketClient.SendMessage))) { client.SendMessage(response => { sendMessageResponse = response; sync.Proceed(); }, channel, TestText); } Assert.NotNull(sendMessageResponse); Assert.Equal(TestText, sendMessageResponse.text); return(sendMessageResponse.ts); }
private static DateTime PostMessage(SlackSocketClient client, string channel) { var waiter = new EventWaitHandle(false, EventResetMode.ManualReset); MessageReceived sendMessageResponse = null; client.SendMessage(response => { sendMessageResponse = response; waiter.Set(); }, channel, TestText); Policy .Handle <AssertFailedException>() .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds)) .Execute(() => { Assert.IsTrue(waiter.WaitOne(), "Still waiting for things to happen..."); }); Assert.IsNotNull(sendMessageResponse, "sendMessageResponse != null"); Assert.AreEqual(TestText, sendMessageResponse.text, "Got invalid returned text, something's not right here..."); return(sendMessageResponse.ts); }
public void TestConnectPostAndDelete() { EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset); SlackSocketClient client = new SlackSocketClient(token); client.Connect((o) => { Debug.WriteLine("RTM Start"); }, () => { Debug.WriteLine("Connected"); wait.Set(); }); Assert.IsTrue(wait.WaitOne(10000), "Didn't return within a reasonable time."); Thread.Sleep(500); Assert.IsTrue(client.IsConnected, "Invalid, doesn't think it's connected."); wait = new EventWaitHandle(false, EventResetMode.ManualReset); DateTime ts = DateTime.MinValue; SlackAPI.WebSocketMessages.MessageReceived a = null; client.SendMessage((resp) => { a = resp; wait.Set(); }, testChannel, testText); Assert.IsTrue(wait.WaitOne(1000), "Took too long for Slack to acknowledge message."); ts = a.ts; Assert.AreEqual(a.text, testText, "Got invalid returned text, something's not right here..."); DeletedResponse r = null; wait = new EventWaitHandle(false, EventResetMode.ManualReset); client.DeleteMessage((resp) => { r = resp; wait.Set(); }, testChannel, ts); Assert.IsTrue(wait.WaitOne(1000), "Took too long for Slack to acknowledge delete."); Assert.IsTrue(r.ok, "Message not deleted!"); Assert.AreEqual(r.channel, testChannel, "Got invalid channel? Something's not right here..."); Assert.AreEqual(r.ts, ts, "Got invalid time stamp? Something's not right here..."); }
public void SendMessage(string message, string channelId) { SlackClient.SendMessage((mr) => { }, channelId, message); }
private static DateTime PostMessage(SlackSocketClient client, string channel) { var waiter = new EventWaitHandle(false, EventResetMode.ManualReset); MessageReceived sendMessageResponse = null; client.SendMessage(response => { sendMessageResponse = response; waiter.Set(); }, channel, TestText); Policy .Handle<AssertFailedException>() .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds)) .Execute(() => { Assert.IsTrue(waiter.WaitOne(), "Still waiting for things to happen..."); }); Assert.IsNotNull(sendMessageResponse, "sendMessageResponse != null"); Assert.AreEqual(TestText, sendMessageResponse.text, "Got invalid returned text, something's not right here..."); return sendMessageResponse.ts; }
/// <summary> /// Used for Scrum meeting bot connection and to conduct scrum meeting. - JJ /// </summary> public void Scrum() { SlackSocketClient client = new SlackSocketClient(_environmentVariableRepository.ScrumBotToken);//scrumBot // Creating a Action<MessageReceived> for Slack Socket Client to get connected. MessageReceived messageReceive = new MessageReceived(); messageReceive.ok = true; Action <MessageReceived> showMethod = (MessageReceived messageReceived) => new MessageReceived(); //Connecting the bot of the given token client.Connect((connected) => { _scrumBotId = connected.self.id; }); // Method will be called when someone sends message client.OnMessageReceived += (message) => { _scrumlogger.Debug("Scrum bot got message :" + message); try { IScrumBotRepository scrumBotRepository = _component.Resolve <IScrumBotRepository>(); _scrumlogger.Debug("Scrum bot got message : " + message.text + " From user : "******" Of channel : " + message.channel); string replyText = scrumBotRepository.ProcessMessagesAsync(message.user, message.channel, message.text, _scrumBotId).Result; _scrumlogger.Debug("Scrum bot got reply : " + replyText + " To user : "******" Of channel : " + message.channel); if (!String.IsNullOrEmpty(replyText)) { _scrumlogger.Debug("Scrum bot sending reply"); client.SendMessage(showMethod, message.channel, replyText); _scrumlogger.Debug("Scrum bot sent reply"); } } catch (TaskCanceledException ex) { client.SendMessage(showMethod, message.channel, _stringConstant.ErrorMsg); _scrumlogger.Trace(ex.StackTrace); _scrumlogger.Error("\n" + _stringConstant.LoggerScrumBot + " OAuth Server Not Responding " + ex.InnerException); client.CloseSocket(); throw ex; } catch (HttpRequestException ex) { client.SendMessage(showMethod, message.channel, _stringConstant.ErrorMsg); _scrumlogger.Trace(ex.StackTrace); _scrumlogger.Error("\n" + _stringConstant.LoggerScrumBot + " OAuth Server Closed \nInner exception :\n" + ex.InnerException); client.CloseSocket(); throw ex; } catch (Exception ex) { client.SendMessage(showMethod, message.channel, _stringConstant.ErrorMsg); _scrumlogger.Trace(ex.StackTrace); _scrumlogger.Error("\n" + _stringConstant.LoggerScrumBot + " Generic exception \nMessage : \n" + ex.Message + "\nInner exception :\n" + ex.InnerException); client.CloseSocket(); throw ex; } }; }
public void SendMessage(Action <MessageReceived> callback, string text, string channelId = null) { Client.SendMessage(callback, channelId ?? activeChat.Id, text); //client.SendMessage(callback, channelId ?? activeChat.Id, text); }