public async Task <SlackResponse> UpdateViewAsync <T>(UpdateViewRequest <T> request, string botToken, string requestUrl = "views.publish") { using (var httpClient = httpClientFactory.CreateClient(nameof(ISlackClient))) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", botToken); HttpResponseMessage response; SlackResponse slackResponse = new SlackResponse(); try { var updateViewSerialized = JsonConvert.SerializeObject(request); response = await httpClient.PostAsync(requestUrl, new StringContent(updateViewSerialized, Encoding.UTF8, "application/json")); var responseSource = response.Content.ReadAsStringAsync().Result; slackResponse = JsonConvert.DeserializeObject <SlackResponse>(responseSource); if (!response.IsSuccessStatusCode) { logger.LogError($"Error occured while sending message in slack with code: {response.StatusCode}"); } } catch (Exception ex) { logger.LogError($"Couldn't update view for user with Id: {request.UserId}. Error: {ex.Message}"); return(slackResponse); } return(slackResponse); } }
public OutgoingWebhookResponse MapToOutgoingWebhookResponse(SlackResponse slackResponse) { return(new OutgoingWebhookResponse { Text = slackResponse.Text }); }
public async Task PickOrders(CoffeeService coffee, User user, string text, SlackResponse response) { if (!int.TryParse(text, out var count)) { throw new NotWellFormedException(); } if (count <= 0) { throw new NotWellFormedException(); } var at = DateTime.Now; await coffee.PickOrderAsync(count, at); var orders = await coffee.GetOrdersAsync(at); var picked = orders.Where(o => o.PickedAt > DateTime.MinValue).ToList(); var sb = new StringBuilder($"<당첨자 명단> {orders.Count}명 중에 {picked.Count}명").AppendLine(); await sb.AppendOrders(coffee, picked); var responseText = sb.ToString(); response .Ephemeral("추첨하였습니다") .InChannel(responseText, "user") .InChannel(responseText, "manager"); }
/// <summary> /// The main method which make HTTP request /// </summary> /// <typeparam name="T"></typeparam> /// <param name="methodName">Name of the method.</param> /// <param name="args">The arguments.</param> /// <returns></returns> /// <exception cref="SlackClientException">Error during the HTTP request process</exception> private async Task Request <T>(string methodName, params KeyValuePair <string, string>[] args) where T : SlackResponse { var url = new Uri(SlackApiRoot, $"{methodName}?token={Uri.EscapeUriString(_token)}"); var request = new HttpRequestMessage(HttpMethod.Post, url); if (args != null && args.Length > 0) { request.Content = new FormUrlEncodedContent(args); } SlackResponse resInfo; try { var response = await _httpClient.SendAsync(request).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); resInfo = JsonConvert.DeserializeObject <T>(content, SerializerSettings); } catch (Exception e) { throw new SlackClientException("Error during the HTTP request process", e); } Response = resInfo; }
public override Task ExecuteAsync(string generator, WebHookHandlerContext context) { // For more information about Slack WebHook payloads, please see // 'https://api.slack.com/outgoing-webhooks' NameValueCollection entry = context.GetDataOrDefault <NameValueCollection>(); // We can trace to see what is going on. Trace.WriteLine(entry.ToString()); // Switch over the IDs we used when configuring this WebHook switch (context.Id) { case "trigger": // Information can be returned using a SlackResponse var triggerReply = new SlackResponse("Hello trigger!"); context.Response = context.Request.CreateResponse(triggerReply); break; case "slash": // Information can be returned in a plain text response context.Response = context.Request.CreateResponse(); context.Response.Content = new StringContent("Hello slash command!"); break; } return(Task.FromResult(true)); }
public async Task <bool> SendMessageAsync(SendMessageRequest request, CancellationToken cancellationToken = default) { using (var httpClient = httpClientFactory.CreateClient(nameof(ISlackClient))) { httpClient.DefaultRequestHeaders.Authorization = request.AppToken != null ? new AuthenticationHeaderValue("Bearer", request.AppToken) : httpClient.DefaultRequestHeaders.Authorization; var channel = await OpenChannelWithUserAsync(request.SlackId, httpClient); SlackResponse slackResponse = await SendMessageInChannelAsync(channel.Id, request.Text, httpClient, "chat.postMessage", request.CallbackId, request.Attachments, request.Blocks, cancellationToken); if (!slackResponse.Ok) { logger.LogError(slackResponse.Error); return(false); } logger.LogInformation( "Sending slack message for user with Id: {@id}, with message: {@message}, test = {@isTest}", request.SlackId, request.Text); return(true); } }
public async Task GetMenu(CoffeeService coffee, User user, string text, SlackResponse response) { var menus = await coffee.GetMenusAsync(); var enabledMenus = menus.Where(m => m.Enabled); var disabledMenus = menus.Where(m => !m.Enabled).ToArray(); var sb = new StringBuilder("*메뉴*").AppendLine(); foreach (var m in enabledMenus) { sb.AppendLine($"*{m.Id}* - {m.Description}: {m.Price}원"); } if (disabledMenus.Length > 0) { sb.AppendLine().AppendLine("*비활성화된 메뉴*"); foreach (var m in disabledMenus) { sb.AppendLine($"{m.Description}"); } } response.Ephemeral(sb.ToString()); }
public async Task <SlackResponse> UpdateViewAsync <T>(UpdateViewRequest <T> request, string requestUrl = "views.publish", CancellationToken cancellationToken = default) { using (var httpClient = httpClientFactory.CreateClient(nameof(ISlackClient))) { HttpResponseMessage response; SlackResponse slackResponse = new SlackResponse(); try { var updateViewSerialized = JsonConvert.SerializeObject(request); response = await httpClient.PostAsync(requestUrl, new StringContent(updateViewSerialized, Encoding.UTF8, "application/json"), cancellationToken); var responseMessage = await response.Content.ReadAsStringAsync(); logger.LogInformation(responseMessage); slackResponse = JsonConvert.DeserializeObject <SlackResponse>(responseMessage); if (!response.IsSuccessStatusCode) { logger.LogError($"Error occured while sending message in slack with code: {response.StatusCode}"); } } catch (Exception ex) { logger.LogError($"Couldn't update view for user with Id: {request.UserId}. Error: {ex.Message}"); return(slackResponse); } return(slackResponse); } }
public void WriteToChannel_BlockMessage_ReturnsCorrectSlackResponse() { //Given const string webhookSecret = "123abc"; const string message = "{ \"blocks\": [ { \"type\": \"section\", \"text\": { \"type\": \"mrkdwn\", \"text\": \":mega: *PA! Usage Report* :mega:\" } } ] }"; SlackResponse expected = new SlackResponse("{\"StatusCode\": 201,\"Content\": \"testing\",\"From\": \"John Doe\"}", true, HttpStatusCode.Created); //When using (AutoMock mock = AutoMock.GetLoose()) { mock.Mock <ISlackActionHandler>() .Setup(x => x.PostMessageToChannel(webhookSecret, message)) .Returns(expected); SlackMessager sut = mock.Create <SlackMessager>(); SlackResponse actual = sut.SendMessage(webhookSecret, message); //Then mock.Mock <ISlackActionHandler>() .Verify(x => x.PostMessageToChannel(webhookSecret, message), Times.Exactly(1)); Assert.Equal(expected.Content, actual.Content); Assert.Equal(expected.IsSuccessful, actual.IsSuccessful); Assert.Equal(expected.StatusCode, actual.StatusCode); } }
public async Task SendActivitiesAsyncShouldSucceed() { var slackResponse = new SlackResponse { Ok = true, Ts = "mockedTS", }; var slackApi = new Mock <SlackClientWrapper>(_testOptions); slackApi.Setup(x => x.TestAuthAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult("mockedUserId")); slackApi.Setup(x => x.PostMessageAsync(It.IsAny <NewSlackMessage>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(slackResponse)); var slackAdapter = new SlackAdapter(slackApi.Object); var activity = new Activity { Type = ActivityTypes.Message, Text = "text", Conversation = new ConversationAccount() { Id = "testConversationId", }, }; Activity[] activities = { activity }; var turnContext = new TurnContext(slackAdapter, activity); var responses = await slackAdapter.SendActivitiesAsync(turnContext, activities, default); Assert.Equal(slackResponse.Ts, responses[0].Id); }
/// <summary> /// Format Slack error response /// </summary> /// <param name="errorDescription">Error to be sent to slack for display</param> /// <returns>Slack formatted error response</returns> private static SlackResponse FormatErrorSlackResponse(string errorDescription) { var slackResponse = new SlackResponse(); slackResponse.text = "Next available trains"; // create attachment object var attachmentList = new List <Attachments>(); var attachment = new Attachments(); attachment.color = "#1E98D1"; attachment.footer = "Seprr © 2020"; attachment.ts = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString(); var fieldList = new List <Fields>(); attachment.text = $"*There has been an error processing your request. Please try again.*"; var field = new Fields(); field.value = $"* Details:* {errorDescription}"; field.title = $"Error Info # "; fieldList.Add(field); attachment.fields = fieldList; attachmentList.Add(attachment); slackResponse.attachments = attachmentList; return(slackResponse); }
public async Task <IActionResult> Execute([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { try { var request = await req.ReadSlackRequest(); if (string.IsNullOrWhiteSpace(request.Text)) { return(SlackResponse.NoLocationProvided().AsJson()); } var location = new LocationFromRequest(request.Text); var totalAvailableSeats = _locations.TotalCapacityOf(location); var filledSeats = _capacityService.NumberOfDesksOccupiedForLocation(location); var result = $"There are {filledSeats} of {totalAvailableSeats} desks used in {request.Text}."; var imageUrl = _urlHelper.CapacityImageFor(location); return(new SlackResponse(result, imageUrl).AsJson()); } catch (Exception ex) { log.LogError(ex.ToString()); throw; } }
private ContentResult SlackResponse(SlackResponse response) { return(new ContentResult { StatusCode = (int)response.Status, ContentType = response.ContentType, Content = response.Body(_jsonSettings) }); }
public SlashCommandResponse MapToSlashCommandResponse(SlackResponse slackResponse) { return(new SlashCommandResponse { Text = slackResponse.SuppressMessageTextOnSlashCommandResponse ? "" : slackResponse.Text, ResponseType = slackResponse.ResponseType, Attachments = slackResponse.Attachments }); }
public async Task CancelOrder(CoffeeService coffee, User user, string text, SlackResponse response) { var canceled = await coffee.CancelOrderAsync(user.Id, DateTime.Now, DateTime.MinValue); response.Ephemeral(canceled != null ? "취소하였습니다." : "예약이 없습니다."); if (canceled != null) { response.InChannel($"{user.Name} 님이 주문을 취소하였습니다."); } }
private async Task Send(SlackResponse slackResponse) { WriteLineToConsole($"Sending message"); string json = Serialiser.ToJsonString <SlackResponse>(slackResponse); byte[] buffer = Encoding.UTF8.GetBytes(json); await _clientWebSocket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None); }
private async Task <IActionResult> DoAsync() { var workspaceName = HttpContext.SlackWorkspaceName(); var request = new SlackRequest(HttpContext, await _slackService.GetWorkspaceAsync(workspaceName)); var response = new SlackResponse(request); // 기다리지 않는다. Task.Run(() => ExecuteCommand(_dbContextOptions, request, response)); return(Ok()); }
private static async Task SendSlackResponse(string text, string responseUrl) { var client = new HttpClient(); var slackResponse = new SlackResponse() { Text = text, ResponseType = "ephemeral" }; await client.PostAsJsonAsync(responseUrl, slackResponse); }
public async Task FillWallet(CoffeeService coffee, User user, string text, SlackResponse response) { if (!int.TryParse(text, out var amount)) { throw new NotWellFormedException(); } var u = await coffee.FillWalletAsync(user.Id, amount, DateTime.Now); response.Ephemeral($"현재 잔액은 {u.Deposit}원 입니다."); }
public async Task ChangeMenu(CoffeeService coffee, User user, string text, SlackResponse response) { var menu = UnpackMenu(text); if (menu == null) { throw new NotWellFormedException(); } await coffee.ChangeMenuAsync(menu); response.Ephemeral($"{menu.Id}를 {menu.Price}원으로 수정하였습니다."); }
public override Task ExecuteAsync(string generator, WebHookHandlerContext context) { NameValueCollection nvc; if (context.TryGetData <NameValueCollection>(out nvc)) { string question = nvc["subtext"]; string msg = string.Format("The answer to '{0}' is '{1}'.", question, "Often"); SlackResponse reply = new SlackResponse(msg); context.Response = context.Request.CreateResponse(reply); } return(Task.FromResult(true)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { logger = log; var slackResponse = new SlackResponse { text = $"", icon_emoji = ":yami:", username = "******", link_names = "1" }; string bodyContent = await new StreamReader(req.Body).ReadToEndAsync(); var values = System.Web.HttpUtility.ParseQueryString(bodyContent); var jsonContent = JsonConvert.SerializeObject(values.AllKeys.ToDictionary(k => k, k => values[k])); var slackRequest = JsonConvert.DeserializeObject <SlackRequest>(jsonContent); if (slackRequest.text.Contains("--help") || slackRequest.text.Contains("-h")) { return(HelpActionResult()); } // list request var fileListRequest = ToFileListRequst(slackRequest); if (ValidateFileListRequest(fileListRequest) != null) { slackResponse.text = ValidateFileListRequest(fileListRequest); return((ActionResult) new OkObjectResult(JsonConvert.SerializeObject(slackResponse))); } var listResponse = await ExecuteGetFileListRequestAsync(fileListRequest); if (listResponse.files.Count == 0) { slackResponse.text = $"削除対象のファイルが0件です"; return((ActionResult) new OkObjectResult(JsonConvert.SerializeObject(slackResponse))); } // delete request var files = listResponse.files; var deleteMessage = await ExecuteDeleteFileListRequestAsync(files); slackResponse.text = deleteMessage; return((ActionResult) new OkObjectResult(JsonConvert.SerializeObject(slackResponse))); }
public async Task EnableMenu(CoffeeService coffee, User user, string text, SlackResponse response) { var splitted = text.Split(' ').Select(s => s.Trim()).ToArray(); if (splitted.Length != 2 || !int.TryParse(splitted[1], out var enabledInt)) { throw new NotWellFormedException(); } var enabled = enabledInt > 0; await coffee.EnableMenuAsync(splitted[0], enabled); response.Ephemeral($"{splitted[0]}를 {(enabled ? "활성화" : "비활성화")} 시켰습니다."); }
public async Task GetHelp(CoffeeService coffee, User user, string text, SlackResponse response) { var sb = new StringBuilder(); foreach ((var command, var name, var description) in handlers.GetDescriptions()) { if (command.ForManager && !user.IsManager) { continue; } sb.AppendLine($"*{name}* : {description}"); } response.Ephemeral(sb.ToString()); }
public SlackResponse Get() { var words = new string[] { "We need more Big data", "Containers!!!", "Scale more", "We need Innovation", "What about Quantum Computing?", "Agile it", "Lean Enterprise", "Innovate", "You only fail when you fail to learn", "Do the right thing it is as important as doing the thing right", "Microservices!", "Woman in code", "What is devops?" }; var rand = new Random(); var word = words[rand.Next(0, words.Length)]; var result = new SlackResponse() { response_type = "in_channel", text = word }; return(result); }
public async Task MakeOrder(CoffeeService coffee, User user, string text, SlackResponse response) { var canceled = await coffee.CancelOrderAsync(user.Id, DateTime.Now, DateTime.MinValue); var order = await coffee.MakeOrderAsync(user.Id, text, DateTime.Now, canceled); var deposit = await coffee.GetDepositAsync(user.Id); response.Ephemeral($"{order.Price}원, 현재 잔액 {deposit}원"); if (canceled != null && canceled.IsPicked && order.Price != canceled.Price) { response.Ephemeral($"추첨된 메뉴와 가격이 다릅니다. 추출러에게 바뀐 메뉴를 확실히 알려주세요."); } response.InChannel($"{user.Name} 님이 {order.MenuId}{(canceled != null ? "로 변경" : "를 주문")} 하였습니다."); }
public async Task GetOrders(CoffeeService coffee, User user, string text, SlackResponse response) { var at = DateTime.Now; var orders = await coffee.GetOrdersAsync(at); if (orders.Count <= 0) { response.Ephemeral("주문자가 없습니다."); return; } var sb = new StringBuilder(); await sb.AppendOrderInfo(coffee, orders); response.Ephemeral(sb.ToString()); }
public async Task GetHistory(CoffeeService coffee, User user, string text, SlackResponse response) { if (!int.TryParse(text, out int days)) { days = 180; } StringBuilder sb = new StringBuilder(); var walletHistory = await coffee.GetFillHistories(user.Id, DateTime.Now, days); foreach (var fill in walletHistory) { sb.AppendLine($"{fill.At.Month}월 {fill.At.Day}일 : *{fill.Amount}* 원"); } response.Ephemeral(sb.ToString()); }
private static IActionResult HelpActionResult() { var text = $@" ``` ファイル一括削除 delete-files [START_DATE] [END_DATE] [--all-channels | -ac] [--all-users | -au] -ac, --all-channels 全publicチャンネルを削除対象とする -au, --all-user 全ユーザーのファイルを削除対象とする -h, --help ヘルプ ```"; var slackResponse = new SlackResponse { text = text, icon_emoji = ":yami:", username = "******", link_names = "1" }; return((ActionResult) new OkObjectResult(JsonConvert.SerializeObject(slackResponse))); }
public SlackResponse PostMessage(SlackMessage message) { var httpWebRequest = HttpWebRequest.Create(string.Format("{0}/chat.postMessage", ApiBaseUrl)); SlackResponse response = null; // At the moment, slack does not support json encoded bodies in messages WHICH IS REALLY REALLY CRAZY, everything has to be URI encoded. Who knew! //httpWebRequest.ContentType = "application/json"; //httpWebRequest.Method = "POST"; //using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) //{ // var json = JsonConvert.SerializeObject(message); // streamWriter.Write(json); // streamWriter.Flush(); //} ASCIIEncoding ascii = new ASCIIEncoding(); var messageEncoded = message.EncodeAsURI(); byte[] postBytes = ascii.GetBytes(messageEncoded); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = postBytes.Length; using (var stream = httpWebRequest.GetRequestStream()) { stream.Write(postBytes, 0, postBytes.Length); stream.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); response = JsonConvert.DeserializeObject <SlackResponse>(result); } return(response); }