Skip to content

new Client that handles slash command async responses #7

Description

@dfreis

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;
   }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions