void AuthSignIn() { EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset); SlackSocketClient client = new SlackSocketClient(token); client.OnHello += () => { wait.Set(); }; client.Connect((l) => { if (!l.ok) return; BeginInvoke(new Action(() => { connected = new ConnectedInterface(client, l); connected.Dock = DockStyle.Fill; Controls.Add(connected); password.Visible = false; })); }); wait.WaitOne(); }
public static SlackSocketClient GetClient(string authToken) { var wait = new EventWaitHandle(false, EventResetMode.ManualReset); var client = new SlackSocketClient(authToken); client.Connect(x => { Console.WriteLine("RTM Start"); }, () => { Console.WriteLine("Connected"); wait.Set(); }); Policy .Handle<AssertFailedException>() .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds)) .Execute(() => { Assert.IsTrue(wait.WaitOne(), "Still waiting for things to happen..."); }); Policy .Handle<AssertFailedException>() .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds)) .Execute(() => { Assert.IsTrue(client.IsConnected, "Doh, still isn't connected"); }); return client; }
public static SlackSocketClient GetClient(string authToken) { var wait = new EventWaitHandle(false, EventResetMode.ManualReset); var client = new SlackSocketClient(authToken); client.Connect((x, sc) => { Console.WriteLine("RTM Start"); }, () => { Console.WriteLine("Connected"); wait.Set(); }); Policy .Handle <AssertFailedException>() .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds)) .Execute(() => { Assert.IsTrue(wait.WaitOne(), "Still waiting for things to happen..."); }); Policy .Handle <AssertFailedException>() .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds)) .Execute(() => { Assert.IsTrue(client.IsConnected, "Doh, still isn't connected"); }); return(client); }
public async Task Connect() { SlackSocketClient.Connect((loginResponse => { if (loginResponse.ok) { Logger.LogInformation("Socket client responded ok"); } else { Logger.LogError($"SlackSocketClient Error: {loginResponse.error}"); } }), () => Logger.LogInformation("Socket connected")); SlackSocketClient.OnMessageReceived += message => { Logger.LogInformation(JsonConvert.SerializeObject(message)); }; SlackSocketClient.OnReactionAdded += reaction => { Logger.LogInformation(JsonConvert.SerializeObject(reaction)); }; await SlackTaskClient.ConnectAsync(); var response = await SlackTaskClient.PostMessageAsync("#sandbox", "Hi", "I'm a bot"); if (!response.ok) { Logger.LogError($"Post Message Error: {response.error}"); } Logger.LogInformation("Connected"); }
public SlackAdapter(ChatServer chatServerConfig) { serverConfig = chatServerConfig; client = new SlackSocketClient(serverConfig.Password); Messages = Observable.FromEvent<Action<SlackAPI.WebSocketMessages.NewMessage>, ChatMessage>(handler => { Action<SlackAPI.WebSocketMessages.NewMessage> converter = slackMessage => { try { if (client == null || string.IsNullOrWhiteSpace(slackMessage.user)) { return; } User user = client.UserLookup[slackMessage.user]; // Don't relay our own messages if (user.name.Equals(serverConfig.UserName, StringComparison.OrdinalIgnoreCase)) { return; } if (slackMessage.channel.StartsWith("D")) { Console.WriteLine("({0})DirectMessage {1}: {2}", serverConfig.ServerId, user.name, slackMessage.text); return; } Channel channel = slackMessage.channel.StartsWith("C") ? client.ChannelLookup[slackMessage.channel] : client.GroupLookup[slackMessage.channel]; var chatMessage = new ChatMessage { ServerId = serverConfig.ServerId, Room = channel.name, User = user.name, Text = FormatIncomingMessage(slackMessage.text), TimeStamp = slackMessage.ts }; handler(chatMessage); } catch (Exception ex) { Console.WriteLine($"{serverConfig.ServerId}|EXCEPTION: {ex}"); } }; return converter; }, converter => client.OnMessageReceived += converter, converter => client.OnMessageReceived -= converter ); connectionStatusTimer = new Timer(15000) { AutoReset = true }; connectionStatusTimer.Elapsed += ConnectionStatusTimer_Elapsed; }
public override bool Connect() { var clientReady = new SemaphoreSlim(0); var socketReady = new SemaphoreSlim(0); socketClient = new SlackSocketClient(Configuration.Password); socketClient.Connect(connected => { clientReady.Release(); }, () => { socketReady.Release(); }); socketClient.OnMessageReceived += MessageReceivedCallback; if (!Task.WaitAll(new[] { clientReady.WaitAsync(), socketReady.WaitAsync() }, TimeSpan.FromSeconds(10))) { return(false); } Channels = socketClient.Channels.Select(ToChatChannel) .Concat(socketClient.Groups.Select(ToChatChannel)) .Concat(socketClient.DirectMessages.Select(ToChatChannel)) .ToList(); activityTimer = new Timer(state => socketClient.SendPresence(Presence.active), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); return(true); }
private SlackSocketClient CreateClient(string authToken, IWebProxy proxySettings = null) { SlackSocketClient client; LoginResponse loginResponse = null; using (var syncClient = new InSync($"{nameof(SlackClient.Connect)} - Connected callback")) using (var syncClientSocket = new InSync($"{nameof(SlackClient.Connect)} - SocketConnected callback")) using (var syncClientSocketHello = new InSync($"{nameof(SlackClient.Connect)} - SocketConnected hello callback")) { client = new SlackSocketClient(authToken, proxySettings); client.OnHello += () => syncClientSocketHello.Proceed(); client.Connect(x => { loginResponse = x; Console.WriteLine($"Connected {x.ok}"); syncClient.Proceed(); if (!x.ok) { // If connect fails, socket connect callback is not called syncClientSocket.Proceed(); syncClientSocketHello.Proceed(); } }, () => { Console.WriteLine("Socket Connected"); syncClientSocket.Proceed(); }); } loginResponse.AssertOk(); return(client); }
private SlackBotCommand(NewMessage message, SlackSocketClient slackBot) { user = slackBot.UserLookup.ContainsKey(message.user) ? slackBot.UserLookup[message.user] : null; channel = null; if (slackBot.ChannelLookup.ContainsKey(message.channel)) { channel = slackBot.ChannelLookup[message.channel]; } else if (slackBot.GroupLookup.ContainsKey(message.channel)) { channel = slackBot.GroupLookup[message.channel]; } string text = message.text.Substring(message.text.IndexOf(CommandPrefix) + CommandPrefix.Length).NormalizeSpace(); int firstSpace = text.IndexOf(' '); if (firstSpace != -1) { command = text.Substring(0, firstSpace); commandText = text.Substring(firstSpace + 1); } else { command = text; commandText = string.Empty; } timestamp = message.ts; }
public SlackHelper(TriviaContext _dbcontext) { dbcontext = _dbcontext; pendingQuestionId = Guid.Empty; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("authentication.json", false, false) .AddJsonFile("conversations.json", false, true); Configuration = builder.Build(); string token = Configuration["auth"]; client = new SlackSocketClient(token); workingTriviaChannelId = Configuration["workingchannel"]; triviaChannelId = Configuration["triviaChannelId"]; //triviaChannelId = Configuration["workingchannel"]; adminId = Configuration["adminId"]; adminDM = Configuration["adminDM"]; string timeSpanString = Configuration["timespan"]; int.TryParse(timeSpanString, out int timeSpanHours); //timespan = new TimeSpan(0, timeSpanHours, 0, 0); timespan = new TimeSpan(0, 1, 0, 0); }
public SlackService(string authToken) { AuthToken = authToken; var waitEvent = new ManualResetEvent(false); Users = new Dictionary <string, SlackUser>(); Slack = new SlackSocketClient(AuthToken); Console.WriteLine("Trying to connect to the Slack server...."); Slack.Connect( (LoginResponse response) => { if (response.ok == false) { Console.WriteLine("Auth error : " + response.error); } Console.WriteLine("Connected"); Console.WriteLine(" logged in as " + Slack.MyData.name); waitEvent.Set(); }); Slack.OnMessageReceived += OnMessageReceived; Slack.EmitPresence(_ => { }, Presence.active); waitEvent.WaitOne(); waitEvent.Dispose(); }
void AuthSignIn() { EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset); SlackSocketClient client = new SlackSocketClient(token); client.OnHello += () => { wait.Set(); }; client.Connect((l) => { if (!l.ok) { return; } BeginInvoke(new Action(() => { connected = new ConnectedInterface(client, l); connected.Dock = DockStyle.Fill; Controls.Add(connected); password.Visible = false; })); }); wait.WaitOne(); }
public void TestManualSubscribePresenceChangeAndManualPresenceChange() { // Arrange slackClient = this.fixture.CreateUserClient(); using (var sync = new InSync()) { slackClient.OnPresenceChanged += x => { if (x.user == slackClient.MySelf.id) { // Assert sync.Proceed(); } }; slackClient.SubscribePresenceChange(slackClient.MySelf.id); } using (var sync = new InSync()) { slackClient.OnPresenceChanged += x => { if (x is ManualPresenceChange && x.user == slackClient.MySelf.id) { // Assert sync.Proceed(); } }; // Act slackClient.EmitPresence(x => x.AssertOk(), Presence.away); slackClient.EmitPresence(x => x.AssertOk(), Presence.auto); } }
static void InitializeSlack() { string botToken = Configuration["Slack:BotToken"]; ManualResetEventSlim clientReady = new ManualResetEventSlim(false); client = new SlackSocketClient(botToken); client.Connect((connected) => { clientReady.Set(); }, () => { }); client.OnMessageReceived += (message) => { Console.WriteLine(message.user + "(" + message.username + "): " + message.text); if (message.text.StartsWith("rpi:")) { string cmd = message.text.RightOf("rpi:").Trim().LeftOf(" "); List <string> options = new List <string>(); while (cmd.StartsWith("--")) { var opt = cmd.LeftOf(" "); options.Add(opt); cmd = message.text.RightOf(opt).Trim().LeftOf(" "); } string data = message.text.RightOf(cmd).Trim(); Console.WriteLine("cmd: " + cmd); Console.WriteLine("data: " + data); string ret = "Error occurred."; try { if (router.TryGetValue(cmd, out Func <string, List <string>, string> fnc)) { ret = fnc(data, options); } else { string cmdline = (cmd + " " + data).Trim(); ret = "```\r\n" + cmdline.Bash() + "```"; } } catch (Exception ex) { ret = ex.Message; } client.PostMessage((mr) => { }, message.channel, ret); } }; clientReady.Wait(); }
private bool SendMessages(ref bool atLeastOneSuccess) { var success = true; var files = SelectFiles(); if (files.Length > 0) { ManualResetEventSlim clientReady = new ManualResetEventSlim(false); SlackSocketClient client = new SlackSocketClient(Token); client.Connect((connected) => { // This is called once the client has emitted the RTM start command clientReady.Set(); }, () => { // This is called once the RTM client has connected to the end point }); client.OnMessageReceived += (message) => { // Handle each message as you receive them }; clientReady.Wait(); client.GetUserList((ulr) => { Info("Got users."); }); foreach (FileInf file in files) { try { var xdoc = XDocument.Load(file.Path); foreach (XElement xMessage in xdoc.XPathSelectElements("Messages/Message")) { var username = xMessage.Element("User").Value; var text = xMessage.Element("Text").Value; var user = client.Users.Find(x => x.name.Equals(username)); var dmchannel = client.DirectMessages.Find(x => x.user.Equals(user.id)); client.PostMessage((mr) => Info("Message '" + text + "' sent to " + dmchannel.id + "."), dmchannel.id, text); if (!atLeastOneSuccess) { atLeastOneSuccess = true; } } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while sending the messages of the file {0}.", e, file.Path); success = false; } } } return(success); }
private void Reconnect() { SlackClient.CloseSocket(); SlackClient = null; SlackClient = new SlackSocketClient(SlackseConfig.Token); SlackClient.OnMessageReceived += WrapperAction; PongCancellationTokenSource.Cancel(); this.Connect(); }
public SlackBotClient( IOptions <SlackBotOptions> options, ILogger <SlackBotClient> logger) { SlackBotOptions = options.Value; SlackTaskClient = new SlackTaskClient(SlackBotOptions.Token); SlackSocketClient = new SlackSocketClient(SlackBotOptions.Token); Logger = logger; }
/// <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; } }
/// <summary> /// Try close the slack streaming connection /// </summary> private void TryCloseConnection() { try { SlackSocketClient.CloseSocket(); } catch (Exception exception) { Console.WriteLine(exception); } }
public ConnectedInterface(SlackSocketClient connectedClient, LoginResponse loginDetails) { Client = connectedClient; chats = new Dictionary<string, ChatInterface>(); InitializeComponent(); channelList = new SlackChannelList(this); channelList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; channelList.AutoScroll = true; channelList.BackColor = Color.FromArgb(0x4D, 0x39, 0x4B); channelList.Location = new Point(0, 52); //53 channelList.Margin = new Padding(0); channelList.Name = "channelList"; channelList.Size = new Size(220, 671); channelList.TabIndex = 2; channelList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; Controls.Add(this.channelList); channelList.Flush(); username = new Label() { Text = Client.MySelf.name, Location = new Point(64, 10), Size = new Size(120, 24), ForeColor = Color.White, Font = new Font(CustomFonts.Fonts.Families[1], 14, FontStyle.Bold), TextAlign = ContentAlignment.BottomLeft }; userPicture = new CachedPictureBox(Client.MyData.profile.image_48); userPicture.Location = new Point(8, 8); userPicture.Size = new Size(48, 48); TeamName = new Label() { Text = Client.MyTeam.name, Size = new Size(188, 53), Location = new Point(16, 0), TextAlign = ContentAlignment.MiddleLeft, ForeColor = Color.White, Font = new Font(CustomFonts.Fonts.Families[1], 14, FontStyle.Bold) }; profileTitle.Controls.Add(username); teamTitle.Controls.Add(TeamName); profileTitle.Controls.Add(userPicture); //Default to general channel. SelectChannel(Client.Channels[0].id); this.Invalidate(); }
public ConnectedInterface(SlackSocketClient connectedClient, LoginResponse loginDetails) { Client = connectedClient; chats = new Dictionary <string, ChatInterface>(); InitializeComponent(); channelList = new SlackChannelList(this); channelList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; channelList.AutoScroll = true; channelList.BackColor = Color.FromArgb(0x4D, 0x39, 0x4B); channelList.Location = new Point(0, 52); //53 channelList.Margin = new Padding(0); channelList.Name = "channelList"; channelList.Size = new Size(220, 671); channelList.TabIndex = 2; channelList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; Controls.Add(this.channelList); channelList.Flush(); username = new Label() { Text = Client.MySelf.name, Location = new Point(64, 10), Size = new Size(120, 24), ForeColor = Color.White, Font = new Font(CustomFonts.Fonts.Families[1], 14, FontStyle.Bold), TextAlign = ContentAlignment.BottomLeft }; userPicture = new CachedPictureBox(Client.MyData.profile.image_48); userPicture.Location = new Point(8, 8); userPicture.Size = new Size(48, 48); TeamName = new Label() { Text = Client.MyTeam.name, Size = new Size(188, 53), Location = new Point(16, 0), TextAlign = ContentAlignment.MiddleLeft, ForeColor = Color.White, Font = new Font(CustomFonts.Fonts.Families[1], 14, FontStyle.Bold) }; profileTitle.Controls.Add(username); teamTitle.Controls.Add(TeamName); profileTitle.Controls.Add(userPicture); //Default to general channel. SelectChannel(Client.Channels[0].id); this.Invalidate(); }
public void Start() { if (_slackClient != null) return; _log.Info("Starting..."); _slackClient = new SlackSocketClient(_apiKeyToken); _slackClient.OnHello += _slackClient_OnHello; _slackClient.Connect(_slackClient_OnConnected); _keepAliveTimer.Change(60000, 60000); }
public override void Configure() { Log.Debug(nameof(Configure)); base.Configure(); _client = new SlackSocketClient(AuthToken); _client.OnMessageReceived += Client_OnMessageReceived; _timer = new System.Timers.Timer(60000 * 5); _reconnectTimer = new System.Timers.Timer(30000); Outputs["SlackChannelGeneral"].OnMessage += ChannelGeneral_OnMessage; Outputs["SlackChannelOctgnLobby"].OnMessage += ChannelOctgnLobby_OnMessage; Outputs["SlackChannelOctgnDev"].OnMessage += ChannelOctgnDev_OnMessage; }
/// <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; } }
/// <summary> /// Test if we can connect /// </summary> /// <param name="slackSocketClient"></param> private void TestConnection(SlackSocketClient slackSocketClient) { slackSocketClient.TestAuth((testme) => { Console.WriteLine("TestAuth"); if (testme.ok == false) { Console.WriteLine("Failed to connect"); } else { } }); }
/// <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); } }); }
public void Start() { if (_slackClient != null) { return; } _log.Info("Starting..."); _slackClient = new SlackSocketClient(_apiKeyToken); _slackClient.OnHello += _slackClient_OnHello; _slackClient.Connect(_slackClient_OnConnected); _keepAliveTimer.Change(60000, 60000); }
private static DeletedResponse DeleteMessage(SlackSocketClient client, string channel, DateTime messageTimestamp) { DeletedResponse deletedResponse = null; using (var sync = new InSync(nameof(SlackClient.DeleteMessage))) { client.DeleteMessage(response => { deletedResponse = response; sync.Proceed(); }, channel, messageTimestamp); } return(deletedResponse); }
protected MessageHandlerBase(SlackSocketClient client, HandlerContext context, ILogger logger) { Client = client; Context = context; Logger = logger; _retryPolicy = Policy .Handle <RateLimitedException>() .WaitAndRetryAsync( 10, retryAttempt => TimeSpan.FromSeconds(5 * retryAttempt), (_, timeSpan, retry, _) => Logger.LogWarning($"Rate limited exception. Attempt {retry}, Wait {timeSpan}")); Client.BindCallback <NewMessage>(OnMessageReceived); }
/// <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; } }
public void TestConnectPostAndDelete() { // given SlackSocketClient client = this.fixture.CreateUserClient(); string channel = this.fixture.Config.TestChannel; // when DateTime messageTimestamp = PostMessage(client, channel); DeletedResponse deletedResponse = DeleteMessage(client, channel, messageTimestamp); // then Assert.NotNull(deletedResponse); Assert.True(deletedResponse.ok); Assert.Equal(channel, deletedResponse.channel); Assert.Equal(messageTimestamp, deletedResponse.ts); }
public Slack() { var token = ConfigurationManager.AppSettings["slack.auth.token"]; _connectionTimer = new System.Timers.Timer(1000 * 60); // 1 minute _connectionTimer.Elapsed += _connectionTimer_Elapsed; _connectionTimer.Start(); _client = new SlackSocketClient(token); _client.OnMessageReceived += _client_OnMessageReceived; _client.Connect(response => { LogManager.GetCurrentClassLogger().Info("Connected to Slack"); _botId = _client.Users.FirstOrDefault(x => x.name == "mooch")?.id; }); }
public void TestConnectPostAndDelete() { // given SlackSocketClient client = ClientHelper.GetClient(_config.Slack.UserAuthToken); string channel = _config.Slack.TestChannel; // when DateTime messageTimestamp = PostMessage(client, channel); DeletedResponse deletedResponse = DeleteMessage(client, channel, messageTimestamp); // then Assert.IsNotNull(deletedResponse, "No response was found"); Assert.IsTrue(deletedResponse.ok, "Message not deleted!"); Assert.AreEqual(channel, deletedResponse.channel, "Got invalid channel? Something's not right here..."); Assert.AreEqual(messageTimestamp, deletedResponse.ts, "Got invalid time stamp? Something's not right here..."); }
public void Start() { LoadConfig(); rand = new Random(); LoadFaces(); haarCascade = new CascadeClassifier(config.classifierFile); client = new SlackSocketClient(config.botToken); checkSocketTimer = new System.Timers.Timer(); checkSocketTimer.Elapsed += CheckSocketConnected; checkSocketTimer.Interval = 10000; // in miliseconds checkSocketTimer.Start(); try { ManualResetEventSlim clientReady = new ManualResetEventSlim(false); ManualResetEventSlim stopClient = new ManualResetEventSlim(false); client.Connect((connected) => { // This is called once the client has emitted the RTM start command clientReady.Set(); Console.WriteLine("Connected!"); }, () => { // This is called once the RTM client has connected to the end point }); clientReady.Wait(); client.OnMessageReceived += OnMessageReceived; client.BindCallback <NewFileSharedMessage>(OnNewFileShared); client.GetChannelList(GetChannelsCallback); var c = client.Channels.Find(x => x.name.Equals("general")); //we listen and post only on the general channel myChannels.Add(c); stopClient.Wait(); } catch (Exception e) { Console.WriteLine("Error: Unable to connect to slack."); } }
public void TestConnectBot() { EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset); SlackSocketClient client = new SlackSocketClient("IDon'tThinkBotsHaveRTMSupport:("); client.Connect((o) => { Debug.WriteLine("RTM Start"); }, () => { Debug.WriteLine("Connected"); wait.Set(); }); Assert.IsTrue(wait.WaitOne(10000), "Didn't return within a reasonable time."); Assert.IsTrue(client.IsConnected, "Invalid, doesn't think it's connected."); }
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..."); }
private string PostedMessage(SlackSocketClient client) { string messageId = null; using (var sync = new InSync()) { client.PostMessage( response => { messageId = response.ts; Assert.IsTrue(response.Ok, "Error while posting message to channel. "); sync.Proceed(); }, _config.Slack.TestChannel, "Hi there!", as_user: true); } return messageId; }
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); }
void Start(string[] args) { var MyIni = new IniFile("Settings.ini"); if (!MyIni.KeyExists("Token")) { MyIni.Write("Token", "EnterTokenHere"); AUTHTOKEN = MyIni.Read("Token"); } else { AUTHTOKEN = MyIni.Read("Token"); } if (!MyIni.KeyExists("Userbase")) { MyIni.Write("Userbase", "User1,User2,User3"); userbase = MyIni.Read("Userbase").Split(','); } else { userbase = MyIni.Read("Userbase").Split(','); } if (!MyIni.KeyExists("DefaultChannel")) { MyIni.Write("DefaultChannel", "general"); DefaultChannel = MyIni.Read("DefaultChannel"); } else { DefaultChannel = MyIni.Read("DefaultChannel"); } client = new SlackSocketClient(AUTHTOKEN); // Create seperate thread for the head loop to prevent of Thread.Sleep Thread headloop = new Thread(HeadLoop); headloop.Start(); }
private static DeletedResponse DeleteMessage(SlackSocketClient client, string channel, DateTime messageTimestamp) { DeletedResponse deletedResponse = null; var waiter = new EventWaitHandle(false, EventResetMode.ManualReset); client.DeleteMessage(response => { deletedResponse = response; waiter.Set(); }, channel, messageTimestamp); 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..."); }); return deletedResponse; }
private bool ConnectSlackClient() { using (ManualResetEvent connectionEvent = new ManualResetEvent(false)) using (ManualResetEvent connectionSocketEvent = new ManualResetEvent(false)) { this.Client = new SlackSocketClient(this.token); try { this.Client.Connect(x => connectionEvent.Set(), () => connectionSocketEvent.Set()); return WaitHandle.WaitAll(new WaitHandle[] { connectionEvent, connectionSocketEvent }, Timeout); } catch (Exception ex) { this.Logger.Debug(ex); return false; } finally { connectionEvent.Set(); connectionSocketEvent.Set(); } } }
public void Stop() { _log.Info("Shutting down..."); _slackClient = null; }
/// <summary> /// Performs the initial Slack integration. /// </summary> public void StartIntegration() { client = new SlackSocketClient (Token); client.Connect ((loginResponse) => { Connected.Invoke(this, null); client.OnMessageReceived += (obj) => { SlackMessageEventArgs e = new SlackMessageEventArgs { Text = obj.text, Member = new SlackMember(GetUserByName(obj.user)) }; e.Channel = GetChannelByName(obj.channel) == null ? new SlackChannel(e.Member.Name, obj.channel) : new SlackChannel(GetChannelByName(obj.channel)); if (e.Text.Contains($"<@{client.MySelf.id}>")) MentionReceived?.Invoke(this, e); else MessageReceived?.Invoke(this, e); }; }, () => { //socket connected }); }
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 TJBot(SlackSocketClient client) { _client = client; Responders = new List<IResponder>(); runners = new List<IRunner>(); }