Code Monkey home page Code Monkey logo

java-sdk's Introduction

DBL Java Library

A Java wrapper for the top.gg API

Usage

First, build a DiscordBotListAPI object.

DiscordBotListAPI api = new DiscordBotListAPI.Builder()
	.token("token")
	.botId("botId")
	.build();

Posting stats

DBL provides three ways to post your bots stats.

#1 Posts the server count for the whole bot.

int serverCount = ...; // the total amount of servers across all shards

api.setStats(serverCount);

#2 Posts the server count for an individual shard.

int shardId = ...; // the id of this shard
int shardCount = ...; // the amount of shards
int serverCount = ...; // the server count of this shard

api.setStats(shardId, shardCount, serverCount);

#3 Posts the server counts for every shard in one request.

List<Integer> shardServerCounts = ...; // a list of all the shards' server counts

api.setStats(shardServerCounts);

Checking votes

String userId = ...; // ID of the user you're checking
api.hasVoted(userId).whenComplete((hasVoted, e) -> {
	if(hasVoted)
		System.out.println("This person has voted!");
	else
		System.out.println("This person has not voted!");
});

Getting voting multiplier

api.getVotingMultiplier().whenComplete((multiplier, e) -> {
	if(multiplier.isWeekend())
		System.out.println("It's the weekend, so votes are worth 2x!");
	else
		System.out.println("It's not the weekend :pensive:");
});

Download

Release

Replace VERSION with the latest version or commit hash. The latest version can be found under releases.

Maven

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.github.top-gg</groupId>
        <artifactId>java-sdk</artifactId>
        <version>VERSION</version>
    </dependency>
</dependencies>

Gradle

repositories {
    maven { url 'https://jitpack.io' }
}
dependencies {
    compile 'com.github.top-gg:java-sdk:VERSION'
}

java-sdk's People

Contributors

faith-ie avatar nikammerlaan avatar oliyy avatar pixxies avatar team-woo avatar thibstars avatar tonkku107 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-sdk's Issues

Library broken?

I'm using the setStats() method, with a timer. But the server count keeps staying on N/A.

DiscordBotListAPI discordBotListAPI = new DiscordBotListAPI.Builder()
    .token("")
    .botId("")
    .build();

int serverCount = jda.getGuilds().size();

discordBotListAPI.setStats(serverCount);

I don't get any errors in my console.

Warning when using incorrect token.

When you attempt to set the stats of your bot with an invalid token, there is no indication that your token is invalid. It would be helpful to know whether or not the token is working or not.

Incorrect/Misleading Maven Dependency Info

The README.md has the incorrect info to include this library into a Maven project. The current README specifies this:

<dependencies>
    <dependency>
        <groupId>com.github.DiscordBotList</groupId>
        <artifactId>DBL-Java-Wrapper</artifactId>
        <version>VERSION</version>
    </dependency>
</dependencies>

However, jitpack.io specifies the artifact ID as DBL-Java-Library. In addition, it is unclear what the current version of the library is. The version is not specified in the README, but is only specified in build.gradle. But this is misleading, as jitpack.io specifies that there is a "v" prepended to the version. The dependency info is as follows:

<dependency>
   <groupId>com.github.DiscordBotList</groupId>
      <artifactId>DBL-Java-Library</artifactId>
   <version>v1.0</version>
</dependency>

Illegal reflective acces

When trying to set the server count with the api i get this :

WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.google.gson.internal.ConstructorConstructor (file:/C:/Users/User/.m2/repository/com/google/code/gson/gson/2.6.2/gson-2.6.2.jar) to constructor java.lang.Void() WARNING: Please consider reporting this to the maintainers of com.google.gson.internal.ConstructorConstructor WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release

I'm using java 9.0.4

Your API is broken.

Expected Behavior
That your api is working.

Observed Behavior
Instead your API is returning this:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
at org.json.JSONObject.(JSONObject.java:222)
at org.json.JSONObject.(JSONObject.java:406)
at org.discordbots.api.client.impl.DiscordBotListAPII

Code:

public void onReady(@NotNull ReadyEvent event) {

    DiscordBotListAPI api = new DiscordBotListAPI.Builder()
            .token("Here stands the token ๐Ÿ‘ ")
            .botId("493066387183632387")
            .build();
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {
            //event.getJDA().getPresence().setGame(null);
            new Thread(() -> {
                    for (Member m : Objects.requireNonNull(Main.shardMan.getGuildById("504609411243704365")).getMembers()) {
                        api.hasVoted(m.getId()).whenComplete((hasVoted, e) -> {
                            if (hasVoted) {
                                if (!m.getRoles().contains(Objects.requireNonNull(Main.shardMan.getGuildById("504609411243704365")).getRoleById("610402330315325472"))) {
                                    String votes = "Herbert cant load any data";

                                    Objects.requireNonNull(Objects.requireNonNull(Main.shardMan.getGuildById("504609411243704365")).getTextChannelById("504609411243704365")).sendMessage(new EmbedBuilder()
                                            .setColor(Color.cyan)
                                            .setDescription(m.getAsMention() + " voted the **" + votes + "th** for me :heart:")
                        
             .build()).queue();
                                }
                            }
                        });
                    }

Server count does not update anymore

Version: 2.1.2

DiscordBotListAPI#setStats is no longer properly updating my server counter. It is stuck at 613, while I can see in my application logs that it sits at 653 (at the time of writing).

I update the servercount like so:
topggApi.setStats(jda.getGuilds().size());
which is called every time a guild joins or leaves.

I don't see an error though. Could this please be investigated?

gson cannot deserialise to Void

setStats creates a ResponseTransformer that attempts to deserialise the response to java.lang.Void:

    private CompletionStage<Void> setStats(JSONObject jsonBody) {
        HttpUrl url = baseUrl.newBuilder()
                .addPathSegment("bots")
                .addPathSegment(botId)
                .addPathSegment("stats")
                .build();

        return post(url, jsonBody, Void.class);
    }

    private <E> CompletionStage<E> post(HttpUrl url, JSONObject jsonBody, Class<E> aClass) {
        return post(url, jsonBody, new DefaultResponseTransformer<>(aClass, gson));
    }

public class DefaultResponseTransformer<E> implements ResponseTransformer<E> {

    private final Class<E> aClass;
    private final Gson gson;

    public DefaultResponseTransformer(Class<E> aClass, Gson gson) {
        this.aClass = aClass;
        this.gson = gson;
    }

    @Override
    public E transform(Response response) throws IOException {
        String body = response.body().string();
        return gson.fromJson(body, aClass);
    }

}

However, this does not work on newer versions of java because java.base is a sealed module:

com.google.gson.JsonIOException: Failed making constructor 'java.lang.Void#Void()' accessible; either change its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: Unable to make private java.lang.Void() accessible: module java.base does not "opens java.lang" to unnamed module @45d84a20
	at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:131)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:211)
	at com.google.gson.Gson.fromJson(Gson.java:991)
	at com.google.gson.Gson.fromJson(Gson.java:956)
	at com.google.gson.Gson.fromJson(Gson.java:905)
	at com.google.gson.Gson.fromJson(Gson.java:876)
	at org.discordbots.api.client.io.DefaultResponseTransformer.transform(DefaultResponseTransformer.java:21)
	at org.discordbots.api.client.impl.DiscordBotListAPIImpl$1.onResponse(DiscordBotListAPIImpl.java:234)
	at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
	at java.base/java.lang.Thread.run(Thread.java:833)

I don't think it makes sense anyway. If you are not interested in the response, why deserialise it? Probably better to not use a ResponseTransformer and complete the future with null when done instead of deserialising to Void.

Inconsistent naming and values for setStats and getGuildCount

The problem

When I checked the code, I noticed, that setStats requires you to provide the Server count as an Integer.
On the other hand, does getServerCount() return the current Server count on the DBL-Site as a Long.

This makes it unnecessary complicated for the dev to update (or get) his bots Server count on DBL, since it requires them to use two different values: Integer for setStats and Long for getServerCount.
Java-APIs/Wrappers like JDA return the bots Server count as a Long, so you have to first change it to an Integer in order to send it through the setStats method.
While this isn't that complicated, it still is annoying and a useless step to do.

Also, the naming of the methods can be misleading.
Right now does setStats only update the total Server count of the bot, the Server count of a single shard from the bot or the Server count of all the shards the bot has.
Since this is literally the only thing the method does (And I'm fairly sure there won't be any future additions for stats to update) I recommend to rename those to setServerCount, to have a more consistent naming with the getServerCount method.

Links

Here are the mentioned methods that I mean.

setStats in DiscordBotListAPI.java:
https://github.com/DiscordBotList/DBL-Java-Library/blob/219345b9a8704fca8f9c46539ed98979ea53c2cb/src/main/java/org/discordbots/api/client/DiscordBotListAPI.java#L12-L14

getServerCount in Bot.java:
https://github.com/DiscordBotList/DBL-Java-Library/blob/219345b9a8704fca8f9c46539ed98979ea53c2cb/src/main/java/org/discordbots/api/client/entity/Bot.java#L120-L122

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.