xyz.putzi.slackmc.bungeecord.messaging.Messenger.java Source code

Java tutorial

Introduction

Here is the source code for xyz.putzi.slackmc.bungeecord.messaging.Messenger.java

Source

/*
 * SlackMc Bukkit/Bungeecord Api - Bukkit/Bungeecord plugin for Slack
 *      Copyright (C) 2016  putzi_x  (http://putzi.xyz)
 *
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 */

package xyz.putzi.slackmc.bungeecord.messaging;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.md_5.bungee.api.plugin.Plugin;
import xyz.putzi.slackmc.common.messaging.model.SlackMessenger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class Messenger implements SlackMessenger {

    private String message;
    private String botName;
    private String botIcon;
    private JsonArray attachment;
    private String channel;
    private Boolean markDown;

    private final String slackHookUrl;
    private final Plugin plugin;

    public Messenger(Plugin plugin, String slackHookUrl) {
        this.slackHookUrl = Objects.requireNonNull(slackHookUrl, "slackHookUrl");
        this.plugin = Objects.requireNonNull(plugin, "plugin");
    }

    @Override
    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public void setBotName(String botName) {
        this.botName = botName;
    }

    public void setBotIcon(String botIcon) {
        this.botIcon = botIcon;
    }

    @Override
    public void setAttachment(JsonArray attachments) {
        this.attachment = attachments;
    }

    @Override
    public void setChannel(String channel) {
        this.channel = channel;
    }

    @Override
    public void setMarkDown(boolean markDown) {
        this.markDown = markDown;
    }

    private JsonObject toJsonObject() {
        JsonObject object = new JsonObject();
        if (message != null)
            object.addProperty("text", message);
        if (botName != null)
            object.addProperty("username", botName);
        if (botIcon != null)
            if (botIcon.startsWith(":") && botIcon.endsWith(":"))
                object.addProperty("icon_emoji", botIcon);
            else
                object.addProperty("icon_url", botIcon);
        if (markDown != null)
            object.addProperty("mrkdown", markDown);
        if (attachment != null)
            object.add("attachments", attachment);
        if (channel != null)
            object.addProperty("channel", channel);

        return object;
    }

    @Override
    public void send() {
        plugin.getProxy().getScheduler().runAsync(plugin, () -> {
            JsonObject object = toJsonObject();
            Objects.requireNonNull(object, "Object must not be null");

            String payload = "payload=" + object.toString();
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(slackHookUrl).openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);

                BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
                outputStream.write(payload.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                outputStream.close();

                int serverResponse = connection.getResponseCode();
                if (serverResponse >= 400 && serverResponse < 600) {
                    BufferedInputStream errorStream = new BufferedInputStream(connection.getErrorStream());
                    String errorMessage = CharStreams.toString(new InputStreamReader(errorStream, Charsets.UTF_8));
                    System.out.println(errorMessage);
                    System.out.println(serverResponse);
                    errorStream.close();
                }
                connection.disconnect();
            } catch (IOException exception) {
                System.out.println("An error occurred while sending message to slack!");
            }
        });
    }
}