commit cb191b2a289d606855e2af84633f9889fca94464 Author: Linus Date: Mon Nov 7 23:07:01 2016 +0100 first commit diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..c9bca31 --- /dev/null +++ b/config.yml @@ -0,0 +1,3 @@ +chat-format: '&c[Telegram]&r %player%: %message%' +enable-joinquitmessages: true +enable-deathmessages: true \ No newline at end of file diff --git a/de/Linus122/TelegramChat/Data.java b/de/Linus122/TelegramChat/Data.java new file mode 100644 index 0000000..a4c4951 --- /dev/null +++ b/de/Linus122/TelegramChat/Data.java @@ -0,0 +1,16 @@ +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 linkedChats = new HashMap(); + //Player name // RandomInt + public HashMap linkCodes = new HashMap(); + public static List ids = new ArrayList(); + boolean firstUse = true; +} diff --git a/de/Linus122/TelegramChat/LinkTelegramCmd.java b/de/Linus122/TelegramChat/LinkTelegramCmd.java new file mode 100644 index 0000000..387ee7d --- /dev/null +++ b/de/Linus122/TelegramChat/LinkTelegramCmd.java @@ -0,0 +1,37 @@ +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(Telegram.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 " + Telegram.authJson.getAsJsonObject("result").get("username").getAsString() + " to Telegram and send this message to " + Telegram.authJson.getAsJsonObject("result").get("username").getAsString() + ":"); + cs.sendMessage("§c" + token); + + return true; + } + +} diff --git a/de/Linus122/TelegramChat/Main.java b/de/Linus122/TelegramChat/Main.java new file mode 100644 index 0000000..cda8c3f --- /dev/null +++ b/de/Linus122/TelegramChat/Main.java @@ -0,0 +1,163 @@ +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.TelegramComponents.Chat; + + +public class Main extends JavaPlugin implements Listener{ + File datad = new File("plugins/TelegramChat/data.json"); + public static FileConfiguration cfg; + + public static Data data = new Data(); + static Plugin pl; + @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(); + } + } + Telegram.auth(); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ + public void run(){ + if(Telegram.connected){ + Telegram.getupdate(); + } + } + }, 20L, 20L); + } + @Override + public void onDisable(){ + 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 void sendToMC(UUID uuid, String msg, int sender){ + OfflinePlayer op = Bukkit.getOfflinePlayer(uuid); + List recievers = new ArrayList(); + 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){ + Telegram.sendMsg(id, msgF); + } + Bukkit.broadcastMessage(msgF); + + } + public static void link(UUID player, int chatID){ + Main.data.linkedChats.put(chatID, player); + OfflinePlayer p = Bukkit.getOfflinePlayer(player); + Telegram.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(Telegram.connected){ + Chat chat = new Chat(); + chat.parse_mode = "Markdown"; + chat.text = "`" + e.getPlayer().getName() + " joined the game.`"; + Telegram.sendAll(chat); + } + } + @EventHandler + public void onDeath(PlayerDeathEvent e){ + if(!this.getConfig().getBoolean("enable-deathmessages")) return; + if(Telegram.connected){ + Chat chat = new Chat(); + chat.parse_mode = "Markdown"; + chat.text = "`"+e.getDeathMessage() + "`"; + Telegram.sendAll(chat); + } + } + @EventHandler + public void onQuit(PlayerQuitEvent e){ + if(!this.getConfig().getBoolean("enable-joinquitmessages")) return; + if(Telegram.connected){ + Chat chat = new Chat(); + chat.parse_mode = "Markdown"; + chat.text = "`" + e.getPlayer().getName() + " left the game.`"; + System.out.println(chat.text); + Telegram.sendAll(chat); + } + } + @EventHandler + public void onChat(AsyncPlayerChatEvent e){ + if(Telegram.connected){ + Chat chat = new Chat(); + chat.parse_mode = "Markdown"; + chat.text = e.getPlayer().getName() + ": _" + e.getMessage() + "_"; + Telegram.sendAll(chat); + } + } +} diff --git a/de/Linus122/TelegramChat/Telegram.java b/de/Linus122/TelegramChat/Telegram.java new file mode 100644 index 0000000..cf4991f --- /dev/null +++ b/de/Linus122/TelegramChat/Telegram.java @@ -0,0 +1,189 @@ +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 com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import de.Linus122.TelegramComponents.Chat; + + +public class Telegram { + public static JsonObject authJson; + public static boolean connected = false; + + + static int lastUpdate = 0; + public static boolean auth(){ + try{ + JsonObject obj = sendGet("https://api.telegram.org/bot" + Main.data.token + "/getMe"); + authJson = obj; + 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 static void getupdate(){ + + JsonObject up = null; + try { + + up = sendGet("https://api.telegram.org/bot" + Main.data.token + "/getUpdates?offset=" + (lastUpdate + 1)); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if(up == null){ + auth(); + } + 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){ + Telegram.sendMsg(id, "Emoticons are not allowed, sorry!"); + return; + } + } + if(text.length() == 0) return; + 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 me if you like TelegramChat! [PayPal Donation URL](https://goo.gl/I02XGH)"; + Telegram.sendMsg(chat2); + } + Telegram.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)){ + Main.sendToMC(Main.data.linkedChats.get(id), text, id); + }else{ + Telegram.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); + } + } + + } + } + } + } + + public static void sendMsg(int id, String msg){ + Gson gson = new Gson(); + Chat chat = new Chat(); + chat.chat_id = id; + chat.text = msg; + post("sendMessage", gson.toJson(chat, Chat.class)); + + } + public static void sendMsg(Chat chat){ + Gson gson = new Gson(); + post("sendMessage", gson.toJson(chat, Chat.class)); + + } + public static 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)); + } + } + }).start(); + } + public static 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) { + auth(); + System.out.print("[Telegram] Disconnected from Telegram, reconnect..."); + } + + } + + public static 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(); + + } +} diff --git a/de/Linus122/TelegramChat/TelegramCmd.java b/de/Linus122/TelegramChat/TelegramCmd.java new file mode 100644 index 0000000..99cb026 --- /dev/null +++ b/de/Linus122/TelegramChat/TelegramCmd.java @@ -0,0 +1,35 @@ +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]; + boolean success = false; + + success = Telegram.auth(); + if(success){ + cs.sendMessage("§cSuccessfully connected to Telegram!"); + cs.sendMessage("§aAdd " + Telegram.authJson.getAsJsonObject("result").get("username").getAsString() + " to Telegram!"); + }else{ + cs.sendMessage("§cWrong token. Paste in the whole token!"); + } + return true; + } + +} diff --git a/de/Linus122/TelegramComponents/Chat.java b/de/Linus122/TelegramComponents/Chat.java new file mode 100644 index 0000000..d30e39e --- /dev/null +++ b/de/Linus122/TelegramComponents/Chat.java @@ -0,0 +1,7 @@ +package de.Linus122.TelegramComponents; + +public class Chat { + public String text; + public int chat_id; + public String parse_mode; +} diff --git a/plugin.yml b/plugin.yml new file mode 100644 index 0000000..e0f507b --- /dev/null +++ b/plugin.yml @@ -0,0 +1,14 @@ +name: TelegramChat +main: de.Linus122.TelegramChat.Main +version: 1.0 +authors: [Linus122] +description: Brings minecraft chat to Telegram! +commands: + telegram: + description: Main command + usage: / [token] + permission: telegram.settoken + linktelegram: + description: Main command + usage: / + permission: telegram.linktelegram \ No newline at end of file