Search code examples
javaminecraftbukkit

Minecraft (bukkit) plugins, send user a clickable link


Im developing a bukkit plugin and I need to send a URL to the user, I need to have the link clickable by the user so it can be opened in the users's browser.

I tried using HTML and other types of tags but nothing worked. I also searched Bukkit Java library and did not find anything other than colouring the text output.


Solution

  • To send a clickable link to a client you need to send a raw json message to him, there are different methods to do this:

    Using the /tellraw command

    Using Server.dispatchCommand(<your sender>,<Your command String>); you can let the console execute a command, we want to execute the command /tellraw <user> {text:"Click.",clickEvent:{action:open_url,value:"http://stackoverflow.com/q/34635271"}}. This can be done in code as follows:

    public void sendMessage(Player player, String message, String url) {
        Bukkit.getServer().dispatchCommand(
            Bukkit.getConsoleSender(),
            "/tellraw " + player.getName() + 
            " {text:\"" + message + "\",clickEvent:{action:open_url,value:\"" +
            url + "\"}}");
    }
    

    Using native craftbukkit methods

    We can call some unsafe methods of Bukkit to send a message directly, to do this, we first need to cast our player to a CraftPlayer, then get a EntityPlayer and finally invoke sendPacket on the playerConnection of the player.

    Based on: Gamecube762's JsonMessages.java

    public static PacketPlayOutChat createPacketPlayOutChat(String s){return new PacketPlayOutChat(ChatSerializer.a(s));}
    
    public static void SendJsonMessage(Player p, String s){( (CraftPlayer)p ).getHandle().playerConnection.sendPacket( createPacketPlayOutChat(s) );}
    
    public void sendMessage(Player player, String message, String url) {
        SendJsonMessage(player,
            "{text:\"" + message + "\",clickEvent:{action:open_url,value:\"" +
            url + "\"}}");
    }
    

    Using a libary for bukkit

    There are a lot of people who faced this problem before and wrote a library to solve the hassle.

    These can be found by a simple google search for bukkit send json message.

    Security risks

    The above methods assume YOUR code is under control of the calling of the methods, if the code/data passed to the method is provided by untrusted sources, they can escape out of the json string and add json tags you didn't expect. You should either validate or escape incoming untrusted data.

    More tellraw examples:

    Minecraftforums: 1.8 - Raw JSON Text Examples (for /tellraw, /title, books, signs)