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

Prima versione "funzionante"

Per ora inoltra solo i messaggi di testo tra la chat "provaBot" su matrix e la chat tra me ed il bot su telegram, con gli id delle stanze brutalmente hardcodate dentro.
This commit is contained in:
Ahab 2018-04-09 02:01:44 +02:00
parent c07392b09c
commit 0daaf77f2f
18 changed files with 295 additions and 85 deletions

BIN
lib/httpclient-4.5.5.jar Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
lib/maybe/jna-4.4.0.jar Normal file

Binary file not shown.

Binary file not shown.

View File

@ -29,13 +29,15 @@ 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.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
includes=** includes=**
jar.compress=false 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}
# 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,9 +1,13 @@
package com.em.miguelbridge; package com.em.miguelbridge;
import com.em.miguelbridge.matrixbot.MatrixBot;
import com.em.miguelbridge.telegrambot.TGBot; import com.em.miguelbridge.telegrambot.TGBot;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi; import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException; import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
/* /*
* @author Emanuele Magon * @author Emanuele Magon
@ -16,14 +20,43 @@ public class Launcher {
// Instanzia le API dei bot di Telegram (richiesto) // Instanzia le API dei bot di Telegram (richiesto)
TelegramBotsApi botsApi = new TelegramBotsApi(); TelegramBotsApi botsApi = new TelegramBotsApi();
// Avvia il bot di Telegram // Avvia i bot
try { try {
TGBot bot = new TGBot(); TGBot tgBot = new TGBot();
System.out.println("Caricamento del bot @" + bot.getBotUsername() + " su telegram..."); MatrixBot matrixBot = new MatrixBot();
botsApi.registerBot(bot);
System.out.println("Bot Telegram avviato! @" + bot.getBotUsername()); System.out.println("Caricamento del bot telegram @" + tgBot.getBotUsername() + "...");
} catch (TelegramApiException e) { tgBot.linkMatrixBot(matrixBot);
System.err.println("Errore avvio bot: " + e); botsApi.registerBot(tgBot);
System.out.println("Bot Telegram avviato! @" + tgBot.getBotUsername());
System.out.println("\nCaricamento del bot Matrix " + MatrixBot.readUserName() + "...");
matrixBot.setAccessToken(matrixBot.login());
System.out.println("Bot Matrix avviato! " + matrixBot.readUserName());
String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu";
while (true) {
//Main loop del bot di matrix
String[] newMessaggio;
String lastMessaggio = "";
while (true) {
newMessaggio = matrixBot.getLastMessage(roomAddress);
if (!newMessaggio[0].equals(matrixBot.readUserName()) && !newMessaggio[1].equals(lastMessaggio)) {
tgBot.cEcho("18200812", "Qualcono da matrix dice: " + newMessaggio[1]);
}
lastMessaggio = newMessaggio[1];
}
}
} catch (Exception ex) {
System.err.println("Avvio caricamento bot:");
Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
} }

View File

@ -4,25 +4,33 @@ 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.InputStreamReader; import java.net.URISyntaxException;
import java.net.HttpURLConnection; import java.net.URLEncoder;
import java.net.MalformedURLException; import org.json.simple.*;
import java.net.URL; import org.json.simple.parser.*;
/** /**
* @author Emanuele Magon * @author Emanuele Magon
*/ */
public class MatrixBot { public class MatrixBot {
//https://matrix.org/docs/guides/client-server.html //https://matrix.org/docs/guides/client-server.html
private String homeUrl; private final String homeUrl;
private String fileInfo; private final static String fileInfo = "files/MatrixBotInfo.txt";
private String accessToken;
public MatrixBot() { public String getAccessToken() {
homeUrl = "https://maxwell.ydns.eu/_matrix/client/"; return accessToken;
fileInfo = "files/MatrixBotInfo.txt";
} }
public String readUserName() throws FileNotFoundException, IOException { public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public MatrixBot() {
homeUrl = "https://maxwell.ydns.eu/_matrix/client/r0";
}
public static String readUserName() throws FileNotFoundException, IOException {
FileReader file = new FileReader(fileInfo); FileReader file = new FileReader(fileInfo);
BufferedReader in = new BufferedReader(file); BufferedReader in = new BufferedReader(file);
String str = in.readLine(); String str = in.readLine();
@ -43,19 +51,73 @@ public class MatrixBot {
/** /**
* *
* @return Access Token per il bot, da utilizzare nelle prossime chiamate * @return Access Token per il bot, da utilizzare nelle prossime richieste HTTP
* @throws java.io.IOException
* @throws org.json.simple.parser.ParseException
* @throws java.net.URISyntaxException
*/ */
public String login() throws IOException { public String login() throws IOException, ParseException, URISyntaxException {
String requestUrl = "r0/login"; String requestUrl = homeUrl + "/login";
String[][] reqParams = new String[][] { String[][] reqParams = new String[][] {
{"\"type\"", "\"m.login.password\""}, {"type", "m.login.password"},
{"\"user\"", "\"" + readUserName() + "\""}, {"user", readUserName()},
{"\"password\"", "\"" + readPswd() + "\""} {"password", readPswd()}
}; };
String[] risposta = RequestHandler.postRequest(homeUrl, reqParams); String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams);
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(risposta[1]);
return ""+obj.get("access_token");
}
return (risposta[0] + " - " + risposta[1]); public String joinRoom(String roomAddress) throws IOException, ParseException, URISyntaxException {
String requestUrl = homeUrl + String.format("/rooms/%s/join?access_token=%s",
roomAddress, accessToken);
String[][] reqParams = null;
String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams);
return risposta[0] + " - " + risposta[1];
}
public String sendMessage(String message, String roomAddress) throws IOException, URISyntaxException {
String requestUrl = homeUrl + String.format("/rooms/%s/send/m.room.message?access_token=%s",
roomAddress, accessToken);
String[][] reqParams = new String[][] {
{"msgtype", "m.text"},
{"body", message}
};
String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams);
return risposta[0] + " - " + risposta[1];
}
public String[] getLastMessage(String roomAddress) throws IOException, ParseException {
String filtro = URLEncoder.encode("{\"room\":{\"timeline\":{\"limit\":1}}}", "UTF-8");
String requestUrl = homeUrl +
String.format("/sync?filter=%s&access_token=%s",
filtro, accessToken);
String[] risposta = RequestHandler.getRequest(requestUrl);
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(risposta[1]);
JSONObject rooms = (JSONObject) obj.get("rooms");
JSONObject joined = (JSONObject) rooms.get("join");
JSONObject thisRoom = (JSONObject) joined.get(roomAddress);
JSONObject timeline = (JSONObject) thisRoom.get("timeline");
JSONArray events = (JSONArray) timeline.get("events");
JSONObject last = (JSONObject) events.get(0);
String sender = (String) last.get("sender");
JSONObject content = (JSONObject) last.get("content");
String body = (String) content.get("body");
//Come prima stringa c'è l'id del mittente, come seconda il body del messaggio
String[] lastMessage = new String[] {sender, body};
return lastMessage;
} }
} }

View File

@ -0,0 +1,75 @@
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

@ -1,75 +1,79 @@
package com.em.miguelbridge.matrixbot; package com.em.miguelbridge.matrixbot;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.URI;
import java.net.MalformedURLException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
/** /**
* @author Emanuele Magon * @author Emanuele Magon
*/ */
public class RequestHandler { public class RequestHandler {
public static String[] getRequest(String inURL) throws MalformedURLException, IOException { public static String[] getRequest(String inUrl) throws IOException {
String[] risposta = new String[2]; HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(inUrl);
//add header
request.setHeader("User-Agent", "Mozilla/5.0");
request.addHeader("Content-Type", "charset=UTF_8");
URL url = new URL(inURL); HttpResponse response = client.execute(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int status = connection.getResponseCode(); BufferedReader rd = new BufferedReader(
BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
new InputStreamReader(connection.getInputStream()));
String inputLine;
String risp = "";
while ((inputLine = in.readLine()) != null) {
risp += inputLine;
}
in.close();
risposta[0] = "" + status; StringBuffer result = new StringBuffer();
risposta[1] = risp; String line = "";
while ((line = rd.readLine()) != null)
result.append(line);
String[] risposta =
new String[] {""+response.getStatusLine().getStatusCode(), result.toString()};
return risposta; return risposta;
} }
public static String[] postRequest(String inURL, String[][] reqParams) throws MalformedURLException, IOException { public static String[] postRequestJSON(String inUrl, String[][] reqParams) throws IOException, URISyntaxException {
String[] risposta = new String[2]; HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(inUrl);
URL url = new URL(inURL); //add header
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); post.setHeader("User-Agent", "Mozilla/5.0");
connection.setRequestMethod("POST"); post.addHeader("Content-Type", "charset=UTF_8");
// Send post request JSONObject obj = new JSONObject();
connection.setDoOutput(true); if (reqParams != null) {
String postParam = ""; for (String[] param : reqParams)
for (String[] reqParam : reqParams) { obj.put(param[0], param[1]);
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()); String jsonString = obj.toJSONString();
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; StringEntity requestEntity = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON);
risposta[1] = risp; post.setEntity(requestEntity);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null)
result.append(line);
String[] risposta =
new String[] {""+response.getStatusLine().getStatusCode(), result.toString()};
return risposta; return risposta;
} }
} }

View File

@ -1,6 +1,5 @@
package com.em.miguelbridge.matrixbot; package com.em.miguelbridge.matrixbot;
import java.io.IOException;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -10,12 +9,29 @@ import java.util.logging.Logger;
*/ */
public class prova { public class prova {
public static void main(String[] args) { public static void main(String[] args) {
String accessToken, roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu";
try { try {
MatrixBot bot = new MatrixBot(); MatrixBot bot = new MatrixBot();
System.out.println(bot.readUserName() + " - " + bot.readPswd()); //System.out.println(bot.readUserName() + " - " + bot.readPswd());
System.out.println(bot.login()); accessToken = bot.login();
} catch (IOException ex) {
//System.out.println(bot.joinRoom(chatID));
//System.out.println(bot.sendMessage("ciaoo", chatID));
String[] ultimoMess;
while (true) {
ultimoMess = bot.getLastMessage(roomAddress);
if (!ultimoMess[0].equals(bot.readUserName())) {
System.out.println(ultimoMess[0] + " dice: " + ultimoMess[1]);
bot.sendMessage(ultimoMess[1], roomAddress);
}
}
} catch (Exception ex) {
Logger.getLogger(prova.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(prova.class.getName()).log(Level.SEVERE, null, ex);
} }
} }

View File

@ -1,8 +1,12 @@
package com.em.miguelbridge.telegrambot; package com.em.miguelbridge.telegrambot;
import com.em.miguelbridge.matrixbot.MatrixBot;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
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;
@ -15,6 +19,11 @@ public class TGBot extends TelegramLongPollingBot {
//Costanti con il mio id e il nome del file delle richieste //Costanti con il mio id e il nome del file delle richieste
private final String admin_id = "18200812"; private final String admin_id = "18200812";
private final String fileToken = "files/TGbot.token"; private final String fileToken = "files/TGbot.token";
private MatrixBot matrixBot;
public void linkMatrixBot(MatrixBot matrixBot) {
this.matrixBot = matrixBot;
}
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
@ -29,8 +38,8 @@ public class TGBot extends TelegramLongPollingBot {
//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();
System.out.println(chat_id);
cEcho(chat_id, testoMessaggio); sendToMatrix(testoMessaggio);
} }
} }
@ -71,4 +80,13 @@ public class TGBot extends TelegramLongPollingBot {
System.err.println("Errore: " + e); System.err.println("Errore: " + e);
} }
} }
private void sendToMatrix(String testoMessaggio) {
try {
String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu";
matrixBot.sendMessage("Qualcuno da Telegram dice: " + testoMessaggio, roomAddress);
} catch (Exception ex) {
Logger.getLogger(TGBot.class.getName()).log(Level.SEVERE, null, ex);
}
}
} }