使用java api发消息到slack

原创
2016/09/26 22:39
阅读数 987

##maven

		<dependency>
			<groupId>net.gpedro.integrations.slack</groupId>
			<artifactId>slack-webhook</artifactId>
			<version>1.2.1</version>
		</dependency>

##构造field和attachment

public static SlackAttachment newAttachment(String title, String titleLink, String text, List<SlackField> fields){
        SlackAttachment slackAttachment = new SlackAttachment();
        slackAttachment.setFallback(text);
        slackAttachment.setColor("danger");
        slackAttachment.setFields(fields);
        slackAttachment.setTitle(title);
        slackAttachment.setTitleLink(titleLink);
        slackAttachment.setText(text);
        return slackAttachment;
    }

    public static SlackField newField(String name,Object value){
        SlackField field = new SlackField();
        field.setTitle(name);
        field.setValue(Objects.toString(value));
        field.setShorten(false);
        return field;
    }

##发送

public void sendWithAttachment(String title,String link,String text,SlackAttachment attachment){
        try{
            SlackMessage slackMessage = new SlackMessage("");
            slackMessage.setChannel("#" + channel);
            slackMessage.setUsername(String.format("[%s] - Bot",appId));
            slackMessage.setIcon(":exclamation:");
            slackMessage.setAttachments(Collections.singletonList(attachment));
            slackApi.call(slackMessage);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

##docs

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部