1
1
mirror of https://github.com/ahabhyde/miguelbridge synced 2025-01-10 14:34:21 +01:00

Supporto a multi stanze

Per ora configurabili solamente manualmente. Il bot prova a joinare tutte le stanze salvate nel json all'avvio
This commit is contained in:
Ahab 2018-04-09 19:53:14 +02:00
parent f5e4f582f8
commit 6c65ae8bdb
7 changed files with 168 additions and 147 deletions

BIN
lib/GSON.jar Normal file

Binary file not shown.

View File

@ -29,6 +29,7 @@ dist.jar=${dist.dir}/MiguelBridge.jar
dist.javadoc.dir=${dist.dir}/javadoc dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath= endorsed.classpath=
excludes= excludes=
file.reference.GSON.jar=lib\\GSON.jar
file.reference.httpclient-4.5.5.jar=lib\\httpclient-4.5.5.jar file.reference.httpclient-4.5.5.jar=lib\\httpclient-4.5.5.jar
file.reference.json-simple-1.1.1.jar=lib\\json-simple-1.1.1.jar file.reference.json-simple-1.1.1.jar=lib\\json-simple-1.1.1.jar
file.reference.telegrambots-3.0-jar-with-dependencies.jar=lib\\telegrambots-3.0-jar-with-dependencies.jar file.reference.telegrambots-3.0-jar-with-dependencies.jar=lib\\telegrambots-3.0-jar-with-dependencies.jar
@ -37,7 +38,8 @@ jar.compress=false
javac.classpath=\ javac.classpath=\
${file.reference.json-simple-1.1.1.jar}:\ ${file.reference.json-simple-1.1.1.jar}:\
${file.reference.telegrambots-3.0-jar-with-dependencies.jar}:\ ${file.reference.telegrambots-3.0-jar-with-dependencies.jar}:\
${file.reference.httpclient-4.5.5.jar} ${file.reference.httpclient-4.5.5.jar}:\
${file.reference.GSON.jar}
# Space-separated list of extra javac options # Space-separated list of extra javac options
javac.compilerargs= javac.compilerargs=
javac.deprecation=false javac.deprecation=false

View File

@ -1,14 +1,15 @@
{ {
"matrixuser": "Matrix user name", "rooms": [
"tgtoken": "Token key given from BotFather", {
"matrixpswd": "Matrix user password",
"matrixhomeserver": "https://homeserver.com/_matrix/client/r0",
"rooms": [{
"tgname": "Name of the room in Telegram",
"matrixname": "Name of the room in Matrix", "matrixname": "Name of the room in Matrix",
"tgid": "Chat id of the room in Telegram", "tgid": "Chat id of the room in Telegram",
"lastmessageid": "event id of the last message sent in this room. DO NOT EDIT",
"matrixid": "Chat id of the room in Matrix", "matrixid": "Chat id of the room in Matrix",
"lastmessageid": "event id of the last message sent in this room. DO NOT EDIT" "tgname": "Name of the room in Telegram"
]} }
],
"matrixhomeserver": "https://homeserver.com/_matrix/client/r0",
"tgtoken": "Token key given from BotFather",
"matrixuser": "Matrix user name",
"matrixpswd": "Matrix user password"
} }

View File

@ -2,6 +2,10 @@ package com.em.miguelbridge;
import com.em.miguelbridge.matrixbot.MatrixBot; import com.em.miguelbridge.matrixbot.MatrixBot;
import com.em.miguelbridge.telegrambot.TGBot; import com.em.miguelbridge.telegrambot.TGBot;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -45,7 +49,14 @@ public class Launcher {
matrixBot.setAccessToken(matrixBot.login()); matrixBot.setAccessToken(matrixBot.login());
System.out.println("Bot Matrix avviato! " + matrixBot.readBotUserName()); System.out.println("Bot Matrix avviato! " + matrixBot.readBotUserName());
String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; //Joina tutte le room presenti nel json del collegamento
JSONArray rooms = getRooms();
String roomid = "";
for (int k=0; k<rooms.size(); k++) {
JSONObject room = (JSONObject) rooms.get(k);
roomid = (String) room.get("matrixid");
matrixBot.joinRoom(roomid);
}
String[] newMessaggio; String[] newMessaggio;
@ -53,38 +64,54 @@ public class Launcher {
while (true) { while (true) {
//Main loop del bot di matrix //Main loop del bot di matrix
Thread.sleep(3 * 1000); Thread.sleep(500);
lastMessageId = getLastMessageId(); rooms = getRooms();
newMessaggio = (String[]) matrixBot.getLastMessage(roomAddress); for (int roomNumber=0; roomNumber<rooms.size(); roomNumber++) {
JSONObject room = (JSONObject) rooms.get(roomNumber);
String matrixRoomId = (String) room.get("matrixid");
lastMessageId = getLastMessageId(matrixRoomId);
newMessaggio = (String[]) matrixBot.getLastMessage(matrixRoomId);
if (!newMessaggio[0].equals(matrixBot.readBotUserName()) && !newMessaggio[2].equals(lastMessageId)) { if (!newMessaggio[0].equals(matrixBot.readBotUserName()) && !newMessaggio[2].equals(lastMessageId)) {
tgBot.cEcho("18200812", newMessaggio[0] + " da matrix dice: " + newMessaggio[1]); String tgroomid = (String) room.get("tgid");
tgBot.cEcho(tgroomid, newMessaggio[0] + ":\n" + newMessaggio[1]);
} }
saveLastMessageId(newMessaggio[2]); saveLastMessageId(newMessaggio[2], matrixRoomId);
}
} }
} catch (Exception ex) { } catch (Exception ex) {
System.err.println("Avvio caricamento bot:");
Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
private static synchronized String getLastMessageId() throws FileNotFoundException, IOException, ParseException { private static synchronized String getLastMessageId(String matrixRoomId) throws FileNotFoundException, IOException, ParseException {
JSONParser jparser = new JSONParser(); JSONParser jparser = new JSONParser();
FileReader file; FileReader file;
BufferedReader in; BufferedReader in;
JSONObject obj; JSONObject obj;
JSONArray rooms; JSONArray rooms;
JSONObject room; JSONObject room;
int roomNumber = -1;
file = new FileReader(Launcher.fileSettings); file = new FileReader(Launcher.fileSettings);
in = new BufferedReader(file); in = new BufferedReader(file);
obj = (JSONObject) jparser.parse(in); obj = (JSONObject) jparser.parse(in);
rooms = (JSONArray) obj.get("rooms"); rooms = (JSONArray) obj.get("rooms");
room = (JSONObject) rooms.get(0);
for (int k=0; k<rooms.size(); k++) {
JSONObject thisRoom = (JSONObject) rooms.get(k);
String thisRoomId = (String) thisRoom.get("matrixid");
if (matrixRoomId.equals(thisRoomId)) {
roomNumber = k;
break;
}
}
room = (JSONObject) rooms.get(roomNumber);
file.close(); file.close();
in.close(); in.close();
@ -92,7 +119,47 @@ public class Launcher {
return (String) room.get("lastmessageid"); return (String) room.get("lastmessageid");
} }
private static synchronized void saveLastMessageId(String id) throws FileNotFoundException, IOException, ParseException { private static synchronized void saveLastMessageId(String messageId, String matrixRoomId) throws FileNotFoundException, IOException, ParseException {
JSONParser jparser = new JSONParser();
FileReader file;
BufferedReader in;
JSONObject obj;
JSONArray rooms;
JSONObject room;
int roomNumber = -1;
file = new FileReader(Launcher.fileSettings);
in = new BufferedReader(file);
obj = (JSONObject) jparser.parse(in);
rooms = (JSONArray) obj.get("rooms");
for (int k=0; k<rooms.size(); k++) {
JSONObject thisRoom = (JSONObject) rooms.get(k);
String thisRoomId = (String) thisRoom.get("matrixid");
if (matrixRoomId.equals(thisRoomId)) {
roomNumber = k;
break;
}
}
room = (JSONObject) rooms.get(roomNumber);
room.put("lastmessageid", messageId);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(obj.toJSONString());
String prettyJsonString = gson.toJson(je);
new File(fileSettings).createNewFile();
PrintWriter writer = new PrintWriter(fileSettings);
writer.print(prettyJsonString);
writer.close();
file.close();
in.close();
}
public static synchronized JSONArray getRooms() throws FileNotFoundException, IOException, ParseException {
JSONParser jparser = new JSONParser(); JSONParser jparser = new JSONParser();
FileReader file; FileReader file;
BufferedReader in; BufferedReader in;
@ -104,15 +171,10 @@ public class Launcher {
in = new BufferedReader(file); in = new BufferedReader(file);
obj = (JSONObject) jparser.parse(in); obj = (JSONObject) jparser.parse(in);
rooms = (JSONArray) obj.get("rooms"); rooms = (JSONArray) obj.get("rooms");
room = (JSONObject) rooms.get(0);
room.put("lastmessageid", id);
new File(fileSettings).createNewFile();
PrintWriter writer = new PrintWriter(fileSettings);
writer.print(obj.toJSONString());
writer.close();
file.close(); file.close();
in.close(); in.close();
return rooms;
} }
} }

View File

@ -5,8 +5,11 @@ import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.*; import org.json.simple.*;
import org.json.simple.parser.*; import org.json.simple.parser.*;
@ -97,10 +100,10 @@ public class MatrixBot {
String[][] reqParams = null; String[][] reqParams = null;
String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams);
return risposta[0] + " - " + risposta[1]; return risposta[0];
} }
public String sendMessage(String message, String roomAddress) throws IOException, URISyntaxException { public synchronized String sendMessage(String message, String roomAddress) throws IOException, URISyntaxException {
String requestUrl = homeUrl + String.format("/rooms/%s/send/m.room.message?access_token=%s", String requestUrl = homeUrl + String.format("/rooms/%s/send/m.room.message?access_token=%s",
roomAddress, accessToken); roomAddress, accessToken);
@ -114,7 +117,8 @@ public class MatrixBot {
return risposta[0] + " - " + risposta[1]; return risposta[0] + " - " + risposta[1];
} }
public String[] getLastMessage(String roomAddress) throws IOException, ParseException { public String[] getLastMessage(String roomAddress) {
try {
String filtro = URLEncoder.encode("{\"room\":{\"timeline\":{\"limit\":1}}}", "UTF-8"); String filtro = URLEncoder.encode("{\"room\":{\"timeline\":{\"limit\":1}}}", "UTF-8");
String requestUrl = homeUrl + String requestUrl = homeUrl +
String.format("/sync?filter=%s&access_token=%s", String.format("/sync?filter=%s&access_token=%s",
@ -135,8 +139,11 @@ public class MatrixBot {
JSONObject content = (JSONObject) last.get("content"); JSONObject content = (JSONObject) last.get("content");
String body = (String) content.get("body"); String body = (String) content.get("body");
//Come prima stringa c'è l'id del mittente, come seconda il body del messaggio //Come prima stringa c'è l'id del mittente, come seconda il body del messaggio e come terzo l'id del messaggio
String[] lastMessage = new String[] {sender, body, eventid}; String[] lastMessage = new String[] {sender, body, eventid};
return lastMessage; return lastMessage;
} catch (Exception ex) {
return new String[] {"", "", ""};
}
} }
} }

View File

@ -1,75 +0,0 @@
package com.em.miguelbridge.matrixbot;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @author Emanuele Magon
*/
public class OLDRequestHandler {
public static String[] getRequest(String inURL) throws MalformedURLException, IOException {
String[] risposta = new String[2];
URL url = new URL(inURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int status = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
String risp = "";
while ((inputLine = in.readLine()) != null) {
risp += inputLine;
}
in.close();
risposta[0] = "" + status;
risposta[1] = risp;
return risposta;
}
public static String[] postRequest(String inURL, String[][] reqParams) throws MalformedURLException, IOException {
String[] risposta = new String[2];
URL url = new URL(inURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// Send post request
connection.setDoOutput(true);
String postParam = "";
for (String[] reqParam : reqParams) {
postParam += reqParam[0] + "=" + reqParam[1] + "&";
}
if (postParam.length() > 0)
postParam = postParam.substring(0, postParam.length()-1);
System.out.println(postParam);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(postParam);
wr.flush();
wr.close();
int status = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
String risp = "";
while ((inputLine = in.readLine()) != null) {
risp += inputLine;
}
in.close();
risposta[0] = "" + status;
risposta[1] = risp;
return risposta;
}
}

View File

@ -3,12 +3,15 @@ package com.em.miguelbridge.telegrambot;
import com.em.miguelbridge.Launcher; import com.em.miguelbridge.Launcher;
import com.em.miguelbridge.matrixbot.MatrixBot; import com.em.miguelbridge.matrixbot.MatrixBot;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.telegram.telegrambots.api.methods.send.*; import org.telegram.telegrambots.api.methods.send.*;
import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.api.objects.Update;
@ -33,17 +36,28 @@ public class TGBot extends TelegramLongPollingBot {
*/ */
//Controllo per vedere se l'update è un messaggio testuale e che esso non sia vuoto //Controllo per vedere se l'update è un messaggio testuale e che esso non sia vuoto
if (update.hasMessage() && update.getMessage().hasText()) { if (update.hasMessage()) {
if (update.getMessage().getText().equalsIgnoreCase("/chatid") ||
update.getMessage().getText().equalsIgnoreCase("/chatid@" + getBotUsername())) {
String chat_id = "" + update.getMessage().getChatId();
cEcho(chat_id, chat_id);
}
else {
//Testo e mittente //Testo e mittente
String testoMessaggio = update.getMessage().getText(); String testoMessaggio = update.getMessage().getText();
String chat_id = "" + update.getMessage().getChatId(); String chat_id = "" + update.getMessage().getChatId();
String sender = update.getMessage().getFrom().getFirstName() + " " String sender = update.getMessage().getFrom().getFirstName() + " "
+ update.getMessage().getFrom().getLastName(); + update.getMessage().getFrom().getLastName();
String destination;
//Per capire qual'è l'id della chat di telegram try {
//System.out.println(chat_id); destination = getDestinationRoom(chat_id);
if (destination == null)
echoToMatrix(testoMessaggio, sender); throw new Exception();
echoToMatrix(testoMessaggio, sender, destination);
} catch (Exception ex) {
cEcho(chat_id, "Errore: questa chat non è collegata a matrix.");
}
}
} }
} }
@ -71,6 +85,17 @@ public class TGBot extends TelegramLongPollingBot {
return ""; return "";
} }
private String getDestinationRoom(String sender_id) throws IOException, FileNotFoundException, ParseException {
//Dalla chat mittente in telegram ritorna l'id della chat di matrix relativa
JSONArray rooms = Launcher.getRooms();
for (int k=0; k<rooms.size(); k++) {
JSONObject room = (JSONObject) rooms.get(k);
String roomTgId = (String) room.get("tgid");
if (roomTgId.equals(sender_id))
return (String) room.get("matrixid");
}
return null;
}
//----------COMANDI---------- //----------COMANDI----------
public void cEcho(String chat_id, String testoMessaggio){ public void cEcho(String chat_id, String testoMessaggio){
@ -88,10 +113,9 @@ public class TGBot extends TelegramLongPollingBot {
} }
} }
private void echoToMatrix(String testoMessaggio, String sender) { private void echoToMatrix(String testoMessaggio, String sender, String destination) {
try { try {
String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; matrixBot.sendMessage(sender + ":\n" + testoMessaggio, destination);
matrixBot.sendMessage(sender + " da Telegram dice: " + testoMessaggio, roomAddress);
} catch (Exception ex) { } catch (Exception ex) {
Logger.getLogger(TGBot.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(TGBot.class.getName()).log(Level.SEVERE, null, ex);
} }