slack-api icon indicating copy to clipboard operation
slack-api copied to clipboard

new Client that handles slash command async responses

Open dfreis opened this issue 9 years ago • 1 comments

this is very similar to SlackWebApiClientImpl and can be used to send responses to 'response_url' when receiving /slash commands. The thing special is the handling of the 'response_type' ('in_channel' or 'ephemeral') within the post(..) method. See also https://api.slack.com/docs/attachments

my code:

public class SlackSlashResponseWebhookClient {
   private String webhookUrl;
   private ObjectMapper mapper;
   private CloseableHttpClient httpClient;

   public SlackSlashResponseWebhookClient(String webhookUrl) {
      this(webhookUrl, null);
   }

   public SlackSlashResponseWebhookClient(String webhookUrl, ObjectMapper mapper) {
      this(webhookUrl, mapper, SlackWebApiConstants.DEFAULT_TIMEOUT);
   }

   public SlackSlashResponseWebhookClient(String webhookUrl, ObjectMapper mapper, int timeout) {
      if (webhookUrl == null) {
         throw new SlackArgumentException("Missing WebHook URL Configuration @ SlackApi");
      } else if (!webhookUrl.startsWith("https://hooks.slack.com/commands/")) {
         throw new SlackArgumentException("Invalid Service URL. WebHook URL Format: https://hooks.slack.com/commands/{id_1}/{id_2}/{token}");
      }
      this.webhookUrl = webhookUrl;
      this.mapper = mapper != null ? mapper : new ObjectMapper();
      httpClient = RestUtils.createHttpClient(timeout);
   }

   public void shutdown() {
      if (httpClient != null) try { httpClient.close(); } catch (Exception e) {}
   }

   public String post(Payload payload, boolean ephemeral) {
      if (payload != null) {
         String message = null;
         try {
            message = mapper.writeValueAsString(payload);
         } catch (JsonProcessingException e) {
            throw new SlackException(e);
         }

         Map<String, String> parameters = new HashMap<String, String>();
         parameters.put("response_url", ephemeral ? "ephemeral" : "in_channel");
         parameters.put("payload", message);
         return RestUtils.execute(httpClient, this.webhookUrl, RestUtils.createUrlEncodedFormEntity(parameters));
      }
      return null;
   }
}

dfreis avatar Dec 01 '15 08:12 dfreis

thanks your report! I'll consider up function to integrate the SlackWebhookClient

allbegray avatar Dec 01 '15 10:12 allbegray