Java

Spigot プレイヤー座標を取得しJSONでPOSTする

1.18.1での二秒ごとにユーザーの座標を別のサーバーにPOSTするサンプルスクリプトです。

package mcchat.mcchat;

import com.fasterxml.jackson.core.JsonParseException;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.TimerTask;
import java.util.Timer;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
import org.json.simple.parser.ParseException;

import okhttp3.*;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;



public final class McChat extends JavaPlugin {

    class OtherRun extends TimerTask {
        @Override
        public void run() {
            getLogger().info("一定期間ごとに実行されるよ!");
            Object players = Bukkit.getOnlinePlayers();
            Map<String, Object> usersInfo = new HashMap();
            for (Player player : Bukkit.getOnlinePlayers()) {
                Map<String, Object> user = new HashMap();
                user.put("UUID", player.getUniqueId().toString());
                user.put("location_x", String.valueOf(player.getLocation().getX()));
                user.put("location_y", String.valueOf(player.getLocation().getY()));
                user.put("location_z", String.valueOf(player.getLocation().getZ()));
                usersInfo.put(player.getName().toString(),user);
            }
            JSONObject usersInfoJson =  new JSONObject(usersInfo);
            getLogger().info(usersInfo.toString());

            try {
                final MediaType mediaTypeJson = okhttp3.MediaType.parse("application/json; charset=UTF-8");
                OkHttpClient client = new OkHttpClient();
                MediaType MIMEType = MediaType.parse("application/json; charset=utf-8");
                final RequestBody requestBody = RequestBody.create(mediaTypeJson, usersInfoJson.toString());
                Request request = new Request.Builder().url("http://localhost:5000/userCoordinates").post(requestBody).build();
                Response response = client.newCall(request).execute();
            } catch (IOException e){
                getLogger().info("error to send info to server");
            }

            getLogger().info("sent info to api server2");
        }
    }

    @Override
    public void onEnable() {
        getLogger().info("プラグインが有効になったよ!");

        Timer timer = null;
        timer = new Timer();
        OtherRun otherRun = new OtherRun();
        timer.schedule( otherRun, 2000, 2000 );
    }

    @Override
    public void onDisable() {
        getLogger().info("プラグインが停止しました");
    }
}

-Java