Skip to content

Commit

Permalink
Use Slack webhook or Slack API token
Browse files Browse the repository at this point in the history
  • Loading branch information
Vichheann Saing committed May 28, 2016
1 parent f6cd163 commit ae71717
Show file tree
Hide file tree
Showing 4 changed files with 235 additions and 54 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,11 @@ To generate a "Service API Key", see [PagerDuty Support: Adding Services](https:

##### [Slack](https://www.slack.com)

The target for a Slack subscription will be the channel name (including the `#`, for example `#channel`). You can optionally suffix the channel name with `!` and that will cause the alerts to include a `@channel` mention (for example `#channel!`).
You can specify either `SLACK_TOKEN` (which will be evaluated first for compatibility reason) or `SLACK_WEBHOOK_URL` (which should be the preferred method).
If you set `SLACK_TOKEN`, the target for a Slack subscription will be the channel name (including the `#`, for example `#channel`). You can optionally suffix the channel name with `!` and that will cause the alerts to include a `@channel` mention (for example `#channel!`). If you set `SLACK_WEBHOOK_URL`, you don't need to suffix the channel, you can simply use `#channel` or `@channel`.

* `SLACK_TOKEN` - The Slack api auth token. Default: ``
* `SLACK_WEBHOOK_URL` - The Slack webhook URL. Default: ``
* `SLACK_USERNAME` - The username that messages will be sent to slack. Default: `Seyren`
* `SLACK_ICON_URL` - The user icon URL. Default: ``
* `SLACK_EMOJIS` - Mapping between state and emojis unicode. Default: ``
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
*/
package com.seyren.core.service.notification;

import static com.google.common.collect.Iterables.*;
import static com.google.common.collect.Iterables.transform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;
Expand All @@ -28,12 +30,16 @@
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
Expand Down Expand Up @@ -64,37 +70,144 @@ protected SlackNotificationService(SeyrenConfig seyrenConfig, String baseUrl) {
this.baseUrl = baseUrl;
}

@Override
public boolean canHandle(SubscriptionType subscriptionType) {
return subscriptionType == SubscriptionType.SLACK;
}

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException {
String token = seyrenConfig.getSlackToken();
String channel = subscription.getTarget();
String username = seyrenConfig.getSlackUsername();
String iconUrl = seyrenConfig.getSlackIconUrl();
if ( !seyrenConfig.getSlackToken().isEmpty() ) {
LOGGER.info("Will use API token");
notifyUsingApiToken(check, subscription, alerts);
}
else if ( !seyrenConfig.getSlackWebhook().isEmpty() ) {
LOGGER.info("Will use Webhook");
notifyUsingWebhook(check, subscription, alerts);
}
else
LOGGER.warn("Slack token and Slack Webhook are empty. Do nothing.");
}

//
// API Test Token. You should really switch to Webhook.
// Just copied previous code.
//

private void notifyUsingApiToken(Check check, Subscription subscription, List<Alert> alerts) {
String token = seyrenConfig.getSlackToken();
String channel = subscription.getTarget();
String username = seyrenConfig.getSlackUsername();
String iconUrl = seyrenConfig.getSlackIconUrl();

List<String> emojis = extractEmojis();

String url = String.format("%s/api/chat.postMessage", baseUrl);
HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
HttpPost post = new HttpPost(url);
post.addHeader("accept", "application/json");

List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("token", token));
parameters.add(new BasicNameValuePair("channel", StringUtils.removeEnd(channel, "!")));
parameters.add(new BasicNameValuePair("text", formatContent(emojis, check, subscription, alerts)));
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("icon_url", iconUrl));

try {
post.setEntity(new UrlEncodedFormEntity(parameters));
if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
}
HttpResponse response = client.execute(post);
if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(), new BasicResponseHandler().handleResponse(response));
}
} catch (Exception e) {
LOGGER.warn("Error posting to Slack", e);
} finally {
post.releaseConnection();
HttpClientUtils.closeQuietly(client);
}
}

private String formatContent(List<String> emojis, Check check, Subscription subscription, List<Alert> alerts) {
String url = formatCheckUrl(check);
String alertsString = formatAlert(alerts);

String channel = subscription.getTarget().contains("!") ? "<!channel>" : "";

List<String> emojis = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis())
String description = formatDescription(check);

final String state = check.getState().toString();

return String.format("%s*%s* %s [%s]%s\n```\n%s\n```\n#%s %s",
Iterables.get(emojis, check.getState().ordinal(), ""),
state,
check.getName(),
url,
description,
alertsString,
state.toLowerCase(Locale.getDefault()),
channel
);
}

private List<String> extractEmojis() {
List<String> emojis = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis())
);
return emojis;
}

private String formatCheckUrl(Check check) {
String url = String.format("%s/#/checks/%s", seyrenConfig.getBaseUrl(), check.getId());
return url;
}

private String formatAlert(List<Alert> alerts) {
String alertsString = Joiner.on("\n").join(transform(alerts, new Function<Alert, String>() {
@Override
public String apply(Alert input) {
return String.format("%s = %s (%s to %s)", input.getTarget(), input.getValue().toString(), input.getFromType(), input.getToType());
}
}));
return alertsString;
}

private String formatDescription(Check check) {
String description;
if (StringUtils.isNotBlank(check.getDescription())) {
description = String.format("\n> %s", check.getDescription());
} else {
description = "";
}
return description;
}

//
// Webhook
//

private void notifyUsingWebhook(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException {
String webhookUrl = seyrenConfig.getSlackWebhook();

List<String> emojis = extractEmojis();

String url = String.format("%s/api/chat.postMessage", baseUrl);
HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
HttpPost post = new HttpPost(url);
HttpPost post = new HttpPost(webhookUrl);
post.addHeader("accept", "application/json");

List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("token", token));
parameters.add(new BasicNameValuePair("channel", StringUtils.removeEnd(channel, "!")));
parameters.add(new BasicNameValuePair("text", formatContent(emojis, check, subscription, alerts)));
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("icon_url", iconUrl));

try {
post.setEntity(new UrlEncodedFormEntity(parameters));
String message = generateMessage(emojis, check, subscription, alerts);
post.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
LOGGER.info("> message: {}", message);
}
HttpResponse response = client.execute(post);
if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
LOGGER.info("> message: {}", message);
LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(), new BasicResponseHandler().handleResponse(response));
}
} catch (Exception e) {
Expand All @@ -103,43 +216,34 @@ public void sendNotification(Check check, Subscription subscription, List<Alert>
post.releaseConnection();
HttpClientUtils.closeQuietly(client);
}

}

@Override
public boolean canHandle(SubscriptionType subscriptionType) {
return subscriptionType == SubscriptionType.SLACK;
private String generateMessage(List<String> emojis, Check check, Subscription subscription, List<Alert> alerts) throws JsonProcessingException {
Map<String,String> payload = new HashMap<String, String>();
payload.put("channel", subscription.getTarget());
payload.put("username", seyrenConfig.getSlackUsername());
payload.put("text", formatText(emojis, check, subscription, alerts));
payload.put("icon_url", seyrenConfig.getSlackIconUrl());

String message = new ObjectMapper().writeValueAsString(payload);
return message;
}

private String formatContent(List<String> emojis, Check check, Subscription subscription, List<Alert> alerts) {
String url = String.format("%s/#/checks/%s", seyrenConfig.getBaseUrl(), check.getId());
String alertsString = Joiner.on("\n").join(transform(alerts, new Function<Alert, String>() {
@Override
public String apply(Alert input) {
return String.format("%s = %s (%s to %s)", input.getTarget(), input.getValue().toString(), input.getFromType(), input.getToType());
}
}));
private String formatText(List<String> emojis, Check check, Subscription subscription, List<Alert> alerts) {
String url = formatCheckUrl(check);
String alertsString = formatAlert(alerts);

String channel = subscription.getTarget().contains("!") ? "<!channel>" : "";

String description;
if (StringUtils.isNotBlank(check.getDescription())) {
description = String.format("\n> %s", check.getDescription());
} else {
description = "";
}
String description = formatDescription(check);

final String state = check.getState().toString();

return String.format("%s*%s* %s [%s]%s\n```\n%s\n```\n#%s %s",
return String.format("%s *%s* %s (<%s|Open>)%s\n```\n%s\n```",
Iterables.get(emojis, check.getState().ordinal(), ""),
state,
check.getName(),
url,
description,
alertsString,
state.toLowerCase(Locale.getDefault()),
channel
alertsString
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public class SeyrenConfig {
private final String ircCatHost;
private final String ircCatPort;
private final String slackToken;
private final String slackWebhook;
private final String slackUsername;
private final String slackIconUrl;
private final String slackEmojis;
Expand Down Expand Up @@ -146,6 +147,7 @@ public SeyrenConfig() {

// Slack
this.slackToken = configOrDefault("SLACK_TOKEN", "");
this.slackWebhook = configOrDefault("SLACK_WEBHOOK_URL", "");
this.slackUsername = configOrDefault("SLACK_USERNAME", "Seyren");
this.slackIconUrl = configOrDefault("SLACK_ICON_URL", "");
this.slackEmojis = configOrDefault("SLACK_EMOJIS", "");
Expand Down Expand Up @@ -396,6 +398,11 @@ public String getSlackToken() {
return slackToken;
}

@JsonIgnore
public String getSlackWebhook() {
return slackWebhook;
}

@JsonIgnore
public String getSlackUsername() {
return slackUsername;
Expand Down
Loading

0 comments on commit ae71717

Please sign in to comment.