TestBotCommand.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using Microsoft.AspNetCore.Http;
  2. using SlackAPI;
  3. using System.Text.Json;
  4. using System;
  5. using sera_slackbot.Library;
  6. using System.Collections.Generic;
  7. using SlackAPI.RPCMessages;
  8. namespace sera_slackbot.Commands
  9. {
  10. public class TestBotCommand : IBotCommand
  11. {
  12. private JsonFileSaver saver;
  13. private string channelId;
  14. private string userId;
  15. private string text;
  16. private string message;
  17. public TestBotCommand(JsonFileReader reader, JsonFileSaver saver)
  18. {
  19. }
  20. public void ExtractValidData(JsonElement slackEvent)
  21. {
  22. this.text = slackEvent.GetProperty("text").ToString();
  23. this.channelId = slackEvent.GetProperty("channel").ToString();
  24. this.userId = slackEvent.GetProperty("user").ToString();
  25. }
  26. public bool WillTrigger(JsonElement slackEvent)
  27. {
  28. var text = slackEvent.GetProperty("text").ToString();
  29. return text.StartsWith("test", StringComparison.InvariantCultureIgnoreCase);
  30. }
  31. public dynamic Run(SlackClient client)
  32. {
  33. var request = new List<Tuple<string, string>>();
  34. request.Add(new Tuple<string, string>("channel", channelId));
  35. request.Add(new Tuple<string, string>("user", userId));
  36. request.Add(new Tuple<string, string>("blocks", BuildBlocks()));
  37. var callback = new Action<PostMessageResponse>((response) =>
  38. {
  39. Console.WriteLine("Direct API call {0}", response.error);
  40. });
  41. Console.WriteLine(JsonSerializer.Serialize(request.ToArray(), new JsonSerializerOptions { WriteIndented = true }));
  42. client.APIRequestWithToken(callback, request.ToArray());
  43. return new
  44. {
  45. code = StatusCodes.Status200OK,
  46. body = ""
  47. };
  48. }
  49. private string BuildBlocks()
  50. {
  51. var blocks = new List<dynamic>();
  52. blocks.Add(new
  53. {
  54. type = "section",
  55. text = new
  56. {
  57. type = "mrkdwn",
  58. text = "Section text"
  59. }
  60. });
  61. var actionElements = new List<dynamic>();
  62. actionElements.Add(new
  63. {
  64. type = "button",
  65. text = new
  66. {
  67. type = "plain_text",
  68. text = "Yes",
  69. emoji = false
  70. },
  71. value = "yes"
  72. });
  73. actionElements.Add(new
  74. {
  75. type = "button",
  76. text = new
  77. {
  78. type = "plain_text",
  79. text = "No",
  80. emoji = false
  81. },
  82. value = "no"
  83. });
  84. blocks.Add(new
  85. {
  86. type = "actions",
  87. elements = actionElements.ToArray()
  88. });
  89. var jsonText = JsonSerializer.Serialize(blocks);
  90. return jsonText;
  91. }
  92. }
  93. }