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

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

@@ -6,11 +6,72 @@ 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

@@ -11,25 +11,26 @@ 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

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

View File

@@ -20,7 +20,6 @@ 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;
@@ -30,91 +29,92 @@ public class Telegram {
private List<TelegramActionListener> listeners = new ArrayList<TelegramActionListener>(); private List<TelegramActionListener> listeners = new ArrayList<TelegramActionListener>();
public void addListener(TelegramActionListener actionListener){ 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); listeners.add(actionListener);
} }
public boolean auth(String token){ public boolean auth(String token) {
this.token = token; this.token = token;
return reconnect(); return reconnect();
} }
public boolean reconnect(){
try{ public boolean reconnect() {
JsonObject obj = sendGet("https://api.telegram.org/bot" + token + "/getMe"); try {
JsonObject obj = sendGet(String.format(API_URL_GETME, token));
authJson = obj; authJson = obj;
System.out.print("[Telegram] Established a connection with the telegram servers."); System.out.print("[Telegram] Established a connection with the telegram servers.");
connected = true; connected = true;
return true; return true;
}catch(Exception e){ } catch (Exception e) {
connected = false; connected = false;
System.out.print("[Telegram] Sorry, but could not connect to Telegram servers. The token could be wrong."); System.out.print("[Telegram] Sorry, but could not connect to Telegram servers. The token could be wrong.");
return false; return false;
} }
} }
public boolean getUpdate(){
public boolean getUpdate() {
JsonObject up = null; JsonObject up = null;
try { try {
up = sendGet("https://api.telegram.org/bot" + Main.data.token + "/getUpdates?offset=" + (lastUpdate + 1)); up = sendGet(String.format(API_URL_GETUPDATES, Main.getBackend().getToken(), lastUpdate + 1));
} catch (IOException e) { } catch (IOException e) {
return false; return false;
} }
if(up == null){ if (up == null) {
return false; return false;
} }
if(up.has("result")){ if (up.has("result")) {
for (JsonElement ob : up.getAsJsonArray("result")) { for (JsonElement ob : up.getAsJsonArray("result")) {
if (ob.isJsonObject()) { if (ob.isJsonObject()) {
JsonObject obj = (JsonObject) ob; JsonObject obj = (JsonObject) ob;
if(obj.has("update_id")){ if (obj.has("update_id")) {
lastUpdate = obj.get("update_id").getAsInt(); lastUpdate = obj.get("update_id").getAsInt();
} }
if (obj.has("message")) { if (obj.has("message")) {
JsonObject chat = obj.getAsJsonObject("message").getAsJsonObject("chat"); JsonObject chat = obj.getAsJsonObject("message").getAsJsonObject("chat");
if(chat.get("type").getAsString().equals("private")){ if (chat.get("type").getAsString().equals("private")) {
int id = chat.get("id").getAsInt(); int id = chat.get("id").getAsInt();
if(!Main.data.ids.contains(id)) Main.data.ids.add(id); if (!Main.getBackend().ids.contains(id))
Main.getBackend().ids.add(id);
if(obj.getAsJsonObject("message").has("text")){ if (obj.getAsJsonObject("message").has("text")) {
String text = obj.getAsJsonObject("message").get("text").getAsString(); String text = obj.getAsJsonObject("message").get("text").getAsString();
for(char c : text.toCharArray()){ if (text.length() == 0)
/*if((int) c == 55357){ return true;
this.sendMsg(id, "Emoticons are not allowed, sorry!"); if (text.equals("/start")) {
return true; if (Main.getBackend().isFirstUse()) {
}*/ Main.getBackend().setFirstUse(false);
}
if(text.length() == 0) return true;
if(text.equals("/start")){
if(Main.data.firstUse){
Main.data.firstUse = 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);
} }
} }
@@ -124,14 +124,15 @@ public class Telegram {
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) {
for (TelegramActionListener actionListener : listeners) {
actionListener.onSendToTelegram(chat); actionListener.onSendToTelegram(chat);
} }
Gson gson = new Gson(); Gson gson = new Gson();
@@ -139,22 +140,23 @@ public class Telegram {
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 sendAll(final Chat chat) {
public void run(){ new Thread(new Runnable() {
Gson gson = new Gson(); public void run() {
for(int id : Main.data.ids){ for (int id : Main.getBackend().ids) {
chat.chat_id = id; chat.chat_id = id;
//post("sendMessage", gson.toJson(chat, Chat.class)); // post("sendMessage", gson.toJson(chat, Chat.class));
sendMsg(chat); sendMsg(chat);
} }
} }
}).start(); }).start();
} }
public void post(String method, String json){
public void post(String method, String json) {
try { try {
String body = json; String body = json;
URL url = new URL("https://api.telegram.org/bot" + Main.data.token + "/" + method); URL url = new URL(String.format(API_URL_GENERAL, Main.getBackend().getToken(), method));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setDoInput(true); connection.setDoInput(true);
@@ -163,23 +165,14 @@ public class Telegram {
connection.setRequestProperty("Content-Type", "application/json; ; Charset=UTF-8"); connection.setRequestProperty("Content-Type", "application/json; ; Charset=UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(body.length())); connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8")); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(body); writer.write(body);
writer.close(); writer.close();
wr.close(); wr.close();
//OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
//writer.write(body);
//writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line; (line = reader.readLine()) != null;) {
}
writer.close(); writer.close();
reader.close(); reader.close();
} catch (Exception e) { } catch (Exception e) {
@@ -207,4 +200,5 @@ public class Telegram {
return parser.parse(all).getAsJsonObject(); 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

@@ -8,26 +8,27 @@ 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!");
} else {
cs.sendMessage("§cWrong token. Paste in the whole token!"); 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:
# 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-joinquitmessages: true
enable-deathmessages: true enable-deathmessages: true
enable-chatmessages: true enable-chatmessages: true