1
1
mirror of https://github.com/ahabhyde/miguelbridge synced 2025-01-26 14:04:20 +01:00

Nome nel messaggio

Ora viene scritto chi ha scritto il messaggio e tutte le impostazioni sono salvate in un unico file json
This commit is contained in:
Ahab 2018-04-09 12:48:31 +02:00
parent 0daaf77f2f
commit c88a31254a
4 changed files with 111 additions and 41 deletions

View File

@ -2,18 +2,28 @@ 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 java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
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.parser.JSONParser;
import org.json.simple.parser.ParseException;
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.TelegramApiRequestException;
/* /*
* @author Emanuele Magon * @author Emanuele Magon
*/ */
public class Launcher { public class Launcher {
public static void main(String[] args) { public final static String fileSettings = "files/botsettings.json";
public static void main(String[] args) {
// Inizializza il context delle API Telegram (richiesto) // Inizializza il context delle API Telegram (richiesto)
ApiContextInitializer.init(); ApiContextInitializer.init();
@ -31,25 +41,27 @@ public class Launcher {
System.out.println("Bot Telegram avviato! @" + tgBot.getBotUsername()); System.out.println("Bot Telegram avviato! @" + tgBot.getBotUsername());
System.out.println("\nCaricamento del bot Matrix " + MatrixBot.readUserName() + "..."); System.out.println("\nCaricamento del bot Matrix " + MatrixBot.readBotUserName() + "...");
matrixBot.setAccessToken(matrixBot.login()); matrixBot.setAccessToken(matrixBot.login());
System.out.println("Bot Matrix avviato! " + matrixBot.readUserName()); System.out.println("Bot Matrix avviato! " + matrixBot.readBotUserName());
String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu";
String[] newMessaggio;
String lastMessageId = "";
while (true) { while (true) {
//Main loop del bot di matrix //Main loop del bot di matrix
String[] newMessaggio; Thread.sleep(3 * 1000);
String lastMessaggio = ""; lastMessageId = getLastMessageId();
newMessaggio = (String[]) matrixBot.getLastMessage(roomAddress);
while (true) {
newMessaggio = matrixBot.getLastMessage(roomAddress);
if (!newMessaggio[0].equals(matrixBot.readBotUserName()) && !newMessaggio[2].equals(lastMessageId)) {
if (!newMessaggio[0].equals(matrixBot.readUserName()) && !newMessaggio[1].equals(lastMessaggio)) { tgBot.cEcho("18200812", newMessaggio[0] + " da matrix dice: " + newMessaggio[1]);
tgBot.cEcho("18200812", "Qualcono da matrix dice: " + newMessaggio[1]);
}
lastMessaggio = newMessaggio[1];
} }
saveLastMessageId(newMessaggio[2]);
} }
} catch (Exception ex) { } catch (Exception ex) {
@ -59,4 +71,48 @@ public class Launcher {
} }
private static synchronized String getLastMessageId() throws FileNotFoundException, IOException, ParseException {
JSONParser jparser = new JSONParser();
FileReader file;
BufferedReader in;
JSONObject obj;
JSONArray rooms;
JSONObject room;
file = new FileReader(Launcher.fileSettings);
in = new BufferedReader(file);
obj = (JSONObject) jparser.parse(in);
rooms = (JSONArray) obj.get("rooms");
room = (JSONObject) rooms.get(0);
file.close();
in.close();
return (String) room.get("lastmessageid");
}
private static synchronized void saveLastMessageId(String id) throws FileNotFoundException, IOException, ParseException {
JSONParser jparser = new JSONParser();
FileReader file;
BufferedReader in;
JSONObject obj;
JSONArray rooms;
JSONObject room;
file = new FileReader(Launcher.fileSettings);
in = new BufferedReader(file);
obj = (JSONObject) jparser.parse(in);
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();
in.close();
}
} }

View File

@ -1,5 +1,6 @@
package com.em.miguelbridge.matrixbot; package com.em.miguelbridge.matrixbot;
import com.em.miguelbridge.Launcher;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@ -15,7 +16,7 @@ import org.json.simple.parser.*;
public class MatrixBot { public class MatrixBot {
//https://matrix.org/docs/guides/client-server.html //https://matrix.org/docs/guides/client-server.html
private final String homeUrl; private final String homeUrl;
private final static String fileInfo = "files/MatrixBotInfo.txt";
private String accessToken; private String accessToken;
public String getAccessToken() { public String getAccessToken() {
@ -30,23 +31,28 @@ public class MatrixBot {
homeUrl = "https://maxwell.ydns.eu/_matrix/client/r0"; homeUrl = "https://maxwell.ydns.eu/_matrix/client/r0";
} }
public static String readUserName() throws FileNotFoundException, IOException { public static String readBotUserName() throws FileNotFoundException, IOException, ParseException {
FileReader file = new FileReader(fileInfo); FileReader file = new FileReader(Launcher.fileSettings);
BufferedReader in = new BufferedReader(file); BufferedReader in = new BufferedReader(file);
String str = in.readLine();
JSONObject obj = (JSONObject) new JSONParser().parse(in);
in.close(); in.close();
return str; String userName = (String) obj.get("matrixuser");
return userName;
} }
public String readPswd() throws FileNotFoundException, IOException { public String readPswd() throws FileNotFoundException, IOException, ParseException {
FileReader file = new FileReader(fileInfo); FileReader file = new FileReader(Launcher.fileSettings);
BufferedReader in = new BufferedReader(file); BufferedReader in = new BufferedReader(file);
in.readLine(); //Usato per leggere la seconda riga
String str = in.readLine(); JSONObject obj = (JSONObject) new JSONParser().parse(in);
in.close(); in.close();
return str; String pswd = (String) obj.get("matrixpswd");
return pswd;
} }
/** /**
@ -61,7 +67,7 @@ public class MatrixBot {
String[][] reqParams = new String[][] { String[][] reqParams = new String[][] {
{"type", "m.login.password"}, {"type", "m.login.password"},
{"user", readUserName()}, {"user", readBotUserName()},
{"password", readPswd()} {"password", readPswd()}
}; };
@ -112,12 +118,13 @@ public class MatrixBot {
JSONObject timeline = (JSONObject) thisRoom.get("timeline"); JSONObject timeline = (JSONObject) thisRoom.get("timeline");
JSONArray events = (JSONArray) timeline.get("events"); JSONArray events = (JSONArray) timeline.get("events");
JSONObject last = (JSONObject) events.get(0); JSONObject last = (JSONObject) events.get(0);
String eventid = (String) last.get("event_id");
String sender = (String) last.get("sender"); String sender = (String) last.get("sender");
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
String[] lastMessage = new String[] {sender, body}; String[] lastMessage = new String[] {sender, body, eventid};
return lastMessage; return lastMessage;
} }
} }

View File

@ -25,7 +25,7 @@ public class prova {
ultimoMess = bot.getLastMessage(roomAddress); ultimoMess = bot.getLastMessage(roomAddress);
if (!ultimoMess[0].equals(bot.readUserName())) { if (!ultimoMess[0].equals(bot.readBotUserName())) {
System.out.println(ultimoMess[0] + " dice: " + ultimoMess[1]); System.out.println(ultimoMess[0] + " dice: " + ultimoMess[1]);
bot.sendMessage(ultimoMess[1], roomAddress); bot.sendMessage(ultimoMess[1], roomAddress);
} }

View File

@ -1,12 +1,14 @@
package com.em.miguelbridge.telegrambot; package com.em.miguelbridge.telegrambot;
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.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.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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;
@ -16,9 +18,6 @@ import org.telegram.telegrambots.bots.TelegramLongPollingBot;
* @author Emanuele Magon * @author Emanuele Magon
*/ */
public class TGBot extends TelegramLongPollingBot { 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; private MatrixBot matrixBot;
public void linkMatrixBot(MatrixBot matrixBot) { public void linkMatrixBot(MatrixBot matrixBot) {
@ -38,8 +37,13 @@ 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); String sender = update.getMessage().getFrom().getFirstName() + " "
sendToMatrix(testoMessaggio); + update.getMessage().getFrom().getLastName();
//Per capire qual'è l'id della chat di telegram
//System.out.println(chat_id);
echoToMatrix(testoMessaggio, sender);
} }
} }
@ -54,11 +58,14 @@ public class TGBot extends TelegramLongPollingBot {
public String getBotToken() { public String getBotToken() {
try { try {
//Return bot token from BotFather //Return bot token from BotFather
//Legge il file di testo con il nome passato. Mantiene gli a capo e tabulazioni FileReader file = new FileReader(Launcher.fileSettings);
BufferedReader reader; BufferedReader in = new BufferedReader(file);
reader = new BufferedReader(new FileReader (fileToken)); JSONObject obj = (JSONObject) new JSONParser().parse(in);
return reader.readLine(); in.close();
} catch (IOException e) { String token = (String) obj.get("tgtoken");
return token;
} catch (Exception e) {
System.out.println("Errore apertura file token: " + e); System.out.println("Errore apertura file token: " + e);
} }
return ""; return "";
@ -81,10 +88,10 @@ public class TGBot extends TelegramLongPollingBot {
} }
} }
private void sendToMatrix(String testoMessaggio) { private void echoToMatrix(String testoMessaggio, String sender) {
try { try {
String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu";
matrixBot.sendMessage("Qualcuno da Telegram dice: " + testoMessaggio, roomAddress); 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);
} }