Separated all Message types in classes.

Removed Pokemon Go server status json reading, because the web that provided it has gone down.
This commit is contained in:
vylion 2016-10-09 02:15:56 +02:00
parent 8255cb15f8
commit 9d2baf8531
17 changed files with 436 additions and 269 deletions

View file

@ -2,7 +2,7 @@
<artifact type="jar" name="vylionbot:jar"> <artifact type="jar" name="vylionbot:jar">
<output-path>$PROJECT_DIR$/out/artifacts/vylionbot_jar</output-path> <output-path>$PROJECT_DIR$/out/artifacts/vylionbot_jar</output-path>
<root id="archive" name="vylionbot.jar"> <root id="archive" name="vylionbot.jar">
<element id="module-output" name="vylionbot" /> <element id="module-output" name="geiserpbot" />
<element id="extracted-dir" path="$PROJECT_DIR$/libraries/unirest-java-1.4.10-SNAPSHOT-jar-with-dependencies.jar" path-in-jar="/" /> <element id="extracted-dir" path="$PROJECT_DIR$/libraries/unirest-java-1.4.10-SNAPSHOT-jar-with-dependencies.jar" path-in-jar="/" />
</root> </root>
</artifact> </artifact>

View file

@ -2,7 +2,7 @@
<project version="4"> <project version="4">
<component name="ProjectModuleManager"> <component name="ProjectModuleManager">
<modules> <modules>
<module fileurl="file://$PROJECT_DIR$/vylionbot.iml" filepath="$PROJECT_DIR$/vylionbot.iml" /> <module fileurl="file://$PROJECT_DIR$/geiserpbot.iml" filepath="$PROJECT_DIR$/geiserpbot.iml" />
</modules> </modules>
</component> </component>
</project> </project>

View file

@ -1,121 +0,0 @@
package elements;
import elements.exceptions.NoChatNameException;
import elements.exceptions.NoUserException;
import elements.exceptions.NoUsernameException;
import org.json.JSONObject;
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
public class Message {
private Long cid; //chat id
private Integer mid; //message id
private Integer uid; //user id
private String chatType; //chat type
private String fullName; //author name
private String userName; //username
private String chatName; //chat name
private String text; //the actual message
private String consoleLog;
public Message(JSONObject message) {
cid = message.getJSONObject("chat").getLong("id");
mid = message.getInt("message_id");
chatType = message.getJSONObject("chat").getString("type");
//Check for User
if(message.has("from")) {
fullName = message.getJSONObject("from").getString("first_name");
uid = message.getJSONObject("from").getInt("id");
//Check for user last name
if (message.getJSONObject("from").has("last_name"))
fullName += " " + message.getJSONObject("from").getString("last_name");
//Check for user username
if (message.getJSONObject("from").has("username"))
userName = message.getJSONObject("from").getString("username");
else userName = null;
}
else {
fullName = null;
uid = null;
userName = null;
}
//Get group chat name
if (message.getJSONObject("chat").has("title"))
chatName = message.getJSONObject("chat").getString("title");
else chatName = null;
if (message.has("text"))
text = message.getString("text");
else text = null;
consoleLog = message.toString();
}
public long getCid() {
return cid;
}
public long getMid() {
return mid;
}
public int getUid() {
return uid;
}
public String getAuthor() {
return fullName;
}
public boolean hasUsername() {
return userName != null;
}
public String getUsername() throws NoUsernameException {
if(userName == null) throw new NoUsernameException();
return userName;
}
public String getChatName() throws NoChatNameException {
if(userName == null) throw new NoChatNameException();
return chatName;
}
public boolean hasText() {
return text != null;
}
public String getText() {
return text;
}
public boolean isGroup() {
return chatType.contains("group");
}
public boolean isBasicGroup() {
return chatType.equals("group");
}
public boolean isSupergroup() {
return chatType.equals("supergroup");
}
public boolean isChannel() {
return chatType.equals("channel");
}
public boolean isPrivate() {
return chatType.equals("private");
}
@Override
public String toString() {
return consoleLog;
}
}

View file

@ -0,0 +1,10 @@
package elements.exceptions;
/**
* Created by Guillermo Serrahima on 10/9/16.
*/
public abstract class MessageException extends Exception {
public MessageException(String s) {
super(s);
}
}

View file

@ -0,0 +1,14 @@
package elements.exceptions;
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
public class NoAuthorMessageException extends MessageException {
public NoAuthorMessageException() {
super("The message has no user. Is it from a channel?");
}
protected NoAuthorMessageException(String s) {
super(s);
}
}

View file

@ -3,8 +3,8 @@ package elements.exceptions;
/** /**
* Created by Guillermo Serrahima on 10/8/16. * Created by Guillermo Serrahima on 10/8/16.
*/ */
public class NoChatNameException extends Exception { public class NoChatNameMessageException extends MessageException {
public NoChatNameException() { public NoChatNameMessageException() {
super("The chat has no title."); super("The chat has no title.");
} }
} }

View file

@ -3,7 +3,7 @@ package elements.exceptions;
/** /**
* Created by Guillermo Serrahima on 10/8/16. * Created by Guillermo Serrahima on 10/8/16.
*/ */
public class NoTextMessageException extends Exception { public class NoTextMessageException extends MessageException {
public NoTextMessageException() { public NoTextMessageException() {
super("The message has no text."); super("The message has no text.");
} }

View file

@ -1,10 +0,0 @@
package elements.exceptions;
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
public class NoUserException extends Exception {
public NoUserException() {
super("The message has no user. Is it from a channel?");
}
}

View file

@ -3,8 +3,8 @@ package elements.exceptions;
/** /**
* Created by Guillermo Serrahima on 10/8/16. * Created by Guillermo Serrahima on 10/8/16.
*/ */
public class NoUsernameException extends Exception { public class NoUsernameMessageException extends NoAuthorMessageException {
public NoUsernameException() { public NoUsernameMessageException() {
super("The user has no username."); super("The user has no username.");
} }
} }

View file

@ -1,7 +1,7 @@
package elements; package elements.messages;
import elements.exceptions.NoChatNameException; import elements.exceptions.NoAuthorMessageException;
import elements.exceptions.NoUsernameException; import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
@ -20,9 +20,6 @@ public class ChannelMessage extends Message {
public ChannelMessage(JSONObject message) { public ChannelMessage(JSONObject message) {
super(message); super(message);
cid = message.getJSONObject("chat").getLong("id");
mid = message.getInt("message_id");
chatType = message.getJSONObject("chat").getString("type");
//Check for User //Check for User
if(message.has("from")) { if(message.has("from")) {
@ -65,58 +62,54 @@ public class ChannelMessage extends Message {
return mid; return mid;
} }
public int getUid() { public String getChatType() {
return uid; return chatType;
}
public String getAuthor() {
return fullName;
}
public boolean hasUsername() {
return userName != null;
}
public String getUsername() throws NoUsernameException {
if(userName == null) throw new NoUsernameException();
return userName;
}
public String getChatName() throws NoChatNameException {
if(userName == null) throw new NoChatNameException();
return chatName;
}
public boolean hasText() {
return text != null;
}
public String getText() {
return text;
}
public boolean isGroup() {
return chatType.contains("group");
}
public boolean isBasicGroup() {
return chatType.equals("group");
}
public boolean isSupergroup() {
return chatType.equals("supergroup");
}
public boolean isChannel() {
return chatType.equals("channel");
}
public boolean isPrivate() {
return chatType.equals("private");
} }
@Override @Override
public String toString() { public boolean hasAuthor() {
return consoleLog; return fullName != null;
}
@Override
public int getUid() throws NoAuthorMessageException {
if(!hasAuthor()) throw new NoAuthorMessageException();
return uid;
}
@Override
public String getAuthor() throws NoAuthorMessageException {
if(!hasAuthor()) throw new NoAuthorMessageException();
return fullName;
}
public String getUsername() throws NoUsernameMessageException, NoAuthorMessageException {
if(!hasAuthor()) throw new NoAuthorMessageException();
if(userName == null) throw new NoUsernameMessageException();
return userName;
}
public String getChatName() {
return chatName;
}
@Override
public boolean isBasicGroup() {
return false;
}
@Override
public boolean isSupergroup() {
return false;
}
@Override
public boolean isChannel() {
return true;
}
@Override
public boolean isPrivate() {
return false;
} }
} }

View file

@ -0,0 +1,102 @@
package elements.messages;
import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject;
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
public class GroupMessage extends Message {
private Long cid; //chat id
private Integer mid; //message id
private Integer uid; //user id
private String chatType; //chat type
private String fullName; //author name
private String userName; //username
private String chatName; //chat name
private String text; //the actual message
private String consoleLog;
public GroupMessage(JSONObject message) {
super(message);
fullName = message.getJSONObject("from").getString("first_name");
uid = message.getJSONObject("from").getInt("id");
//Check for user last name
if (message.getJSONObject("from").has("last_name"))
fullName += " " + message.getJSONObject("from").getString("last_name");
//Check for user username
if (message.getJSONObject("from").has("username"))
userName = message.getJSONObject("from").getString("username");
else userName = null;
//Get group chat name
if (message.getJSONObject("chat").has("title"))
chatName = message.getJSONObject("chat").getString("title");
else chatName = null;
if (message.has("text"))
text = message.getString("text");
else text = null;
consoleLog = message.toString();
}
public long getCid() {
return cid;
}
public long getMid() {
return mid;
}
@Override
public boolean hasAuthor() {
return true;
}
@Override
public int getUid() {
return uid;
}
public String getAuthor() {
return fullName;
}
public boolean hasUsername() {
return userName != null;
}
public String getUsername() throws NoUsernameMessageException {
if(userName == null) throw new NoUsernameMessageException();
return userName;
}
@Override
public String getChatName() {
return chatName;
}
@Override
public boolean isBasicGroup() {
return true;
}
@Override
public boolean isSupergroup() {
return false;
}
@Override
public boolean isChannel() {
return false;
}
@Override
public boolean isPrivate() {
return false;
}
}

View file

@ -0,0 +1,101 @@
package elements.messages;
import elements.exceptions.NoAuthorMessageException;
import elements.exceptions.NoChatNameMessageException;
import elements.exceptions.NoTextMessageException;
import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject;
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
public abstract class Message {
protected Long cid; //chat id
protected Integer mid; //message id
protected Integer uid; //user id
protected String chatType; //chat type
protected String fullName; //author name
protected String userName; //username
protected String chatName; //chat name
protected String text; //the actual message
protected String consoleLog;
public Message(JSONObject message) {
cid = message.getJSONObject("chat").getLong("id");
mid = message.getInt("message_id");
chatType = message.getJSONObject("chat").getString("type");
if (message.has("text"))
text = message.getString("text");
else text = null;
consoleLog = message.toString();
}
public long getCid() {
return cid;
}
public long getMid() {
return mid;
}
public abstract boolean hasAuthor();
public abstract int getUid() throws NoAuthorMessageException;
public abstract String getAuthor() throws NoAuthorMessageException;
protected boolean hasUsername() {
return userName != null;
}
public abstract String getUsername() throws NoUsernameMessageException, NoAuthorMessageException;
private boolean hasText() {
return text != null;
}
public String getText() throws NoTextMessageException {
if(!hasText()) throw new NoTextMessageException();
return text;
}
public static Message getMessage(JSONObject message) throws Exception {
String type = message.getJSONObject("chat").getString("type");
if(type.equals("group"))
return new GroupMessage(message);
if(type.equals("supergroup"))
return new SupergroupMessage(message);
if(type.equals("channel"))
return new ChannelMessage(message);
if(!type.equals("private"))
throw new Exception("Unidentified message.");
return new PrivateMessage(message);
}
public abstract boolean isBasicGroup();
public abstract boolean isSupergroup();
public abstract boolean isChannel();
public abstract boolean isPrivate();
protected boolean hasChatName() {
return chatName != null;
}
public abstract String getChatName() throws NoChatNameMessageException;
public boolean isGroup() {
return isBasicGroup() || isSupergroup();
}
@Override
public String toString() {
return consoleLog;
}
}

View file

@ -0,0 +1,62 @@
package elements.messages;
import elements.exceptions.NoChatNameMessageException;
import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject;
/**
* Created by Guillermo Serrahima on 10/9/16.
*/
public class PrivateMessage extends Message {
public PrivateMessage(JSONObject message) {
super(message);
}
@Override
public boolean hasAuthor() {
return true;
}
@Override
public int getUid() {
return uid;
}
@Override
public String getAuthor() {
return fullName;
}
@Override
public String getUsername() throws NoUsernameMessageException {
if(!hasUsername()) throw new NoUsernameMessageException();
return userName;
}
@Override
public boolean isBasicGroup() {
return false;
}
@Override
public boolean isSupergroup() {
return false;
}
@Override
public boolean isChannel() {
return false;
}
@Override
public boolean isPrivate() {
return true;
}
@Override
public String getChatName() throws NoChatNameMessageException {
if(!hasChatName()) throw new NoChatNameMessageException();
return chatName;
}
}

View file

@ -0,0 +1,23 @@
package elements.messages;
import org.json.JSONObject;
/**
* Created by Guillermo Serrahima on 10/9/16.
*/
public class SupergroupMessage extends GroupMessage {
public SupergroupMessage(JSONObject message) {
super(message);
}
@Override
public boolean isBasicGroup() {
return false;
}
@Override
public boolean isSupergroup() {
return true;
}
}

View file

@ -5,13 +5,17 @@ import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.http.exceptions.UnirestException;
import elements.Chat; import elements.Chat;
import elements.Message; import elements.exceptions.NoAuthorMessageException;
import elements.Persistence; import elements.exceptions.NoTextMessageException;
import elements.exceptions.NoChatNameException; import elements.messages.GroupMessage;
import elements.exceptions.NoUsernameException; import elements.messages.Message;
import elements.exceptions.NoChatNameMessageException;
import elements.exceptions.NoUsernameMessageException;
import elements.messages.PrivateMessage;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import java.security.PrivateKey;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.*; import java.util.*;
@ -19,7 +23,7 @@ import java.util.*;
* Created by Guillermo Serrahima on 4/1/16. * Created by Guillermo Serrahima on 4/1/16.
*/ */
public class Vylbot { public class Geiserbot {
private static final String TOKEN = "267229954:AAHx49MXLmT1nT0QkccrSIzgmRVCQbjbJaQ"; private static final String TOKEN = "267229954:AAHx49MXLmT1nT0QkccrSIzgmRVCQbjbJaQ";
private static final String USERNAME = "geiserpbot"; private static final String USERNAME = "geiserpbot";
private static final String BASE_URL = "https://api.telegram.org/bot" + TOKEN; private static final String BASE_URL = "https://api.telegram.org/bot" + TOKEN;
@ -31,15 +35,14 @@ public class Vylbot {
private static final int HELP_MESSAGE = START_MESSAGE + 1; private static final int HELP_MESSAGE = START_MESSAGE + 1;
private static final int WARNING_UNKNOWN_ERROR = HELP_MESSAGE + 1; private static final int WARNING_UNKNOWN_ERROR = HELP_MESSAGE + 1;
private static final int WARNING_NO_USERNAME = WARNING_UNKNOWN_ERROR + 1; private static final int WARNING_NO_USERNAME = WARNING_UNKNOWN_ERROR + 1;
private static final int WARNING_POLE_BLOCKED = WARNING_NO_USERNAME + 1; private static final int WARNING_NOT_IMPLEMENTED = WARNING_NO_USERNAME + 1;
private static final int WARNING_NOT_IMPLEMENTED = WARNING_POLE_BLOCKED + 1;
private static final int WARNING_NO_GROUP = WARNING_NOT_IMPLEMENTED + 1; private static final int WARNING_NO_GROUP = WARNING_NOT_IMPLEMENTED + 1;
private static final int WARNING_COUNT_END = WARNING_NO_GROUP + 1; private static final int WARNING_COUNT_END = WARNING_NO_GROUP + 1;
private List<String> commands; private List<String> commands;
private Map<Long, Chat> chats; private Map<Long, Chat> chats;
public Vylbot() { public Geiserbot() {
} }
@ -118,17 +121,8 @@ public class Vylbot {
.asJson(); .asJson();
} }
public HttpResponse<JsonNode> getPokeGoStatus() throws UnirestException {
return Unirest.get("http://pokemongosource.com/is-pokemon-go-down/json")
.asJson();
}
//--- bot thinking //--- bot thinking
private boolean askPogeGoStatus() throws UnirestException {
return getPokeGoStatus().getBody().getObject().getBoolean("pokemon-go-up");
}
public void run() throws UnirestException { public void run() throws UnirestException {
int last_upd_id = 0; int last_upd_id = 0;
HttpResponse<JsonNode> response; HttpResponse<JsonNode> response;
@ -154,7 +148,13 @@ public class Vylbot {
private void processMessage(JSONObject message) throws UnirestException { private void processMessage(JSONObject message) throws UnirestException {
//Process message into a nice and cozy java object //Process message into a nice and cozy java object
Message m = new Message(message); Message m = null;
try {
m = Message.getMessage(message);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
//Console log //Console log
printLog(false, m); printLog(false, m);
@ -170,20 +170,23 @@ public class Vylbot {
private void printLog(boolean full_log, Message m) { private void printLog(boolean full_log, Message m) {
if (full_log) System.out.println("\n" + m); if (full_log) System.out.println("\n" + m);
else { else {
String log = "\nMessage "; String log = "\nMessage";
try { try {
log += "received from chat " + m.getChatName(); log += " received from chat " + m.getChatName();
} catch (NoChatNameException e) { } catch (NoChatNameMessageException e) {
log += "received from a private chat "; log += " received from a private chat";
} }
log += " (chat id: " + m.getCid() + ") "; log += " (chat id: " + m.getCid() + ")";
try { try {
log += "by user @" + m.getUsername() + " "; log += " by user @" + m.getUsername();
} catch (NoUsernameException e) { } catch (NoUsernameMessageException e) {
log += "by user "; log += " by user";
} } catch (NoAuthorMessageException ignored) {}
log += "named " + m.getAuthor();
try {
log += " named " + m.getAuthor();
} catch (NoAuthorMessageException ignored) {}
System.out.println(log + "."); System.out.println(log + ".");
} }
@ -192,27 +195,24 @@ public class Vylbot {
//--- Command handling //--- Command handling
private void handleInput(Message m) throws UnirestException { private void handleInput(Message m) throws UnirestException {
if(!m.isChannel()) { try {
if(m.getText().startsWith("/start") && if (!m.isChannel()) {
if (m.getText().startsWith("/start") &&
(!m.getText().substring("/start".length()).startsWith("@") || (!m.getText().substring("/start".length()).startsWith("@") ||
m.getText().substring("/start".length()).startsWith("@" + USERNAME))) m.getText().substring("/start".length()).startsWith("@" + USERNAME)))
handleStart(m.getCid()); handleStart(m.getCid());
if(m.getText().startsWith("/help") && if (m.getText().startsWith("/help") &&
(!m.getText().substring("/help".length()).startsWith("@") || (!m.getText().substring("/help".length()).startsWith("@") ||
m.getText().substring("/help".length()).startsWith("@" + USERNAME))) m.getText().substring("/help".length()).startsWith("@" + USERNAME)))
handleHelp(m.getCid()); handleHelp(m.getCid());
if(m.getText().startsWith("/pokego") && if (m.getText().startsWith("/whoami") &&
(!m.getText().substring("/pokego".length()).startsWith("@") ||
m.getText().substring("/pokego".length()).startsWith("@" + USERNAME)))
handlePokeGoStatus(m.getCid());
if(m.getText().startsWith("/whoami") &&
(!m.getText().substring("/whoami".length()).startsWith("@") || (!m.getText().substring("/whoami".length()).startsWith("@") ||
m.getText().substring("/whoami".length()).startsWith("@" + USERNAME))) m.getText().substring("/whoami".length()).startsWith("@" + USERNAME)))
handleWhoami(m); handleWhoami(m);
} }
} catch (NoTextMessageException ignored) {}
} }
private void handleStart(long chat_id) throws UnirestException { private void handleStart(long chat_id) throws UnirestException {
@ -225,39 +225,35 @@ public class Vylbot {
"/start - Repite el saludo inicial\n" + "/start - Repite el saludo inicial\n" +
"/help - Saca esta lista\n" + "/help - Saca esta lista\n" +
"/whoami - Muestra información visible sobre ti mismo\n" + "/whoami - Muestra información visible sobre ti mismo\n" +
"/pokego - Muestra el status de los servidores de Pokémon Go " +
"(según una web de terceros).\n" +
"\n_GeiserPBot v1.0.0_"; "\n_GeiserPBot v1.0.0_";
sendMessage(chat_id, help, PARSE_MARKDOWN); sendMessage(chat_id, help, PARSE_MARKDOWN);
return; return;
} }
private void handlePokeGoStatus(long chat_id) throws UnirestException {
String status = "Según mis fuentes, ";
if(askPogeGoStatus())
status += "Pokémon Go funciona";
else
status += "los pokeservidores tienen un pokeproblema";
sendMessage(chat_id, status);
}
private void handleWhoami(Message m) throws UnirestException { private void handleWhoami(Message m) throws UnirestException {
String s = "Eres " + m.getAuthor(); String s = "Estamos en";
try { try {
s+= ", con nombre de usuario @" + m.getUsername(); s += " el chat " + m.getChatName();
} catch (NoUsernameException ignored) {} } catch (NoChatNameMessageException e) {
s += " e id de usuario " + m.getUid(); s += " un chat";
s += ", en "; if(m.isPrivate()) s+= " privado";
try {
s+= "el chat " + m.getChatName();
} catch (NoChatNameException e) {
s+= "un chat privado";
} }
s += " de id " + m.getCid() + ".\n\n"; s += " de id " + m.getCid() + ".\n";
s += "En el PC que me mantiene, la fecha actual es " + LocalDate.now() +
try {
s += "Eres " + m.getAuthor();
try {
s += ", con nombre de usuario @" + m.getUsername();
} catch (NoUsernameMessageException ignored) {}
s += " e id de usuario " + m.getUid() + ".\n";
} catch (NoAuthorMessageException ignored) {}
s += "\nEn el PC que me mantiene, la fecha actual es " + LocalDate.now() +
" en el formato ISO-8601."; " en el formato ISO-8601.";
sendMessage(m.getCid(), s); sendMessage(m.getCid(), s);
} }
@ -289,10 +285,7 @@ public class Vylbot {
case WARNING_NO_USERNAME: case WARNING_NO_USERNAME:
return "No tienes nombre de usuario. Regístrate con uno en la " + return "No tienes nombre de usuario. Regístrate con uno en la " +
"configuración de Telegram para poder participar."; "configuración de Telegram para poder utilizarme.";
case WARNING_POLE_BLOCKED:
return "La pole de hoy ya ha sido conseguida. Vuélvelo a intentar mañana.";
default: return "Entrada incorrecta."; default: return "Entrada incorrecta.";
} }

View file

@ -8,7 +8,7 @@ import com.mashape.unirest.http.exceptions.UnirestException;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
Vylbot bot = new Vylbot(); Geiserbot bot = new Geiserbot();
System.out.println("The Bot @" + bot.getUsername() + " awakens."); System.out.println("The Bot @" + bot.getUsername() + " awakens.");
System.out.println("Bot running."); System.out.println("Bot running.");