1.8.8 Discord Webhook

Discussion in 'Spigot Plugin Development' started by Mitzythecat, Jun 7, 2021.

  1. Hi, I'm trying to send a discord webhook to a channel, but I'm getting a 400 error, I'm not sure why.

    Error:
    Code (Text):
    java.io.IOException: Server returned HTTP response code: 400 for URL: (Had to remove the Discord URL)
    [17:48:39 WARN]:        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1900)
    [17:48:39 WARN]:        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1498)
    [17:48:39 WARN]:        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:268)
    [17:48:39 WARN]:        at me.mitzythecat.blib.utils.DiscordWebhook.execute(DiscordWebhook.java:154)
    [17:48:39 WARN]:        at me.mitzythecat.blib.listeners.KothAnnouncer.onKothStart(KothAnnouncer.java:36)
    Here is the code I'm using to send the discord webhook:
    public void execute() throws IOException {
    if (this.content == null && this.embeds.isEmpty()) {
    throw new IllegalArgumentException("Set content or add at least one EmbedObject");
    }

    JSONObject json = new JSONObject();

    json.put("content", this.content);
    json.put("username", this.username);
    json.put("avatar_url", this.avatarUrl);
    json.put("tts", this.tts);

    if (!this.embeds.isEmpty()) {
    List<JSONObject> embedObjects = new ArrayList<>();

    for (EmbedObject embed : this.embeds) {
    JSONObject jsonEmbed = new JSONObject();

    jsonEmbed.put("title", embed.getTitle());
    jsonEmbed.put("description", embed.getDescription());
    jsonEmbed.put("url", embed.getUrl());

    if (embed.getColor() != null) {
    Color color = embed.getColor();
    int rgb = color.getRed();
    rgb = (rgb << 8) + color.getGreen();
    rgb = (rgb << 8) + color.getBlue();

    jsonEmbed.put("color", rgb);
    }

    EmbedObject.Footer footer = embed.getFooter();
    EmbedObject.Image image = embed.getImage();
    EmbedObject.Thumbnail thumbnail = embed.getThumbnail();
    EmbedObject.Author author = embed.getAuthor();
    List<EmbedObject.Field> fields = embed.getFields();

    if (footer != null) {
    JSONObject jsonFooter = new JSONObject();

    jsonFooter.put("text", footer.getText());
    jsonFooter.put("icon_url", footer.getIconUrl());
    jsonEmbed.put("footer", jsonFooter);
    }

    if (image != null) {
    JSONObject jsonImage = new JSONObject();

    jsonImage.put("url", image.getUrl());
    jsonEmbed.put("image", jsonImage);
    }

    if (thumbnail != null) {
    JSONObject jsonThumbnail = new JSONObject();

    jsonThumbnail.put("url", thumbnail.getUrl());
    jsonEmbed.put("thumbnail", jsonThumbnail);
    }

    if (author != null) {
    JSONObject jsonAuthor = new JSONObject();

    jsonAuthor.put("name", author.getName());
    jsonAuthor.put("url", author.getUrl());
    jsonAuthor.put("icon_url", author.getIconUrl());
    jsonEmbed.put("author", jsonAuthor);
    }

    List<JSONObject> jsonFields = new ArrayList<>();
    for (EmbedObject.Field field : fields) {
    JSONObject jsonField = new JSONObject();

    jsonField.put("name", field.getName());
    jsonField.put("value", field.getValue());
    jsonField.put("inline", field.isInline());

    jsonFields.add(jsonField);
    }

    jsonEmbed.put("fields", jsonFields.toArray());
    embedObjects.add(jsonEmbed);
    }

    json.put("embeds", embedObjects.toArray());
    }

    URL url = new URL(this.url);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("User-Agent", "bLib-Mitzythecat");
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    OutputStream stream = connection.getOutputStream();
    stream.write(json.toString().getBytes());
    stream.flush();
    stream.close();

    connection.getInputStream().close();
    connection.disconnect();
    }
     
  2. Is the internet properly connected?
     
  3. The fact that op is getting a response code means that the internet is properly connected.

    Can you show us the code where you set the values for the webhook message?
     
  4. I'd highly recommend using this API as it's easy and it works.

    Here is a code example I use for my plugin. Obviously you'd have to slightly adapt it to how your plugin works but you should get the concept.

    Code (Java):
            String webHookURL = DeltaKitPvP.getInstance().getConfig().getString("bounty-announcer-discord-webhook-url");
            if (webHookURL == null)
                return;

            DecimalFormat df = new DecimalFormat("###,###,###,###,###.##");
            String v = df.format(amount);

            WebhookClient webhookClient = WebhookClient.withUrl(webHookURL);
            WebhookEmbedBuilder embedBuilder = new WebhookEmbedBuilder();
            embedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("DeltaPVP", null, null));
            embedBuilder.setTitle(new WebhookEmbed.EmbedTitle("Bounty Claimed", null));
            embedBuilder.setDescription("**__" + killer.getName() + "__** has claimed **__" + victim.getName() + "__**'s bounty of \n"
            + "**$"+ v + "**!");

            embedBuilder.setThumbnailUrl("https://crafatar.com/avatars/" + killer.getUniqueId().toString());
            embedBuilder.setColor(16711680);

            webhookClient.send(embedBuilder.build());
            webhookClient.close();

    pom.xml repo:
    Code (Text):
    <repository>
        <name>jcenter</name>
        <id>bintray-jcenter</id>
        <url>https://jcenter.bintray.com</url>
    </repository>
     
    pom.xml depend:
    Code (Text):
       <dependency>
                <groupId>club.minnced</groupId>
                <artifactId>discord-webhooks</artifactId>
                <version>0.5.6</version>
            </dependency>
     
  5. Thanks, I implemented that library but I'm still getting the same issue

    Here it is:
    Code (Text):
    public class KothAnnouncer implements Listener {

        @EventHandler
        public void onKothStart(KothStartEvent event) {
            if (ConfigFile.getConfig().getBoolean("KOTH-ANNOUNCER.ENABLED")) {
                String description = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.DESCRIPTION").replace("%koth%", event.getEventName().replace("%time%", event.getKoth().getCapzone().getTimeLeft().replace("%world%", StringUtils.getWorldName(event.getKoth().getKothData().getCuboid().getCenter()).replace("%x%", String.valueOf(event.getKoth().getKothData().getCuboid().getCenter().getBlockX()).replace("%y%", String.valueOf(event.getKoth().getKothData().getCuboid().getCenter().getBlockY()).replace("%z%", String.valueOf(event.getKoth().getKothData().getCuboid().getCenter().getBlockZ())))))));
                String title = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.TITLE").replace("%koth%", event.getEventName()).replace("%world%", StringUtils.getWorldName(event.getKoth().getKothData().getCuboid().getCenter()));
                String color = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.COLOR");
                String username = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.USERNAME");
                String footermsg = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.FOOTER.MESSAGE");
                String footerlink = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.FOOTER.LINK");
                String thumbnail = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.THUMBNAIL");
                DiscordWebhook webhook = bLib.getInstance().kothannouncer;
                webhook.setUsername(username);
                webhook.addEmbed(new DiscordWebhook.EmbedObject()
                        .setDescription(description)
                        .setColor(Color.getColor(color))
                        .setTitle(title)
                        .setThumbnail(thumbnail)
                        .setFooter(footermsg, footerlink)
                );
                try {
                    webhook.execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
     
     
  6. It shouldn't matter but what java version are you running?
    Not entirely sure what's causing your error, but the code works well for me, so has to be a issue in your connection.
     
  7. Try creating a new webhook url. Discord can be screwy some times.
     
  8. Java 8

    Thanks, I tried that, same issue

    Code (Text):
    public class KothAnnouncer implements Listener {

        @EventHandler
        public void onKothStart(KothStartEvent event) {
            if (ConfigFile.getConfig().getBoolean("KOTH-ANNOUNCER.ENABLED")) {
                String description = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.DESCRIPTION").replace("%koth%", event.getEventName().replace("%time%", event.getKoth().getCapzone().getTimeLeft().replace("%world%", StringUtils.getWorldName(event.getKoth().getKothData().getCuboid().getCenter()).replace("%x%", String.valueOf(event.getKoth().getKothData().getCuboid().getCenter().getBlockX()).replace("%y%", String.valueOf(event.getKoth().getKothData().getCuboid().getCenter().getBlockY()).replace("%z%", String.valueOf(event.getKoth().getKothData().getCuboid().getCenter().getBlockZ())))))));
                String title = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.TITLE").replace("%koth%", event.getEventName()).replace("%world%", StringUtils.getWorldName(event.getKoth().getKothData().getCuboid().getCenter()));
                String color = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.COLOR");
                String username = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.USERNAME");
                String thumbnail = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.THUMBNAIL");
                String webHookURL = ConfigFile.getConfig().getString("KOTH-ANNOUNCER.WEBHOOK-URL");
                if (webHookURL == null)
                    return;

                WebhookClient webhookClient = WebhookClient.withUrl(webHookURL);
                WebhookEmbedBuilder embedBuilder = new WebhookEmbedBuilder();
                embedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(username, null, null));
                embedBuilder.setTitle(new WebhookEmbed.EmbedTitle(title, null));
                embedBuilder.setDescription(description);

                embedBuilder.setThumbnailUrl(thumbnail);
                embedBuilder.setColor(Integer.valueOf(color));

                webhookClient.send(embedBuilder.build());
                webhookClient.close();
            }
        }
    }

     

    java.io.IOException: Server returned HTTP response code: 400 for URL: (removed discord URL as it contained the token)
    [17:56:55 WARN]: at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1900)
    [17:56:55 WARN]: at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1498)
    [17:56:55 WARN]: at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:268)
     
  9. Is anything in the embed > 2000 characters? Discord throws a 400 if it is...
     
  10. Yeah, you can try with string.substring(0, 2000) to test.
     
  11. Yeah, it is only 25 characters long