123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System;
- using System.Text.Json;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Configuration;
- using SlackAPI;
- using sera_slackbot.Library;
- namespace sera_slackbot.Controllers
- {
- [ApiController]
- [Route("interaction")]
- [Produces("application/json")]
- public class SlackInteractionController : ControllerBase
- {
- private readonly ILogger<SlackEventController> logger;
- private readonly IConfiguration configuration;
- private SlackClient client;
- private BotCommandFactory factory;
- private JsonFileReader jsonFileReader;
- private JsonFileSaver jsonFileSaver;
- public SlackInteractionController(IConfiguration config, ILogger<SlackEventController> log)
- {
- configuration = config;
- logger = log;
- var token = configuration.GetSection("Slackbot").GetValue<string>("Bot-User-OAuth-Access-Token");
- this.jsonFileReader = new JsonFileReader(configuration);
- this.jsonFileSaver = new JsonFileSaver(configuration);
- client = new SlackClient(token);
- factory = new BotCommandFactory(this.jsonFileReader, this.jsonFileSaver);
- }
- [HttpGet]
- public IActionResult Get()
- {
- // Console.WriteLine("***Interaction***");
- // foreach (var header in Request.Headers)
- // {
- // Console.WriteLine(header.Key + ": " + header.Value);
- // }
- dynamic response = new
- {
- name = "Slack Interaction Bot",
- code = StatusCodes.Status200OK,
- datetime = DateTime.Now
- };
- return Ok(response);
- }
- [HttpPost]
- public IActionResult HttpPost([FromForm] string payload)
- {
- var payloadObject = JsonSerializer.Deserialize<dynamic>(payload);
- dynamic response = new { code = StatusCodes.Status200OK };
- var typeProperty = payloadObject.GetProperty("type");
- var type = typeProperty.ToString();
- switch (type)
- {
- case "block_actions":
- response = BlockActions(payloadObject);
- break;
- default:
- logger.LogError($"Unknown Interaction Type: '{type}' = {payload}");
- break;
- }
- return StatusCode(response.code, response);
- }
- private dynamic BlockActions(dynamic payload)
- {
- JsonElement actions = payload.GetProperty("actions");
- var valueProperty = "";
- foreach (var action in actions.EnumerateArray())
- {
- valueProperty = action.GetProperty("value").ToString();
- }
- var actionHandler = valueProperty.Split(":")[0];
- var actionValue = valueProperty.Split(":")[1];
- var command = this.factory.CreateInteraction(actionHandler);
- return command.Interaction(client, payload, actionValue);
- }
- }
- }
|