private static async Task Ping(MattermostWebsocket socket) { while (!_cancellationToken.IsCancellationRequested) { var statuses = await socket.GetStatusesAsync(2000); if (statuses == null) throw new TimeoutException("Timeout getting statuses"); if (statuses.Status != "OK") throw new Exception("Websocket Error"); if (string.IsNullOrWhiteSpace(BotUserId)) throw new Exception("bot user id unknown"); await Task.Delay(TimeSpan.FromMinutes(5), _cancellationToken); } }
private static async Task MainAsync() { if (_configuration.Repl) { Repl(); return; } var url = _configuration.ServerUri.TrimEnd('/') + "/api/v4/websocket"; url = Regex.Replace(url, "^https:", "wss:"); url = Regex.Replace(url, "^http:", "ws:"); using var socket = new MattermostWebsocket(new Uri(url), cancellationToken: _cancellationToken); socket.OnPosted += e => { Console.WriteLine($"{e.ChannelDisplayName}> {e.Post.Message}"); if (BotUserId == e.Post.UserId) return; void Reply(string message) => Processing.CreatePost(message, e.Post.ChannelId, e.Post.GetReplyPostId()); if (e.Post.Message.Equals("nb_kill", StringComparison.InvariantCultureIgnoreCase)) { try { Reply(":dizzy_face:"); } finally { KillMe(); } } if (e.Post.Message.Equals("nb_krp", StringComparison.InvariantCultureIgnoreCase)) { try { Processing.KillRunningProcess?.Invoke(); } catch (Exception ex) { Reply($"Failed... {ex.Message}"); } } PostedChannel.Writer.WriteAsync(e, _cancellationToken).GetAwaiter().GetResult(); }; socket.OnHello += sv => { Console.WriteLine($"ServerVersion: {sv}"); }; socket.OnBotUserId += id => { BotUserId = id; }; socket.OnWebSocketResponse += r => { if (!string.IsNullOrEmpty(r.Status)) Console.WriteLine($"Status: {r.Status} seq={r.SeqReply}"); if (!string.IsNullOrEmpty(r.Event)) Console.WriteLine($"Event: {r.Event} seq={r.Seq}"); if (r.Error != null && r.Error.Any()) foreach (var (k, v) in r.Error) { Console.WriteLine($"ERROR: {k}:{v}"); } }; if (_configuration.Verbose) socket.OnJsonMessage += Console.WriteLine; await socket.Authenticate(_configuration.Token); var listenTask = socket.Listen(); var pingTask = Ping(socket); var processingTask = Process(); // Tasks only finish if there is something wrong var endedTask = await Task.WhenAny(processingTask, listenTask, pingTask); await endedTask; }