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

This commit is contained in:
mastercake10 2018-03-03 19:15:16 +01:00
parent a033eb0bd0
commit 7bbcf58caa
11 changed files with 637 additions and 510 deletions

View File

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

View File

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

View File

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

View File

@ -1,16 +1,77 @@
package de.Linus122.TelegramChat; package de.Linus122.TelegramChat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
public class Data { public class Data {
public String token = ""; private String token = "";
//Player name // ChatID // Player name // ChatID
public HashMap<Integer, UUID> linkedChats = new HashMap<Integer, UUID>(); private HashMap<Integer, UUID> linkedChats = new HashMap<Integer, UUID>();
//Player name // RandomInt // Player name // RandomInt
public HashMap<String, UUID> linkCodes = new HashMap<String, UUID>(); private HashMap<String, UUID> linkCodes = new HashMap<String, UUID>();
public List<Integer> ids = new ArrayList<Integer>(); public List<Integer> ids = new ArrayList<Integer>();
boolean firstUse = true; 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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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");
}
}

View File

@ -1,4 +1,19 @@
chat-format: '&c[Telegram]&r %player%: %message%' messages:
enable-joinquitmessages: true # telegram messages
enable-deathmessages: true general-message-to-mc: "&c[Telegram]&r %s: %s"
enable-chatmessages: true 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