1
1
mirror of https://github.com/ahabhyde/miguelbridge synced 2025-01-10 06:24:20 +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
endorsed.classpath=
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.telegrambots-3.0-jar-with-dependencies.jar=lib\\telegrambots-3.0-jar-with-dependencies.jar
includes=**
jar.compress=false
javac.classpath=\
${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
javac.compilerargs=
javac.deprecation=false

View File

@ -1,9 +1,13 @@
package com.em.miguelbridge;
import com.em.miguelbridge.matrixbot.MatrixBot;
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.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
/*
* @author Emanuele Magon
@ -16,14 +20,43 @@ public class Launcher {
// Instanzia le API dei bot di Telegram (richiesto)
TelegramBotsApi botsApi = new TelegramBotsApi();
// Avvia il bot di Telegram
// Avvia i bot
try {
TGBot bot = new TGBot();
System.out.println("Caricamento del bot @" + bot.getBotUsername() + " su telegram...");
botsApi.registerBot(bot);
System.out.println("Bot Telegram avviato! @" + bot.getBotUsername());
} catch (TelegramApiException e) {
System.err.println("Errore avvio bot: " + e);
TGBot tgBot = new TGBot();
MatrixBot matrixBot = new MatrixBot();
System.out.println("Caricamento del bot telegram @" + tgBot.getBotUsername() + "...");
tgBot.linkMatrixBot(matrixBot);
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.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import org.json.simple.*;
import org.json.simple.parser.*;
/**
* @author Emanuele Magon
*/
public class MatrixBot {
//https://matrix.org/docs/guides/client-server.html
private String homeUrl;
private String fileInfo;
private final String homeUrl;
private final static String fileInfo = "files/MatrixBotInfo.txt";
private String accessToken;
public MatrixBot() {
homeUrl = "https://maxwell.ydns.eu/_matrix/client/";
fileInfo = "files/MatrixBotInfo.txt";
public String getAccessToken() {
return accessToken;
}
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);
BufferedReader in = new BufferedReader(file);
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 {
String requestUrl = "r0/login";
public String login() throws IOException, ParseException, URISyntaxException {
String requestUrl = homeUrl + "/login";
String[][] reqParams = new String[][] {
{"\"type\"", "\"m.login.password\""},
{"\"user\"", "\"" + readUserName() + "\""},
{"\"password\"", "\"" + readPswd() + "\""}
{"type", "m.login.password"},
{"user", readUserName()},
{"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;
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;
import java.net.URI;
import java.net.URISyntaxException;
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
*/
public class RequestHandler {
public static String[] getRequest(String inURL) throws MalformedURLException, IOException {
String[] risposta = new String[2];
public static String[] getRequest(String inUrl) throws IOException {
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);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
HttpResponse response = client.execute(request);
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();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
risposta[0] = "" + status;
risposta[1] = risp;
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;
}
public static String[] postRequest(String inURL, String[][] reqParams) throws MalformedURLException, IOException {
String[] risposta = new String[2];
public static String[] postRequestJSON(String inUrl, String[][] reqParams) throws IOException, URISyntaxException {
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(inUrl);
URL url = new URL(inURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
//add header
post.setHeader("User-Agent", "Mozilla/5.0");
post.addHeader("Content-Type", "charset=UTF_8");
// Send post request
connection.setDoOutput(true);
String postParam = "";
for (String[] reqParam : reqParams) {
postParam += reqParam[0] + "=" + reqParam[1] + "&";
JSONObject obj = new JSONObject();
if (reqParams != null) {
for (String[] param : reqParams)
obj.put(param[0], param[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();
String jsonString = obj.toJSONString();
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;
StringEntity requestEntity = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON);
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;
}
}

View File

@ -1,6 +1,5 @@
package com.em.miguelbridge.matrixbot;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -10,12 +9,29 @@ import java.util.logging.Logger;
*/
public class prova {
public static void main(String[] args) {
String accessToken, roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu";
try {
MatrixBot bot = new MatrixBot();
System.out.println(bot.readUserName() + " - " + bot.readPswd());
System.out.println(bot.login());
} catch (IOException ex) {
//System.out.println(bot.readUserName() + " - " + bot.readPswd());
accessToken = bot.login();
//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);
}
}

View File

@ -1,8 +1,12 @@
package com.em.miguelbridge.telegrambot;
import com.em.miguelbridge.matrixbot.MatrixBot;
import java.io.BufferedReader;
import java.io.FileReader;
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.objects.Update;
@ -15,6 +19,11 @@ public class TGBot extends TelegramLongPollingBot {
//Costanti con il mio id e il nome del file delle richieste
private final String admin_id = "18200812";
private final String fileToken = "files/TGbot.token";
private MatrixBot matrixBot;
public void linkMatrixBot(MatrixBot matrixBot) {
this.matrixBot = matrixBot;
}
@Override
public void onUpdateReceived(Update update) {
@ -29,8 +38,8 @@ public class TGBot extends TelegramLongPollingBot {
//Testo e mittente
String testoMessaggio = update.getMessage().getText();
String chat_id = "" + update.getMessage().getChatId();
cEcho(chat_id, testoMessaggio);
System.out.println(chat_id);
sendToMatrix(testoMessaggio);
}
}
@ -71,4 +80,13 @@ public class TGBot extends TelegramLongPollingBot {
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);
}
}
}