1
0
Fork 0
forked from mc/VTools

给mention bot一个获取玩家列表的http接口

This commit is contained in:
Sodium-Aluminate 2023-11-15 22:18:20 +08:00
parent 780834a922
commit afae76d9dd
2 changed files with 57 additions and 0 deletions

View file

@ -0,0 +1,56 @@
package de.strifel.VTools;
import com.google.gson.Gson;
import com.sun.net.httpserver.HttpServer;
import com.velocitypowered.api.proxy.Player;
import org.jetbrains.annotations.TestOnly;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
public class OnlinePlayerQueryService {
private final VTools plugin;
public OnlinePlayerQueryService(VTools plugin) {
this.plugin = plugin;
}
private static final Gson gson = new Gson();
public void register() {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(17611), 0);
server.createContext("/api/getOnlinePlayers", exchange -> {
Collection<Player> players = plugin.getServer().getAllPlayers();
ArrayList<String> playerNames = new ArrayList<>(players.size());
for (Player player : players) {
playerNames.add(player.getUsername());
}
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, 0);
try (OutputStream os = exchange.getResponseBody()) {
String response = gson.toJson(playerNames);
os.write(response.getBytes());
}
});
server.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@TestOnly
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("jerry");
System.out.println(gson.toJson(arrayList));
}
}

View file

@ -46,6 +46,7 @@ public class VTools {
new PlayerStatus(this).register(); new PlayerStatus(this).register();
new GlobalChat(this).register(); new GlobalChat(this).register();
new ServerCloser(this).register(); new ServerCloser(this).register();
new OnlinePlayerQueryService(this).register();
} }
public ProxyServer getServer() { public ProxyServer getServer() {