Parcourir la source

fixed #9, code refactored, messages added to config and more

mastercake10 il y a 6 ans
Parent
commit
7bbcf58caa

+ 1 - 1
pom.xml

@@ -3,7 +3,7 @@
 	<modelVersion>4.0.0</modelVersion>
 	<groupId>TelegramChat</groupId>
 	<artifactId>TelegramChat</artifactId>
-	<version>1.0.10</version>
+	<version>1.0.11</version>
 	<name>TelegramChat</name>
 	<url>https://www.spigotmc.org/resources/telegramchat.16576/</url>
 	<repositories>

+ 25 - 20
src/main/java/de/Linus122/Metrics/Metrics.java

@@ -20,15 +20,16 @@ import com.google.gson.Gson;
 
 /*
  * SpaceIOMetrics main class by Linus122
- * version: 0.05
+ * version: 0.06
  * 
  */
+
 public class Metrics {
 	private Plugin pl;
 	private final Gson gson = new Gson();
 	
 	private String URL = "https://spaceio.xyz/update/%s";
-	private final String VERSION = "0.05";
+	private final String VERSION = "0.06";
 	private int REFRESH_INTERVAL = 600000;
 	
 	public Metrics(Plugin pl){
@@ -133,7 +134,8 @@ public class Metrics {
 	}
 	// method source: http://www.jcgonzalez.com/linux-get-distro-from-java-examples
 	private String getDistro(){
-		 //lists all the files ending with -release in the etc folder
+		
+		// lists all the files ending with -release in the etc folder
         File dir = new File("/etc/");
         File fileList[] = new File[0];
         if(dir.exists()){
@@ -143,22 +145,25 @@ public class Metrics {
                 }
             });
         }
-        //looks for the version file (not all linux distros)
-        File fileVersion = new File("/proc/version");
-        if(fileVersion.exists()){
-            fileList = Arrays.copyOf(fileList,fileList.length+1);
-            fileList[fileList.length-1] = fileVersion;
-        }       
-        //prints first version-related file
-        for (File f : fileList) {
-            try {
-                BufferedReader br = new BufferedReader(new FileReader(f));
-                String strLine = null;
-                while ((strLine = br.readLine()) != null) {
-                    return strLine;
-                }
-                br.close();
-            } catch (Exception e) {}
+        try {
+	        // looks for the version file (not all linux distros)
+	        File fileVersion = new File("/proc/version");
+	        if(fileVersion.exists() && fileList.length > 0){
+	            fileList = Arrays.copyOf(fileList,fileList.length+1);
+	            fileList[fileList.length-1] = fileVersion;
+	        }    
+	        
+	        // prints first version-related file
+	        for (File f : fileList) {
+	                BufferedReader br = new BufferedReader(new FileReader(f));
+	                String strLine = null;
+	                while ((strLine = br.readLine()) != null) {
+	                    return strLine;
+	                }
+	                br.close();
+	        }
+        } catch (Exception e) {
+        	// Exception is thrown when something went wrong while obtaining the distribution name.
         }
 		return "unknown";    
 	}
@@ -181,4 +186,4 @@ class Data {
 	String osArch;
 	String osVersion;
 	String linuxDistro;
-}
+}

+ 1 - 1
src/main/java/de/Linus122/TelegramChat/API.java

@@ -1,7 +1,7 @@
 package de.Linus122.TelegramChat;
 
 public class API {
-	public static Telegram getTelegramHook(){
+	public static Telegram getTelegramHook() {
 		return Main.telegramHook;
 	}
 }

+ 77 - 16
src/main/java/de/Linus122/TelegramChat/Data.java

@@ -1,16 +1,77 @@
-package de.Linus122.TelegramChat;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.UUID;
-
-public class Data {
-	public String token = "";
-	//Player name // ChatID
-	public HashMap<Integer, UUID> linkedChats = new HashMap<Integer, UUID>();
-	//Player name // RandomInt
-	public HashMap<String, UUID> linkCodes = new HashMap<String, UUID>();
-	public List<Integer> ids = new ArrayList<Integer>();
-	boolean firstUse = true;
-}
+package de.Linus122.TelegramChat;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.UUID;
+
+public class Data {
+	private String token = "";
+	// Player name // ChatID
+	private HashMap<Integer, UUID> linkedChats = new HashMap<Integer, UUID>();
+	// Player name // RandomInt
+	private HashMap<String, UUID> linkCodes = new HashMap<String, UUID>();
+	public List<Integer> ids = new ArrayList<Integer>();
+	private boolean firstUse = true;
+
+	public String getToken() {
+		return token;
+	}
+
+	public void setToken(String token) {
+		this.token = token;
+	}
+
+	public HashMap<Integer, UUID> getLinkedChats() {
+		return linkedChats;
+	}
+
+	public void setLinkedChats(HashMap<Integer, UUID> linkedChats) {
+		this.linkedChats = linkedChats;
+	}
+
+	public HashMap<String, UUID> getLinkCodes() {
+		return linkCodes;
+	}
+
+	public void setLinkCodes(HashMap<String, UUID> linkCodes) {
+		this.linkCodes = linkCodes;
+	}
+
+	public List<Integer> getIds() {
+		return ids;
+	}
+
+	public void setIds(List<Integer> ids) {
+		this.ids = ids;
+	}
+
+	public boolean isFirstUse() {
+		return firstUse;
+	}
+
+	public void setFirstUse(boolean firstUse) {
+		this.firstUse = firstUse;
+	}
+
+	public void addChatPlayerLink(int chatID, UUID player) {
+		linkedChats.put(chatID, player);
+	}
+
+	public void addLinkCode(String code, UUID player) {
+		linkCodes.put(code, player);
+	}
+
+	public UUID getUUIDFromLinkCode(String code) {
+		return linkCodes.get(code);
+	}
+
+	public void removeLinkCode(String code) {
+		linkCodes.remove(code);
+	}
+
+	public UUID getUUIDFromChatID(int chatID) {
+		return linkedChats.get(chatID);
+	}
+
+}

+ 38 - 37
src/main/java/de/Linus122/TelegramChat/LinkTelegramCmd.java

@@ -1,37 +1,38 @@
-package de.Linus122.TelegramChat;
-
-import java.io.IOException;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-public class LinkTelegramCmd implements CommandExecutor {
-
-	@Override
-	public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] args) {
-		if(!(cs instanceof Player)){
-			cs.sendMessage("§cSorry, but you can't link the console currently.");
-		}
-		if(!cs.hasPermission("telegram.linktelegram")){
-			cs.sendMessage("§cYou don't have permissions to use this!");
-			return true;
-		}
-		if(Main.data == null){
-			Main.data = new Data();
-		}
-		if(Main.telegramHook.authJson == null){
-			cs.sendMessage("§cPlease add a bot to your server first! /telegram");
-			return true;
-		}
-		
-		String token = Main.generateLinkToken();
-		Main.data.linkCodes.put(token, ((Player) cs).getUniqueId());
-		cs.sendMessage("§aAdd " + Main.telegramHook.authJson.getAsJsonObject("result").get("username").getAsString() + " to Telegram and send this message to " + Main.telegramHook.authJson.getAsJsonObject("result").get("username").getAsString() + ":");
-		cs.sendMessage("§c" + token);
-		
-		return true;
-	}
-
-}
+package de.Linus122.TelegramChat;
+
+import java.io.IOException;
+
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandExecutor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+public class LinkTelegramCmd implements CommandExecutor {
+
+	@Override
+	public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] args) {
+		if (!(cs instanceof Player)) {
+			cs.sendMessage(Utils.formatMSG("cant-link-console")[0]);
+		}
+		if (!cs.hasPermission("telegram.linktelegram")) {
+			cs.sendMessage(Utils.formatMSG("no-permissions")[0]);
+			return true;
+		}
+		if (Main.getBackend() == null) {
+			Main.initBackend();
+		}
+		if (Main.telegramHook.authJson == null) {
+			cs.sendMessage(Utils.formatMSG("need-to-add-bot-first")[0]);
+			return true;
+		}
+
+		String token = Main.generateLinkToken();
+		Main.getBackend().addLinkCode(token, ((Player) cs).getUniqueId());
+		cs.sendMessage(Utils.formatMSG("get-token",
+				Main.telegramHook.authJson.getAsJsonObject("result").get("username").getAsString(),
+				Main.telegramHook.authJson.getAsJsonObject("result").get("username").getAsString(), token));
+
+		return true;
+	}
+
+}

+ 203 - 185
src/main/java/de/Linus122/TelegramChat/Main.java

@@ -1,185 +1,203 @@
-package de.Linus122.TelegramChat;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.net.URLEncoder;
-import java.text.Format;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-import java.util.UUID;
-
-import org.bukkit.Bukkit;
-import org.bukkit.OfflinePlayer;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.entity.PlayerDeathEvent;
-import org.bukkit.event.player.AsyncPlayerChatEvent;
-import org.bukkit.event.player.PlayerJoinEvent;
-import org.bukkit.event.player.PlayerQuitEvent;
-import org.bukkit.plugin.Plugin;
-import org.bukkit.plugin.java.JavaPlugin;
-
-import com.google.gson.Gson;
-
-import de.Linus122.Metrics.Metrics;
-import de.Linus122.TelegramComponents.Chat;
-import de.Linus122.TelegramComponents.ChatMessageToMc;
-
-
-public class Main extends JavaPlugin implements Listener{
-	public static File datad = new File("plugins/TelegramChat/data.json");
-	public static FileConfiguration cfg;
-	
-	public static Data data = new Data();
-	static Plugin pl;
-	public static Telegram telegramHook;
-	
-	@Override
-	public void onEnable(){
-		this.saveDefaultConfig();
-		cfg = this.getConfig();
-		this.pl = this;
-		Bukkit.getPluginCommand("telegram").setExecutor(new TelegramCmd());
-		Bukkit.getPluginCommand("linktelegram").setExecutor(new LinkTelegramCmd());
-		Bukkit.getPluginManager().registerEvents(this, this);
-		File dir = new File("plugins/TelegramChat/");
-		dir.mkdir();
-		data = new Data();
-		if(datad.exists()){
-			try {
-				FileInputStream fin = new FileInputStream(datad);
-				ObjectInputStream ois = new ObjectInputStream(fin);
-				Gson gson = new Gson();
-				data = (Data) gson.fromJson((String) ois.readObject(), Data.class);
-				ois.close();
-				fin.close();
-			} catch (Exception e) {
-				// TODO Auto-generated catch block
-				e.printStackTrace();
-			}
-		}
-		telegramHook = new Telegram();
-		telegramHook.auth(data.token);
-		
-		Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, new Runnable(){
-			boolean connectionLost = false;
-			public void run(){
-				if(connectionLost){
-					boolean success = telegramHook.reconnect();
-					if(success) connectionLost = false;
-				}
-				if(telegramHook.connected){
-					connectionLost = !telegramHook.getUpdate();
-				}
-			}
-		}, 20L, 20L);
-		new Metrics(this);
-	}
-	public static void save(){
-		Gson gson = new Gson();
-		
-		try {
-			FileOutputStream fout= new FileOutputStream (datad);
-			ObjectOutputStream oos = new ObjectOutputStream(fout);
-			
-			oos.writeObject(gson.toJson(data));
-			fout.close();
-			oos.close();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-	}
-	@Override
-	public void onDisable(){
-		save();
-	}
-	public static void sendToMC(ChatMessageToMc chatMsg) {
-		sendToMC(chatMsg.getUuid_sender(), chatMsg.getContent(), chatMsg.getChatID_sender());
-	}
-	private static void sendToMC(UUID uuid, String msg, int sender){
-		OfflinePlayer op = Bukkit.getOfflinePlayer(uuid);
-		List<Integer> recievers = new ArrayList<Integer>();
-		recievers.addAll(Main.data.ids);
-		recievers.remove((Object) sender);
-		String msgF = Main.cfg.getString("chat-format").replace('&', '§').replace("%player%", op.getName()).replace("%message%", msg);
-		for(int id : recievers){
-			telegramHook.sendMsg(id, msgF);
-		}
-		Bukkit.broadcastMessage(msgF.replace("&", "§"));
-	
-	}
-	public static void link(UUID player, int chatID){
-		Main.data.linkedChats.put(chatID, player);
-		OfflinePlayer p = Bukkit.getOfflinePlayer(player);
-		telegramHook.sendMsg(chatID, "Success! Linked " + p.getName());
-	}
-	public static String generateLinkToken(){
-		Random rnd = new Random();
-		int i = rnd.nextInt(9999999);
-		String s = i + "";
-		String finals = "";
-		for(char m : s.toCharArray()){
-			int m2 = Integer.parseInt(m + "");
-			int rndi = rnd.nextInt(2);
-			if(rndi == 0){
-				m2+=97;
-				char c = (char) m2;
-				finals = finals + c;
-			}else{
-				finals = finals + m;
-			}
-		}
-		return finals;
-	}
-	@EventHandler
-	public void onJoin(PlayerJoinEvent e){
-		if(!this.getConfig().getBoolean("enable-joinquitmessages")) return;
-		if(telegramHook.connected){
-			Chat chat = new Chat();
-			chat.parse_mode = "Markdown";
-			chat.text = "`" + e.getPlayer().getName() + " joined the game.`";
-			telegramHook.sendAll(chat);
-		}
-	}
-	@EventHandler
-	public void onDeath(PlayerDeathEvent e){
-		if(!this.getConfig().getBoolean("enable-deathmessages")) return;
-		if(telegramHook.connected){
-			Chat chat = new Chat();
-			chat.parse_mode = "Markdown";
-			chat.text = "`"+e.getDeathMessage() + "`";
-			telegramHook.sendAll(chat);
-		}
-	}
-	@EventHandler
-	public void onQuit(PlayerQuitEvent e){
-		if(!this.getConfig().getBoolean("enable-joinquitmessages")) return;
-		if(telegramHook.connected){
-			Chat chat = new Chat();
-			chat.parse_mode = "Markdown";
-			chat.text = "`" + e.getPlayer().getName() + " left the game.`";
-			System.out.println(chat.text);
-			telegramHook.sendAll(chat);
-		}
-	}
-	@EventHandler
-	public void onChat(AsyncPlayerChatEvent e){
-		if(!this.getConfig().getBoolean("enable-chatmessages")) return;
-		if(telegramHook.connected){
-			Chat chat = new Chat();
-			chat.parse_mode = "Markdown";
-			chat.text = escape(e.getPlayer().getName()) + ": " + escape(e.getMessage()).replaceAll("§.", "") ;
-			telegramHook.sendAll(chat);
-		}
-	}
-	public String escape(String str){
-		return str.replace("_", "\\_");
-	}
-}
+package de.Linus122.TelegramChat;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.UUID;
+
+import org.bukkit.Bukkit;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.configuration.file.FileConfiguration;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.Listener;
+import org.bukkit.event.entity.PlayerDeathEvent;
+import org.bukkit.event.player.AsyncPlayerChatEvent;
+import org.bukkit.event.player.PlayerJoinEvent;
+import org.bukkit.event.player.PlayerQuitEvent;
+import org.bukkit.plugin.java.JavaPlugin;
+
+import com.google.gson.Gson;
+
+import de.Linus122.Metrics.Metrics;
+import de.Linus122.TelegramComponents.Chat;
+import de.Linus122.TelegramComponents.ChatMessageToMc;
+
+public class Main extends JavaPlugin implements Listener {
+	private static File datad = new File("plugins/TelegramChat/data.json");
+	private static FileConfiguration cfg;
+
+	private static Data data = new Data();
+	public static Telegram telegramHook;
+
+	@Override
+	public void onEnable() {
+		this.saveDefaultConfig();
+		cfg = this.getConfig();
+		Utils.cfg = cfg;
+
+		Bukkit.getPluginCommand("telegram").setExecutor(new TelegramCmd());
+		Bukkit.getPluginCommand("linktelegram").setExecutor(new LinkTelegramCmd());
+		Bukkit.getPluginManager().registerEvents(this, this);
+		File dir = new File("plugins/TelegramChat/");
+		dir.mkdir();
+		data = new Data();
+		if (datad.exists()) {
+			try {
+				FileInputStream fin = new FileInputStream(datad);
+				ObjectInputStream ois = new ObjectInputStream(fin);
+				Gson gson = new Gson();
+				data = (Data) gson.fromJson((String) ois.readObject(), Data.class);
+				ois.close();
+				fin.close();
+			} catch (Exception e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		}
+		telegramHook = new Telegram();
+		telegramHook.auth(data.getToken());
+
+		Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
+			boolean connectionLost = false;
+			if (connectionLost) {
+				boolean success = telegramHook.reconnect();
+				if (success)
+					connectionLost = false;
+			}
+			if (telegramHook.connected) {
+				connectionLost = !telegramHook.getUpdate();
+			}
+		}, 10L, 10L);
+
+		new Metrics(this);
+	}
+
+	@Override
+	public void onDisable() {
+		save();
+	}
+
+	public static void save() {
+		Gson gson = new Gson();
+
+		try {
+			FileOutputStream fout = new FileOutputStream(datad);
+			ObjectOutputStream oos = new ObjectOutputStream(fout);
+
+			oos.writeObject(gson.toJson(data));
+			fout.close();
+			oos.close();
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+	}
+
+	public static Data getBackend() {
+		return data;
+	}
+
+	public static void initBackend() {
+		data = new Data();
+	}
+
+	public static void sendToMC(ChatMessageToMc chatMsg) {
+		sendToMC(chatMsg.getUuid_sender(), chatMsg.getContent(), chatMsg.getChatID_sender());
+	}
+
+	private static void sendToMC(UUID uuid, String msg, int sender) {
+		OfflinePlayer op = Bukkit.getOfflinePlayer(uuid);
+		List<Integer> recievers = new ArrayList<Integer>();
+		recievers.addAll(Main.data.ids);
+		recievers.remove((Object) sender);
+		String msgF = Utils.formatMSG("general-message-to-mc", op.getName(), msg)[0];
+		for (int id : recievers) {
+			telegramHook.sendMsg(id, msgF);
+		}
+		Bukkit.broadcastMessage(msgF.replace("&", "§"));
+
+	}
+
+	public static void link(UUID player, int chatID) {
+		Main.data.addChatPlayerLink(chatID, player);
+		OfflinePlayer p = Bukkit.getOfflinePlayer(player);
+		telegramHook.sendMsg(chatID, "Success! Linked " + p.getName());
+	}
+
+	public static String generateLinkToken() {
+
+		Random rnd = new Random();
+		int i = rnd.nextInt(9999999);
+		String s = i + "";
+		String finals = "";
+		for (char m : s.toCharArray()) {
+			int m2 = Integer.parseInt(m + "");
+			int rndi = rnd.nextInt(2);
+			if (rndi == 0) {
+				m2 += 97;
+				char c = (char) m2;
+				finals = finals + c;
+			} else {
+				finals = finals + m;
+			}
+		}
+		return finals;
+	}
+
+	@EventHandler
+	public void onJoin(PlayerJoinEvent e) {
+		if (!this.getConfig().getBoolean("enable-joinquitmessages"))
+			return;
+		if (telegramHook.connected) {
+			Chat chat = new Chat();
+			chat.parse_mode = "Markdown";
+			chat.text = Utils.formatMSG("join-message", e.getPlayer().getName())[0];
+			telegramHook.sendAll(chat);
+		}
+	}
+
+	@EventHandler
+	public void onDeath(PlayerDeathEvent e) {
+		if (!this.getConfig().getBoolean("enable-deathmessages"))
+			return;
+		if (telegramHook.connected) {
+			Chat chat = new Chat();
+			chat.parse_mode = "Markdown";
+			chat.text = Utils.formatMSG("death-message", e.getDeathMessage())[0];
+			telegramHook.sendAll(chat);
+		}
+	}
+
+	@EventHandler
+	public void onQuit(PlayerQuitEvent e) {
+		if (!this.getConfig().getBoolean("enable-joinquitmessages"))
+			return;
+		if (telegramHook.connected) {
+			Chat chat = new Chat();
+			chat.parse_mode = "Markdown";
+			chat.text = Utils.formatMSG("quit-message", e.getPlayer().getName())[0];
+			telegramHook.sendAll(chat);
+		}
+	}
+
+	@EventHandler
+	public void onChat(AsyncPlayerChatEvent e) {
+		if (!this.getConfig().getBoolean("enable-chatmessages"))
+			return;
+		if (telegramHook.connected) {
+			Chat chat = new Chat();
+			chat.parse_mode = "Markdown";
+			chat.text = Utils
+					.escape(Utils.formatMSG("general-message-to-telegram", e.getPlayer().getName(), e.getMessage())[0])
+					.replaceAll("§.", "");
+			telegramHook.sendAll(chat);
+		}
+	}
+
+}

+ 204 - 210
src/main/java/de/Linus122/TelegramChat/Telegram.java

@@ -1,210 +1,204 @@
-package de.Linus122.TelegramChat;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-import de.Linus122.TelegramComponents.Chat;
-import de.Linus122.TelegramComponents.ChatMessageToMc;
-
-
-public class Telegram {
-	public JsonObject authJson;
-	public boolean connected = false;
-	
-	static int lastUpdate = 0;
-	public String token;
-
-	private List<TelegramActionListener> listeners = new ArrayList<TelegramActionListener>();
-	
-	public void addListener(TelegramActionListener actionListener){
-		listeners.add(actionListener);
-	}
-	
-	public boolean auth(String token){
-		this.token = token;
-		return reconnect();
-	}
-	public boolean reconnect(){
-		try{
-			JsonObject obj = sendGet("https://api.telegram.org/bot" + token + "/getMe");
-			authJson = obj;
-			System.out.print("[Telegram] Established a connection with the telegram servers.");
-			connected = true;
-			return true;
-		}catch(Exception e){
-			connected = false;
-			System.out.print("[Telegram] Sorry, but could not connect to Telegram servers. The token could be wrong.");
-			return false;
-		}
-	}
-	public boolean getUpdate(){
-		JsonObject up = null;
-		try {
-			up = sendGet("https://api.telegram.org/bot" + Main.data.token + "/getUpdates?offset=" + (lastUpdate + 1));
-		} catch (IOException e) {
-			return false;
-		}
-		if(up == null){
-			return false;
-		}
-		if(up.has("result")){
-			for (JsonElement ob : up.getAsJsonArray("result")) {
-				if (ob.isJsonObject()) {
-					JsonObject obj = (JsonObject) ob;
-					if(obj.has("update_id")){
-						lastUpdate = obj.get("update_id").getAsInt();
-					}
-					if (obj.has("message")) {
-						JsonObject chat = obj.getAsJsonObject("message").getAsJsonObject("chat");
-						if(chat.get("type").getAsString().equals("private")){
-							int id = chat.get("id").getAsInt();
-							if(!Main.data.ids.contains(id)) Main.data.ids.add(id);
-							
-							if(obj.getAsJsonObject("message").has("text")){
-								String text = obj.getAsJsonObject("message").get("text").getAsString();
-								for(char c : text.toCharArray()){
-									/*if((int) c == 55357){
-										this.sendMsg(id, "Emoticons are not allowed, sorry!");
-										return true;
-									}*/
-
-								}
-								if(text.length() == 0) return true;
-								if(text.equals("/start")){
-									if(Main.data.firstUse){
-										Main.data.firstUse = false;
-										Chat chat2 = new Chat();
-										chat2.chat_id = id;
-										chat2.parse_mode = "Markdown";
-										chat2.text = "Congratulations, your bot is working! Have fun with this Plugin. Feel free to donate via *PayPal* to keep this project up to date! [PayPal Donation URL](http://donate.spaceio.xyz/)";
-										this.sendMsg(chat2);
-									}
-									this.sendMsg(id, "You can see the chat but you can't chat at the moment. Type */linktelegram ingame* to chat!");
-								}else
-								if(Main.data.linkCodes.containsKey(text)){
-									//LINK
-									Main.link(Main.data.linkCodes.get(text), id);
-									Main.data.linkCodes.remove(text);
-								}else if(Main.data.linkedChats.containsKey(id)){
-									ChatMessageToMc chatMsg = new ChatMessageToMc(Main.data.linkedChats.get(id), text, id);
-									for(TelegramActionListener actionListener : listeners){
-										actionListener.onSendToMinecraft(chatMsg);
-									}
-
-									Main.sendToMC(chatMsg);
-								}else{
-									this.sendMsg(id, "Sorry, please link your account with */linktelegram ingame* to use the chat!");
-								}
-							}
-							
-						}else if(chat.get("type").getAsString().equals("group")){
-							int id = chat.get("id").getAsInt();
-							if(!Main.data.ids.contains(id))
-								Main.data.ids.add(id);
-						}
-					}
-					
-				}
-			}	
-		}
-		return true;
-	}
-	
-	public void sendMsg(int id, String msg){
-		Chat chat = new Chat();
-		chat.chat_id = id;
-		chat.text = msg;
-		sendMsg(chat);
-	}
-	public void sendMsg(Chat chat){
-		for(TelegramActionListener actionListener : listeners){
-			actionListener.onSendToTelegram(chat);
-		}
-		Gson gson = new Gson();
-
-		post("sendMessage", gson.toJson(chat, Chat.class));
-		
-	}
-	public void sendAll(final Chat chat){
-		new Thread(new Runnable(){
-			public void run(){
-				Gson gson = new Gson();
-				for(int id : Main.data.ids){
-					chat.chat_id = id;
-					//post("sendMessage", gson.toJson(chat, Chat.class));
-					sendMsg(chat);
-				}
-			}
-		}).start();
-	}
-	public void post(String method, String json){
-		try {
-			String body = json;
-			URL url = new URL("https://api.telegram.org/bot" + Main.data.token + "/" + method);
-			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
-			connection.setRequestMethod("POST");
-			connection.setDoInput(true);
-			connection.setDoOutput(true);
-			connection.setUseCaches(false);
-			connection.setRequestProperty("Content-Type", "application/json; ; Charset=UTF-8");
-			connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
-
-			
-			DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
-			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
-			writer.write(body);
-			writer.close();
-			wr.close();
-			
-			//OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
-			//writer.write(body);
-			//writer.flush();
-
-			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
-
-			for (String line; (line = reader.readLine()) != null;) {
-				
-			}
-
-			writer.close();
-			reader.close();
-		} catch (Exception e) {
-			reconnect();
-			System.out.print("[Telegram] Disconnected from Telegram, reconnect...");
-		}
-		
-	}
-
-	public JsonObject sendGet(String url) throws IOException {
-		String a = url;
-		URL url2 = new URL(a);
-		URLConnection conn = url2.openConnection();
-
-		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
-
-		String all = "";
-		String inputLine;
-		while ((inputLine = br.readLine()) != null) {
-			all += inputLine;
-		}
-
-		br.close();
-		JsonParser parser = new JsonParser();
-		return parser.parse(all).getAsJsonObject();
-
-	}
-}
+package de.Linus122.TelegramChat;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+import de.Linus122.TelegramComponents.Chat;
+import de.Linus122.TelegramComponents.ChatMessageToMc;
+
+public class Telegram {
+	public JsonObject authJson;
+	public boolean connected = false;
+
+	static int lastUpdate = 0;
+	public String token;
+
+	private List<TelegramActionListener> listeners = new ArrayList<TelegramActionListener>();
+
+	private final String API_URL_GETME = "https://api.telegram.org/bot%s/getMe";
+	private final String API_URL_GETUPDATES = "https://api.telegram.org/bot%s/getUpdates?offset=%d";
+	private final String API_URL_GENERAL = "https://api.telegram.org/bot%s/%s";
+
+	public void addListener(TelegramActionListener actionListener) {
+		listeners.add(actionListener);
+	}
+
+	public boolean auth(String token) {
+		this.token = token;
+		return reconnect();
+	}
+
+	public boolean reconnect() {
+		try {
+			JsonObject obj = sendGet(String.format(API_URL_GETME, token));
+			authJson = obj;
+			System.out.print("[Telegram] Established a connection with the telegram servers.");
+			connected = true;
+			return true;
+		} catch (Exception e) {
+			connected = false;
+			System.out.print("[Telegram] Sorry, but could not connect to Telegram servers. The token could be wrong.");
+			return false;
+		}
+	}
+
+	public boolean getUpdate() {
+		JsonObject up = null;
+		try {
+			up = sendGet(String.format(API_URL_GETUPDATES, Main.getBackend().getToken(), lastUpdate + 1));
+		} catch (IOException e) {
+			return false;
+		}
+		if (up == null) {
+			return false;
+		}
+		if (up.has("result")) {
+			for (JsonElement ob : up.getAsJsonArray("result")) {
+				if (ob.isJsonObject()) {
+					JsonObject obj = (JsonObject) ob;
+					if (obj.has("update_id")) {
+						lastUpdate = obj.get("update_id").getAsInt();
+					}
+					if (obj.has("message")) {
+						JsonObject chat = obj.getAsJsonObject("message").getAsJsonObject("chat");
+						if (chat.get("type").getAsString().equals("private")) {
+							int id = chat.get("id").getAsInt();
+							if (!Main.getBackend().ids.contains(id))
+								Main.getBackend().ids.add(id);
+
+							if (obj.getAsJsonObject("message").has("text")) {
+								String text = obj.getAsJsonObject("message").get("text").getAsString();
+								if (text.length() == 0)
+									return true;
+								if (text.equals("/start")) {
+									if (Main.getBackend().isFirstUse()) {
+										Main.getBackend().setFirstUse(false);
+										Chat chat2 = new Chat();
+										chat2.chat_id = id;
+										chat2.parse_mode = "Markdown";
+										chat2.text = Utils.formatMSG("setup-msg")[0];
+										this.sendMsg(chat2);
+									}
+									this.sendMsg(id, Utils.formatMSG("can-see-but-not-chat")[0]);
+								} else if (Main.getBackend().getLinkCodes().containsKey(text)) {
+									// LINK
+									Main.link(Main.getBackend().getUUIDFromLinkCode(text), id);
+									Main.getBackend().removeLinkCode(text);
+								} else if (Main.getBackend().getLinkedChats().containsKey(id)) {
+									ChatMessageToMc chatMsg = new ChatMessageToMc(
+											Main.getBackend().getUUIDFromChatID(id), text, id);
+									for (TelegramActionListener actionListener : listeners) {
+										actionListener.onSendToMinecraft(chatMsg);
+									}
+
+									Main.sendToMC(chatMsg);
+								} else {
+									this.sendMsg(id, Utils.formatMSG("need-to-link")[0]);
+								}
+							}
+
+						} else if (chat.get("type").getAsString().equals("group")) {
+							int id = chat.get("id").getAsInt();
+							if (!Main.getBackend().ids.contains(id))
+								Main.getBackend().ids.add(id);
+						}
+					}
+
+				}
+			}
+		}
+		return true;
+	}
+
+	public void sendMsg(int id, String msg) {
+		Chat chat = new Chat();
+		chat.chat_id = id;
+		chat.text = msg;
+		sendMsg(chat);
+	}
+
+	public void sendMsg(Chat chat) {
+		for (TelegramActionListener actionListener : listeners) {
+			actionListener.onSendToTelegram(chat);
+		}
+		Gson gson = new Gson();
+
+		post("sendMessage", gson.toJson(chat, Chat.class));
+
+	}
+
+	public void sendAll(final Chat chat) {
+		new Thread(new Runnable() {
+			public void run() {
+				for (int id : Main.getBackend().ids) {
+					chat.chat_id = id;
+					// post("sendMessage", gson.toJson(chat, Chat.class));
+					sendMsg(chat);
+				}
+			}
+		}).start();
+	}
+
+	public void post(String method, String json) {
+		try {
+			String body = json;
+			URL url = new URL(String.format(API_URL_GENERAL, Main.getBackend().getToken(), method));
+			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+			connection.setRequestMethod("POST");
+			connection.setDoInput(true);
+			connection.setDoOutput(true);
+			connection.setUseCaches(false);
+			connection.setRequestProperty("Content-Type", "application/json; ; Charset=UTF-8");
+			connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
+
+			DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
+			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
+			writer.write(body);
+			writer.close();
+			wr.close();
+
+			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+
+			writer.close();
+			reader.close();
+		} catch (Exception e) {
+			reconnect();
+			System.out.print("[Telegram] Disconnected from Telegram, reconnect...");
+		}
+
+	}
+
+	public JsonObject sendGet(String url) throws IOException {
+		String a = url;
+		URL url2 = new URL(a);
+		URLConnection conn = url2.openConnection();
+
+		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+
+		String all = "";
+		String inputLine;
+		while ((inputLine = br.readLine()) != null) {
+			all += inputLine;
+		}
+
+		br.close();
+		JsonParser parser = new JsonParser();
+		return parser.parse(all).getAsJsonObject();
+
+	}
+
+}

+ 1 - 0
src/main/java/de/Linus122/TelegramChat/TelegramActionListener.java

@@ -5,5 +5,6 @@ import de.Linus122.TelegramComponents.ChatMessageToMc;
 
 public interface TelegramActionListener {
 	public void onSendToTelegram(Chat chat);
+
 	public void onSendToMinecraft(ChatMessageToMc chatMsg);
 }

+ 37 - 36
src/main/java/de/Linus122/TelegramChat/TelegramCmd.java

@@ -1,36 +1,37 @@
-package de.Linus122.TelegramChat;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-
-public class TelegramCmd implements CommandExecutor {
-
-	@Override
-	public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] args) {
-		if(!cs.hasPermission("telegram.settoken")){
-			cs.sendMessage("§cYou don't have permissions to use this!");
-			return true;
-		}
-		if(args.length == 0){
-			cs.sendMessage("§c/telegram [token]");
-			return true;
-		}
-		if(Main.data == null){
-			Main.data = new Data();
-		}
-		Main.data.token = args[0];
-		Main.save();
-		boolean success = false;
-	
-		success = Main.telegramHook.auth(Main.data.token);
-		if(success){
-			cs.sendMessage("§cSuccessfully connected to Telegram!");
-			cs.sendMessage("§aAdd " + Main.telegramHook.authJson.getAsJsonObject("result").get("username").getAsString() + " to Telegram!");
-		}else{
-			cs.sendMessage("§cWrong token. Paste in the whole token!");
-		}
-		return true;
-	}
-
-}
+package de.Linus122.TelegramChat;
+
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandExecutor;
+import org.bukkit.command.CommandSender;
+
+public class TelegramCmd implements CommandExecutor {
+
+	@Override
+	public boolean onCommand(CommandSender cs, Command arg1, String arg2, String[] args) {
+		if (!cs.hasPermission("telegram.settoken")) {
+			cs.sendMessage("§cYou don't have permissions to use this!");
+			return true;
+		}
+		if (args.length == 0) {
+			cs.sendMessage("§c/telegram [token]");
+			return true;
+		}
+		if (Main.getBackend() == null) {
+			Main.initBackend();
+		}
+		Main.getBackend().setToken(args[0]);
+		Main.save();
+		boolean success = false;
+
+		success = Main.telegramHook.auth(Main.getBackend().getToken());
+		if (success) {
+			cs.sendMessage("§cSuccessfully connected to Telegram!");
+			cs.sendMessage("§aAdd " + Main.telegramHook.authJson.getAsJsonObject("result").get("username").getAsString()
+					+ " to Telegram!");
+		} else {
+			cs.sendMessage("§cWrong token. Paste in the whole token!");
+		}
+		return true;
+	}
+
+}

+ 31 - 0
src/main/java/de/Linus122/TelegramChat/Utils.java

@@ -0,0 +1,31 @@
+package de.Linus122.TelegramChat;
+
+import org.bukkit.configuration.file.FileConfiguration;
+
+public class Utils {
+	public static String escape(String str) {
+		return str.replace("_", "\\_");
+	}
+
+	public static FileConfiguration cfg;
+
+	final static String MESSAGE_SECTION = "messages";
+
+	public static String[] formatMSG(String suffixKey) {
+		return formatMSG(suffixKey, "");
+	}
+
+	public static String[] formatMSG(String suffixKey, Object... args) {
+		String key = MESSAGE_SECTION + "." + suffixKey;
+		if (!cfg.contains(key))
+			return new String[] {
+					"Message not found in config.yml. Please check your config if the following key is present:", key };
+		String rawMessage = cfg.getString(key);
+		if (args != null && args.length > 0)
+			rawMessage = String.format(rawMessage, args);
+		rawMessage = rawMessage.replace("&", "§");
+
+		return rawMessage.split("\\n");
+
+	}
+}

+ 19 - 4
src/main/resources/config.yml

@@ -1,4 +1,19 @@
-chat-format: '&c[Telegram]&r %player%: %message%'
-enable-joinquitmessages: true
-enable-deathmessages: true
-enable-chatmessages: true
+messages:
+  # telegram messages
+  general-message-to-mc: "&c[Telegram]&r %s: %s"
+  join-message: "`%s joined the game.`"
+  quit-message: "`%s left the game.`"
+  death-message: "`%s`"
+  need-to-link: "Sorry, please link your account with */linktelegram ingame* to use the chat!"
+  can-see-but-not-chat: "You can see the chat but you can't chat at the moment. Type */linktelegram ingame* to chat!"
+  success-linked: "Success! Linked %s"
+  setup-msg: "Congratulations, your bot is working! Have fun with this Plugin. Feel free to donate via *PayPal* to keep this project up to date! [PayPal Donation URL](http://donate.spaceio.xyz/)"
+  # minecraft message:
+  general-message-to-telegram: "%s: %s"
+  no-permissions: "&cYou don't have permissions to use this!"
+  cant-link-console: "&cSorry, but you can't link the console currently."
+  need-to-add-bot-first: "&cPlease add a bot to your server first! /telegram"
+  get-token: "&aAdd %s to Telegram and send this message to %s: \n%s"
+enable-joinquitmessages: true
+enable-deathmessages: true
+enable-chatmessages: true