Telegram.java 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package de.Linus122.Telegram;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStreamWriter;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import com.google.gson.Gson;
  14. import com.google.gson.JsonElement;
  15. import com.google.gson.JsonObject;
  16. import com.google.gson.JsonParser;
  17. import de.Linus122.TelegramComponents.ChatMessageToTelegram;
  18. import de.Linus122.TelegramChat.TelegramChat;
  19. import de.Linus122.TelegramComponents.Chat;
  20. import de.Linus122.TelegramComponents.ChatMessageToMc;
  21. import de.Linus122.TelegramComponents.Update;
  22. public class Telegram {
  23. public JsonObject authJson;
  24. public boolean connected = false;
  25. static int lastUpdate = 0;
  26. public String token;
  27. private List<TelegramActionListener> listeners = new ArrayList<TelegramActionListener>();
  28. private final String API_URL_GETME = "https://api.telegram.org/bot%s/getMe";
  29. private final String API_URL_GETUPDATES = "https://api.telegram.org/bot%s/getUpdates?offset=%d";
  30. private final String API_URL_GENERAL = "https://api.telegram.org/bot%s/%s";
  31. private Gson gson = new Gson();
  32. public void addListener(TelegramActionListener actionListener) {
  33. listeners.add(actionListener);
  34. }
  35. public boolean auth(String token) {
  36. this.token = token;
  37. return reconnect();
  38. }
  39. public boolean reconnect() {
  40. try {
  41. JsonObject obj = sendGet(String.format(API_URL_GETME, token));
  42. authJson = obj;
  43. System.out.print("[Telegram] Established a connection with the telegram servers.");
  44. connected = true;
  45. return true;
  46. } catch (Exception e) {
  47. connected = false;
  48. System.out.print("[Telegram] Sorry, but could not connect to Telegram servers. The token could be wrong.");
  49. return false;
  50. }
  51. }
  52. public boolean getUpdate() {
  53. JsonObject up = null;
  54. try {
  55. up = sendGet(String.format(API_URL_GETUPDATES, TelegramChat.getBackend().getToken(), lastUpdate + 1));
  56. } catch (IOException e) {
  57. return false;
  58. }
  59. if (up == null) {
  60. return false;
  61. }
  62. if (up.has("result")) {
  63. for (JsonElement ob : up.getAsJsonArray("result")) {
  64. if (ob.isJsonObject()) {
  65. Update update = gson.fromJson(ob, Update.class);
  66. if(lastUpdate == update.getUpdate_id()) return true;
  67. lastUpdate = update.getUpdate_id();
  68. if (update.getMessage() != null) {
  69. Chat chat = update.getMessage().getChat();
  70. if (chat.isPrivate()) {
  71. // private chat
  72. if (!TelegramChat.getBackend().chat_ids.contains(chat.getId()))
  73. TelegramChat.getBackend().chat_ids.add(chat.getId());
  74. if (update.getMessage().getText() != null) {
  75. String text = update.getMessage().getText();
  76. if (text.length() == 0)
  77. return true;
  78. if (text.equals("/start")) {
  79. if (TelegramChat.getBackend().isFirstUse()) {
  80. TelegramChat.getBackend().setFirstUse(false);
  81. ChatMessageToTelegram chat2 = new ChatMessageToTelegram();
  82. chat2.chat_id = chat.getId();
  83. chat2.parse_mode = "Markdown";
  84. chat2.text = Utils.formatMSG("setup-msg")[0];
  85. this.sendMsg(chat2);
  86. }
  87. this.sendMsg(chat.getId(), Utils.formatMSG("can-see-but-not-chat")[0]);
  88. } else {
  89. handleUserMessage(text, update);
  90. }
  91. }
  92. } else if (!chat.isPrivate()) {
  93. // group chat
  94. int id = chat.getId();
  95. if (!TelegramChat.getBackend().chat_ids.contains(id))
  96. TelegramChat.getBackend().chat_ids.add(id);
  97. if (update.getMessage().getText() != null) {
  98. String text = update.getMessage().getText();
  99. handleUserMessage(text, update);
  100. }
  101. }
  102. }
  103. }
  104. }
  105. }
  106. return true;
  107. }
  108. public void handleUserMessage(String text, Update update) {
  109. Chat chat = update.getMessage().getChat();
  110. int user_id = update.getMessage().getFrom().getId();
  111. if (TelegramChat.getBackend().getLinkCodes().containsKey(text)) {
  112. // LINK
  113. TelegramChat.link(TelegramChat.getBackend().getUUIDFromLinkCode(text), user_id);
  114. TelegramChat.getBackend().removeLinkCode(text);
  115. } else if (TelegramChat.getBackend().getLinkedChats().containsKey(user_id)) {
  116. ChatMessageToMc chatMsg = new ChatMessageToMc(
  117. TelegramChat.getBackend().getUUIDFromUserID(user_id), text, chat.getId());
  118. for (TelegramActionListener actionListener : listeners) {
  119. actionListener.onSendToMinecraft(chatMsg);
  120. }
  121. if(!chatMsg.isCancelled()){
  122. TelegramChat.sendToMC(chatMsg);
  123. }
  124. } else {
  125. this.sendMsg(chat.getId(), Utils.formatMSG("need-to-link")[0]);
  126. }
  127. }
  128. public void sendMsg(int id, String msg) {
  129. ChatMessageToTelegram chat = new ChatMessageToTelegram();
  130. chat.chat_id = id;
  131. chat.text = msg;
  132. sendMsg(chat);
  133. }
  134. public void sendMsg(ChatMessageToTelegram chat) {
  135. for (TelegramActionListener actionListener : listeners) {
  136. actionListener.onSendToTelegram(chat);
  137. }
  138. Gson gson = new Gson();
  139. if(!chat.isCancelled()){
  140. post("sendMessage", gson.toJson(chat, ChatMessageToTelegram.class));
  141. }
  142. }
  143. public void sendAll(final ChatMessageToTelegram chat) {
  144. new Thread(new Runnable() {
  145. public void run() {
  146. for (int id : TelegramChat.getBackend().chat_ids) {
  147. chat.chat_id = id;
  148. // post("sendMessage", gson.toJson(chat, Chat.class));
  149. sendMsg(chat);
  150. }
  151. }
  152. }).start();
  153. }
  154. public void post(String method, String json) {
  155. try {
  156. String body = json;
  157. URL url = new URL(String.format(API_URL_GENERAL, TelegramChat.getBackend().getToken(), method));
  158. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  159. connection.setRequestMethod("POST");
  160. connection.setDoInput(true);
  161. connection.setDoOutput(true);
  162. connection.setUseCaches(false);
  163. connection.setRequestProperty("Content-Type", "application/json; ; Charset=UTF-8");
  164. connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
  165. DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
  166. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
  167. writer.write(body);
  168. writer.close();
  169. wr.close();
  170. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  171. writer.close();
  172. reader.close();
  173. } catch (Exception e) {
  174. reconnect();
  175. System.out.print("[Telegram] Disconnected from Telegram, reconnect...");
  176. }
  177. }
  178. public JsonObject sendGet(String url) throws IOException {
  179. String a = url;
  180. URL url2 = new URL(a);
  181. URLConnection conn = url2.openConnection();
  182. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  183. String all = "";
  184. String inputLine;
  185. while ((inputLine = br.readLine()) != null) {
  186. all += inputLine;
  187. }
  188. br.close();
  189. JsonParser parser = new JsonParser();
  190. return parser.parse(all).getAsJsonObject();
  191. }
  192. }