diff --git a/.idea/misc.xml b/.idea/misc.xml
index 1577011..e1a5887 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -41,13 +41,6 @@
-
-
-
diff --git a/src/elements/Chat.java b/src/elements/Chat.java
index 91e3519..52128c4 100644
--- a/src/elements/Chat.java
+++ b/src/elements/Chat.java
@@ -1,8 +1,9 @@
package elements;
+import elements.exceptions.ReadErrorListException;
+
import java.time.LocalDate;
-import java.time.ZoneId;
import java.util.*;
/**
@@ -17,32 +18,29 @@ public class Chat {
public static final String MODE_COLORS = "mode_colors";
public static final String MODE_FAR_WEST = "mode_far_west";
- private Map users;
- private LocalDate lastPole;
- private String poleWinner;
- private String nextMode;
+ private String name;
+ private Map> lists;
public Chat() {
- users = new HashMap();
- lastPole = null;
- poleWinner = null;
- nextMode = null;
+ lists = new HashMap>();
+ name = null;
}
- public boolean exists(String user) {
- return users.containsKey(user);
+ public Chat(String n) {
+ lists = new HashMap>();
+ name = n;
}
- public boolean isModeChosen() {
- return (nextMode != null);
+ public boolean exists(String list) {
+ return lists.containsKey(list);
}
- public void add(String user) {
- users.put(user, 0);
+ public void add(String listName, ArrayList list) {
+ lists.put(listName, list);
}
- public void add(String user, int p) {
- users.put(user, p);
+ public void add(String list) {
+ lists.put(list, new ArrayList());
}
/*
@@ -54,113 +52,90 @@ public class Chat {
}
users.replace(user, users.get(user)+1);
- Date d = new Date((new Long(date))*1000);
- lastPole = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
+
poleWinner = user;
}
*/
- public void choseMode(String mode) {
- nextMode = mode;
- }
+ public String printList(String list) {
+ ArrayList l = lists.get(list);
+ String s = list + ":\n\n";
- public boolean availablePole() {
- LocalDate today = LocalDate.now();
-
- return (lastPole == null || today.isAfter(lastPole));
- }
-
- public String getRanking() {
- List> top;
- String ranking = "";
- Map.Entry[] ts = new Map.Entry[users.size()];
-
- top = Arrays.asList((users.entrySet().toArray(ts)));
- top.sort(new UserComparator());
-
- for(int i = 0; i < top.size(); i++) {
- ranking += "[" + (i+1) + ".] " + getUsername(top.get(i)) + ": ";
- ranking += getPoles(top.get(i)) + "\n";
+ for(int i = 0; i < l.size(); i++) {
+ s += l.get(i) + "\n";
}
- return ranking;
+ return s.trim();
}
- public String toTxt() {
- String s = DATE_TAG;
- if(lastPole == null) s += "null\n";
- else s += lastPole + "\n";
+ public String orderAlphabetically(String list) {
+ ArrayList toOrder = lists.get(list);
- s += WINNER_TAG;
- if(poleWinner == null) s += "null\n";
- else s += poleWinner + "\n";
+ toOrder.sort(new ChatListItemComparator());
- Iterator it = users.entrySet().iterator();
+ return "Lista ordenada.\n" + printList(list);
+ }
+
+ public ArrayList> saveLists() {
+ ArrayList> listDocs = new ArrayList>();
+ List lines;
+
+ Iterator it = lists.entrySet().iterator();
+
+ if(name != null) {
+ lines = new ArrayList();
+
+ lines.add("#Chat name:");
+ lines.add("#" + name);
+
+ listDocs.add(lines);
+ }
while(it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- s += getUsername(entry) + ":" + getPoles(entry) + "\n";
- }
+ lines = new ArrayList();
- return s;
- }
+ Map.Entry> entry = (Map.Entry>) it.next();
+ lines.add("#List name:");
+ lines.add("#" + entry.getKey());
- public static Chat fromTxt(List lines) {
- Chat c = new Chat();
- int i = 0;
- System.out.println("Reading " + lines.get(i));
+ ArrayList list = entry.getValue();
- if(lines.get(i).startsWith(DATE_TAG)) {
- System.out.println("Reading " + lines.get(i));
- String pole = lines.get(i).substring(DATE_TAG.length());
- if(!pole.equals("null")) {
- String[] reading = pole.split("-");
- LocalDate poleDate = LocalDate.of(Integer.parseInt(reading[0]),
- Integer.parseInt(reading[1]), Integer.parseInt(reading[2]));
- c.setPole(poleDate);
+ for(int i = 0; i < list.size(); i++) {
+ lines.add(list.get(i).saveItem());
}
- i++;
+
+ listDocs.add(lines);
}
- if(lines.get(i).startsWith(WINNER_TAG)) {
- System.out.println("Reading " + lines.get(i));
- String winner = lines.get(i).substring(WINNER_TAG.length());
- c.setWinner(winner);
- i++;
+ return listDocs;
+ }
+
+ public void loadList(String listName, List lines) throws ReadErrorListException {
+ ArrayList list = new ArrayList();
+
+ for(int i = 0; i < lines.size(); i++) {
+ //Comprueba si la línea es un comentario.
+ if(lines.get(i).startsWith("#") || lines.get(i).length() < 1) {
+ //do nothing
+ }
+ //Comprueba si la línea es un comentario. (Windows)
+ else if(lines.get(i).startsWith("\uFEFF#")) {
+ //do nothing
+ }
+ else {
+ System.out.println("Reading " + lines.get(i));
+ String[] reading = lines.get(i).split(";");
+ list.add(new ChatListItem(reading[0], Integer.parseInt(reading[1])));
+ }
}
-
- for(; i < lines.size(); i++) {
- System.out.println("Reading " + lines.get(i));
- String[] reading = lines.get(i).split(":");
- c.add(reading[0],Integer.parseInt(reading[1]));
- }
-
- return c;
- }
-
- private void setPole(LocalDate d) {
- lastPole = d;
- }
-
- private void setWinner(String poleWinner) {
- this.poleWinner = poleWinner;
- }
-
- private String getUsername(Map.Entry e) {
- return e.getKey();
- }
-
- private int getPoles(Map.Entry e) {
- return e.getValue();
}
}
-class UserComparator implements Comparator {
+class ChatListItemComparator implements Comparator {
@Override
- public int compare(Map.Entry entr1, Map.Entry entr2) {
-
- return ((Integer) entr2.getValue()).compareTo((Integer) entr1.getValue());
+ public int compare(ChatListItem entr1, ChatListItem entr2) {
+ return entr1.compareTo(entr2);
}
}
diff --git a/src/elements/ChatListItem.java b/src/elements/ChatListItem.java
new file mode 100644
index 0000000..911e1d5
--- /dev/null
+++ b/src/elements/ChatListItem.java
@@ -0,0 +1,40 @@
+package elements;
+
+import elements.exceptions.ReadErrorListException;
+
+/**
+ * Created by Guillermo Serrahima on 10/9/16.
+ */
+public class ChatListItem {
+ private String name;
+ private Integer value;
+
+ private ChatListItem() {
+
+ }
+
+ public ChatListItem(String name, int value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public ChatListItem(String parse) throws ReadErrorListException {
+ String[] reading = parse.split(";");
+ if(reading.length > 2) throw new ReadErrorListException("Unidentified item.");
+ this.name = reading[0];
+ this.value = Integer.parseInt(reading[1]);
+ }
+
+ public int compareTo(ChatListItem c) {
+ return name.compareTo(c.name);
+ }
+
+ @Override
+ public String toString() {
+ return name + ": " + value;
+ }
+
+ public String saveItem() {
+ return name + ";" + value;
+ }
+}
diff --git a/src/elements/Persistence.java b/src/elements/Persistence.java
index 402b6cd..1c3b84b 100644
--- a/src/elements/Persistence.java
+++ b/src/elements/Persistence.java
@@ -1,10 +1,14 @@
package elements;
+import elements.exceptions.ReadErrorChatException;
+import elements.exceptions.SaveErrorChatException;
+
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -25,25 +29,33 @@ public class Persistence {
return persistence;
}
- /*
- public void saveChat(long chat_id, Chat c) throws SaveErrorException {
- try {
- List lines = Arrays.asList(c.toTxt().split("\n"));
- Path file = Paths.get("chats/" + chat_id + ".txt");
- if (!Files.exists(file.getParent()))
- Files.createDirectories(file.getParent());
- Files.write(file, lines, Charset.forName("UTF-8"));
+ public void saveChat(long chat_id, Chat c) throws SaveErrorChatException {
+ try {
+ ArrayList> lists = c.saveLists();
+ List lines;
+
+ for(int i = 0; i < lists.size(); i++) {
+ lines = lists.get(i);
+ String filename = lines.get(1).substring("#".length());
+
+ if(lines.get(0).equals("#Chat name:")) {
+ filename = "chat_name";
+ }
+ Path file = Paths.get("geiserFiles/" + chat_id + "/lists/" + filename + ".txt");
+ if (!Files.exists(file.getParent()))
+ Files.createDirectories(file.getParent());
+ Files.write(file, lines, Charset.forName("UTF-8"));
+ }
} catch (IOException e) {
- throw new SaveErrorException(chat_id);
+ throw new SaveErrorChatException(e);
}
return;
}
- */
/*
- public HashMap readChats() throws ReadErrorException {
+ public HashMap readChats() throws ReadErrorChatException {
HashMap chats = new HashMap();
if(!Files.exists(Paths.get("chats/"))) return chats;
@@ -51,7 +63,7 @@ public class Persistence {
try {
String filename;
Chat chat;
- List files = Files.walk(Paths.get("chats/"), 1).collect(Collectors.toList());
+ List files = Files.walk(Paths.get("geiserFiles/"), 1).collect(Collectors.toList());
Path file;
List lines;
@@ -68,10 +80,11 @@ public class Persistence {
}
} catch (IOException e) {
e.printStackTrace();
- throw new ReadErrorException();
+ throw new ReadErrorChatException(e);
}
return chats;
}
*/
+
}
diff --git a/src/elements/exceptions/MessageException.java b/src/elements/exceptions/MessageException.java
index 9ff135a..e9bf9b1 100644
--- a/src/elements/exceptions/MessageException.java
+++ b/src/elements/exceptions/MessageException.java
@@ -3,7 +3,7 @@ package elements.exceptions;
/**
* Created by Guillermo Serrahima on 10/9/16.
*/
-public abstract class MessageException extends Exception {
+public class MessageException extends Exception {
public MessageException(String s) {
super(s);
}
diff --git a/src/elements/exceptions/NoUsernameMessageException.java b/src/elements/exceptions/NoUsernameMessageException.java
index e105d71..211269c 100644
--- a/src/elements/exceptions/NoUsernameMessageException.java
+++ b/src/elements/exceptions/NoUsernameMessageException.java
@@ -3,7 +3,7 @@ package elements.exceptions;
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
-public class NoUsernameMessageException extends NoAuthorMessageException {
+public class NoUsernameMessageException extends MessageException {
public NoUsernameMessageException() {
super("The user has no username.");
}
diff --git a/src/elements/exceptions/ReadErrorChatException.java b/src/elements/exceptions/ReadErrorChatException.java
new file mode 100644
index 0000000..60622ec
--- /dev/null
+++ b/src/elements/exceptions/ReadErrorChatException.java
@@ -0,0 +1,16 @@
+package elements.exceptions;
+
+import java.io.IOException;
+
+/**
+ * Created by Guillermo Serrahima on 10/9/16.
+ */
+public class ReadErrorChatException extends IOException {
+ public ReadErrorChatException(String s) {
+ super(s);
+ }
+
+ public ReadErrorChatException(IOException e) {
+ super(e);
+ }
+}
diff --git a/src/elements/exceptions/ReadErrorListException.java b/src/elements/exceptions/ReadErrorListException.java
new file mode 100644
index 0000000..bebba9e
--- /dev/null
+++ b/src/elements/exceptions/ReadErrorListException.java
@@ -0,0 +1,12 @@
+package elements.exceptions;
+
+import java.io.IOException;
+
+/**
+ * Created by Guillermo Serrahima on 10/9/16.
+ */
+public class ReadErrorListException extends Exception {
+ public ReadErrorListException(String s) {
+ super(s);
+ }
+}
diff --git a/src/elements/exceptions/SaveErrorChatException.java b/src/elements/exceptions/SaveErrorChatException.java
new file mode 100644
index 0000000..c6b9863
--- /dev/null
+++ b/src/elements/exceptions/SaveErrorChatException.java
@@ -0,0 +1,16 @@
+package elements.exceptions;
+
+import java.io.IOException;
+
+/**
+ * Created by Guillermo Serrahima on 10/9/16.
+ */
+public class SaveErrorChatException extends IOException {
+ public SaveErrorChatException(String s) {
+ super(s);
+ }
+
+ public SaveErrorChatException(IOException e) {
+ super(e);
+ }
+}
diff --git a/src/elements/messages/ChannelMessage.java b/src/elements/messages/ChannelMessage.java
index 950c044..18d95c2 100644
--- a/src/elements/messages/ChannelMessage.java
+++ b/src/elements/messages/ChannelMessage.java
@@ -54,14 +54,6 @@ public class ChannelMessage extends Message {
consoleLog = message.toString();
}
- public long getCid() {
- return cid;
- }
-
- public long getMid() {
- return mid;
- }
-
public String getChatType() {
return chatType;
}
diff --git a/src/elements/messages/GroupMessage.java b/src/elements/messages/GroupMessage.java
index e6e9d42..33066f7 100644
--- a/src/elements/messages/GroupMessage.java
+++ b/src/elements/messages/GroupMessage.java
@@ -1,5 +1,6 @@
package elements.messages;
+import elements.exceptions.NoTextMessageException;
import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject;
@@ -7,6 +8,10 @@ import org.json.JSONObject;
* Created by Guillermo Serrahima on 10/8/16.
*/
public class GroupMessage extends Message {
+ //Event ID constants
+ public static final int USER_JOINED = 1;
+ public static final int USER_LEFT = 2;
+
private Long cid; //chat id
private Integer mid; //message id
private Integer uid; //user id
@@ -16,12 +21,15 @@ public class GroupMessage extends Message {
private String chatName; //chat name
private String text; //the actual message
private String consoleLog;
+ private Integer event;
public GroupMessage(JSONObject message) {
super(message);
fullName = message.getJSONObject("from").getString("first_name");
uid = message.getJSONObject("from").getInt("id");
+ event = 0;
+ text = null;
//Check for user last name
if (message.getJSONObject("from").has("last_name"))
@@ -39,19 +47,25 @@ public class GroupMessage extends Message {
if (message.has("text"))
text = message.getString("text");
- else text = null;
+ else {
+ if (message.has("new_chat_participant")) {
+ event = USER_JOINED;
+ if(message.getJSONObject("new_chat_participant").has("username"))
+ text = "@" + message.getJSONObject("new_chat_participant").getString("username");
+ else text = message.getJSONObject("new_chat_participant").getString("first_name");
+ }
+
+ else if (message.has("left_chat_participant")) {
+ event = USER_LEFT;
+ if(message.getJSONObject("left_chat_participant").has("username"))
+ text = "@" + message.getJSONObject("left_chat_participant").getString("username");
+ else text = message.getJSONObject("left_chat_participant").getString("first_name");
+ }
+ }
consoleLog = message.toString();
}
- public long getCid() {
- return cid;
- }
-
- public long getMid() {
- return mid;
- }
-
@Override
public boolean hasAuthor() {
return true;
@@ -75,6 +89,15 @@ public class GroupMessage extends Message {
return userName;
}
+ public boolean hasText() {
+ return event != 0 || text != null;
+ }
+
+ public String getText() throws NoTextMessageException {
+ if(text == null) throw new NoTextMessageException();
+ return text;
+ }
+
@Override
public String getChatName() {
return chatName;
@@ -99,4 +122,21 @@ public class GroupMessage extends Message {
public boolean isPrivate() {
return false;
}
+
+ public boolean isEvent() {
+ System.out.println("Event is " + event);
+ try {
+ return event.intValue() != 0;
+ } catch (NullPointerException e) {
+ return false;
+ }
+ }
+
+ public boolean userLeft() {
+ return event.intValue() == USER_LEFT;
+ }
+
+ public boolean userJoined() {
+ return event.intValue() == USER_JOINED;
+ }
}
diff --git a/src/elements/messages/Message.java b/src/elements/messages/Message.java
index 35f78ec..33cdb14 100644
--- a/src/elements/messages/Message.java
+++ b/src/elements/messages/Message.java
@@ -1,11 +1,11 @@
package elements.messages;
-import elements.exceptions.NoAuthorMessageException;
-import elements.exceptions.NoChatNameMessageException;
-import elements.exceptions.NoTextMessageException;
-import elements.exceptions.NoUsernameMessageException;
+import elements.exceptions.*;
import org.json.JSONObject;
+import java.time.ZoneId;
+import java.util.Date;
+
/**
* Created by Guillermo Serrahima on 10/8/16.
*/
@@ -18,6 +18,7 @@ public abstract class Message {
protected String userName; //username
protected String chatName; //chat name
protected String text; //the actual message
+ protected Date timestamp;
protected String consoleLog;
public Message(JSONObject message) {
@@ -30,13 +31,15 @@ public abstract class Message {
else text = null;
consoleLog = message.toString();
+
+ timestamp = new Date(new Long(message.getInt("date"))*1000);
}
public long getCid() {
return cid;
}
- public long getMid() {
+ public int getMid() {
return mid;
}
@@ -52,7 +55,7 @@ public abstract class Message {
public abstract String getUsername() throws NoUsernameMessageException, NoAuthorMessageException;
- private boolean hasText() {
+ public boolean hasText() {
return text != null;
}
@@ -61,7 +64,7 @@ public abstract class Message {
return text;
}
- public static Message getMessage(JSONObject message) throws Exception {
+ public static Message getMessage(JSONObject message) throws MessageException {
String type = message.getJSONObject("chat").getString("type");
if(type.equals("group"))
@@ -71,7 +74,7 @@ public abstract class Message {
if(type.equals("channel"))
return new ChannelMessage(message);
if(!type.equals("private"))
- throw new Exception("Unidentified message.");
+ throw new MessageException("Unidentified message.");
return new PrivateMessage(message);
}
@@ -88,7 +91,7 @@ public abstract class Message {
return chatName != null;
}
- public abstract String getChatName() throws NoChatNameMessageException;
+ public abstract String getChatName();
public boolean isGroup() {
return isBasicGroup() || isSupergroup();
@@ -98,4 +101,12 @@ public abstract class Message {
public String toString() {
return consoleLog;
}
+
+ public String getTimestamp() {
+ return String.valueOf(timestamp);
+ }
+
+ public String getDate() {
+ return String.valueOf(timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
+ }
}
diff --git a/src/elements/messages/PrivateMessage.java b/src/elements/messages/PrivateMessage.java
index a3512f6..68b9cdd 100644
--- a/src/elements/messages/PrivateMessage.java
+++ b/src/elements/messages/PrivateMessage.java
@@ -27,7 +27,7 @@ public class PrivateMessage extends Message {
//Get group chat name
if (message.getJSONObject("chat").has("title"))
chatName = message.getJSONObject("chat").getString("title");
- else chatName = null;
+ else chatName = message.getJSONObject("from").getString("first_name");
if (message.has("text"))
text = message.getString("text");
@@ -78,8 +78,7 @@ public class PrivateMessage extends Message {
}
@Override
- public String getChatName() throws NoChatNameMessageException {
- if(!hasChatName()) throw new NoChatNameMessageException();
+ public String getChatName() {
return chatName;
}
}
diff --git a/src/main/Geiserbot.java b/src/main/Geiserbot.java
index 57167dc..523de9b 100644
--- a/src/main/Geiserbot.java
+++ b/src/main/Geiserbot.java
@@ -5,18 +5,19 @@ import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import elements.Chat;
-import elements.exceptions.NoAuthorMessageException;
-import elements.exceptions.NoTextMessageException;
+import elements.Persistence;
+import elements.exceptions.*;
+import elements.messages.ChannelMessage;
import elements.messages.GroupMessage;
import elements.messages.Message;
-import elements.exceptions.NoChatNameMessageException;
-import elements.exceptions.NoUsernameMessageException;
import elements.messages.PrivateMessage;
import org.json.JSONArray;
import org.json.JSONObject;
import java.security.PrivateKey;
+import java.security.acl.Group;
import java.time.LocalDate;
+import java.time.ZoneId;
import java.util.*;
/**
@@ -25,7 +26,7 @@ import java.util.*;
public class Geiserbot {
private static final String TOKEN = "267229954:AAHx49MXLmT1nT0QkccrSIzgmRVCQbjbJaQ";
- private static final String USERNAME = "geiserpbot";
+ private static final String USERNAME = "gserbot";
private static final String BASE_URL = "https://api.telegram.org/bot" + TOKEN;
private static final String PARSE_MARKDOWN = "Markdown";
private static final String PARSE_HTML = "HTML";
@@ -39,11 +40,11 @@ public class Geiserbot {
private static final int WARNING_NO_GROUP = WARNING_NOT_IMPLEMENTED + 1;
private static final int WARNING_COUNT_END = WARNING_NO_GROUP + 1;
- private List commands;
+ //private List commands;
private Map chats;
public Geiserbot() {
-
+ chats = new HashMap();
}
public String getUsername() {
@@ -151,20 +152,16 @@ public class Geiserbot {
Message m = null;
try {
m = Message.getMessage(message);
- } catch (Exception e) {
+ } catch (MessageException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
//Console log
- printLog(false, m);
+ printLog(true, m);
//Actually read the message
- if (message.has("text")) {
- String text = message.getString("text");
- handleInput(m);
- return;
- }
+ handleInput(m);
}
private void printLog(boolean full_log, Message m) {
@@ -172,11 +169,9 @@ public class Geiserbot {
else {
String log = "\nMessage";
- try {
- log += " received from chat " + m.getChatName();
- } catch (NoChatNameMessageException e) {
- log += " received from a private chat";
- }
+ if(m.isPrivate()) log += " received from a private chat";
+ else log += " received from chat " + m.getChatName();
+
log += " (chat id: " + m.getCid() + ")";
try {
log += " by user @" + m.getUsername();
@@ -195,26 +190,72 @@ public class Geiserbot {
//--- Command handling
private void handleInput(Message m) throws UnirestException {
+ if (m.isChannel())
+ handleInputChannel((ChannelMessage) m);
+
+ else if (m.isGroup())
+ handleInputGroup((GroupMessage) m);
+
+ else if (m.isPrivate())
+ handleInputPrivate((PrivateMessage) m);
+ }
+
+ private void handleInputGroup(GroupMessage m) throws UnirestException {
try {
- if (!m.isChannel()) {
- if (m.getText().startsWith("/start") &&
- (!m.getText().substring("/start".length()).startsWith("@") ||
- m.getText().substring("/start".length()).startsWith("@" + USERNAME)))
- handleStart(m.getCid());
-
- if (m.getText().startsWith("/help") &&
- (!m.getText().substring("/help".length()).startsWith("@") ||
- m.getText().substring("/help".length()).startsWith("@" + USERNAME)))
- handleHelp(m.getCid());
-
- if (m.getText().startsWith("/whoami") &&
- (!m.getText().substring("/whoami".length()).startsWith("@") ||
- m.getText().substring("/whoami".length()).startsWith("@" + USERNAME)))
- handleWhoami(m);
+ if (m.isEvent()) {
+ System.out.println("\nDetected group event.");
+ handleGroupEvent(m);
}
+
+ else if (m.getText().startsWith("/start") &&
+ (!m.getText().substring("/start".length()).startsWith("@") ||
+ m.getText().substring("/start".length()).startsWith("@" + USERNAME)))
+ handleStart(m.getCid());
+
+ else if (m.getText().startsWith("/help") &&
+ (!m.getText().substring("/help".length()).startsWith("@") ||
+ m.getText().substring("/help".length()).startsWith("@" + USERNAME)))
+ handleHelp(m.getCid());
+
+ else if (m.getText().startsWith("/whoami") &&
+ (!m.getText().substring("/whoami".length()).startsWith("@") ||
+ m.getText().substring("/whoami".length()).startsWith("@" + USERNAME)))
+ handleWhoami(m);
+
+ else if (m.getText().startsWith("/list") &&
+ (!m.getText().substring("/list".length()).startsWith("@") ||
+ m.getText().substring("/list".length()).startsWith("@" + USERNAME)))
+ handleList(m);
} catch (NoTextMessageException ignored) {}
}
+ private void handleInputPrivate(PrivateMessage m) throws UnirestException {
+ try {
+ if (m.getText().startsWith("/start") &&
+ (!m.getText().substring("/start".length()).startsWith("@") ||
+ m.getText().substring("/start".length()).startsWith("@" + USERNAME)))
+ handleStart(m.getCid());
+
+ else if (m.getText().startsWith("/help") &&
+ (!m.getText().substring("/help".length()).startsWith("@") ||
+ m.getText().substring("/help".length()).startsWith("@" + USERNAME)))
+ handleHelp(m.getCid());
+
+ else if (m.getText().startsWith("/whoami") &&
+ (!m.getText().substring("/whoami".length()).startsWith("@") ||
+ m.getText().substring("/whoami".length()).startsWith("@" + USERNAME)))
+ handleWhoami(m);
+
+ else if (m.getText().startsWith("/list") &&
+ (!m.getText().substring("/list".length()).startsWith("@") ||
+ m.getText().substring("/list".length()).startsWith("@" + USERNAME)))
+ handleList(m);
+ } catch (NoTextMessageException ignored) {}
+ }
+
+ private void handleInputChannel(ChannelMessage m) throws UnirestException {
+ }
+
private void handleStart(long chat_id) throws UnirestException {
sendMessage(chat_id, "Hola. Soy el bot personal de Guillermo Serrahima.");
return;
@@ -225,52 +266,103 @@ public class Geiserbot {
"/start - Repite el saludo inicial\n" +
"/help - Saca esta lista\n" +
"/whoami - Muestra información visible sobre ti mismo\n" +
- "\n_GeiserPBot v1.0.0_";
+ "/list [nombre de la lista] - Permite crear, mostrar o " +
+ "modificar una lista\n";
- sendMessage(chat_id, help, PARSE_MARKDOWN);
- return;
+ sendMessage(chat_id, help.trim());
+ sendMessage(chat_id, "_" + myName() + " v1.0.0_", PARSE_MARKDOWN);
}
private void handleWhoami(Message m) throws UnirestException {
String s = "Estamos en";
- try {
- s += " el chat " + m.getChatName();
- } catch (NoChatNameMessageException e) {
- s += " un chat";
- if(m.isPrivate()) s+= " privado";
- }
- s += " de id " + m.getCid() + ".\n";
+ if(m.isPrivate()) s+= " un chat privado";
+ else s += " el chat " + m.getChatName();
+
+ s += " de ID " + m.getCid() + ".\n";
try {
- s += "Eres " + m.getAuthor();
+ s += "Eres " + m.getAuthor() + ", con";
try {
- s += ", con nombre de usuario @" + m.getUsername();
+ s += " nombre de usuario @" + m.getUsername() +" e";
} catch (NoUsernameMessageException ignored) {}
- s += " e id de usuario " + m.getUid() + ".\n";
+ s += " ID de usuario " + m.getUid() + ".\n";
} catch (NoAuthorMessageException ignored) {}
s += "En el PC que me mantiene, la fecha actual es " + LocalDate.now() +
- " en el formato ISO-8601.";
+ " en el formato ISO-8601.\n";
- sendMessage(m.getCid(), s);
+ s+= "Tu mensaje tiene hora de " + m.getTimestamp() + "\n";
+
+ replyMessage(m.getCid(), m.getMid(), s.trim());
}
- private boolean exists(long chat_id, String user) {
- return chats.containsKey(chat_id) && chats.get(chat_id).exists(user);
- }
-
- /*
- private void saveChat(long chat_id) throws SaveErrorException {
- try {
- Persistence.getInstance().saveChat(chat_id, chats.get(chat_id));
- } catch (SaveErrorException e) {
- e.printStackTrace();
- throw e;
+ private void handleGroupEvent(GroupMessage m) throws NoTextMessageException, UnirestException {
+ System.out.println("Bot @" + USERNAME + " detects event. Joining: " + m.userJoined() + "; Leaving: " + m.userLeft());
+ if(m.userJoined()) System.out.println("JOINING");
+ if(m.userJoined()) {
+ System.out.println("Bot @" + USERNAME + " detects new chat participant " + m.getText());
+ if(m.getText().equals("@" + USERNAME)) handleStart(m.getCid());
+ }
+ else if(m.userLeft()) {
+ System.out.println("LEAVING");
+ System.out.println("Bot @" + USERNAME + " detects leaving chat participant " + m.getText());
}
}
- */
+
+ private void handleList(GroupMessage m) throws UnirestException, NoTextMessageException {
+ String[] reading = m.getText().split(" ", 2);
+ if(reading.length < 2) {
+ sendMessage(m.getCid(), "Formato incorrecto. " +
+ "Debes poner un espacio entre el comando /list y el nombre de la lista.");
+ return;
+ }
+ String list = reading[0];
+
+ if(!exists(m.getCid()))
+ chats.put(m.getCid(), new Chat(m.getChatName()));
+ if(!exists(m.getCid(), list))
+ chats.get(m.getCid()).add(list);
+
+ sendMessage(m.getCid(), getWarning(WARNING_NOT_IMPLEMENTED));
+ }
+
+ private void handleList(PrivateMessage m) throws UnirestException, NoTextMessageException {
+ String[] reading = m.getText().split(" ", 2);
+ if(reading.length < 2) {
+ sendMessage(m.getCid(), "Formato incorrecto. " +
+ "Debes poner un espacio entre el comando /list y el nombre de la lista.");
+ return;
+ }
+ String list = reading[0];
+
+ if(!exists(m.getCid()))
+ chats.put(m.getCid(), new Chat(m.getChatName()));
+ if(!exists(m.getCid(), list)) {
+ try {
+ chats.get(m.getCid()).add(list);
+ saveChat(m.getCid());
+ } catch (SaveErrorChatException e) {
+ sendMessage(m.getCid(), "Ha habido un error guardando la lista.");
+ return;
+ }
+ }
+
+ sendMessage(m.getCid(), getWarning(WARNING_NOT_IMPLEMENTED));
+ }
+
+ private boolean exists(long chat_id) {
+ return chats.containsKey(chat_id);
+ }
+
+ private boolean exists(long chat_id, String list) {
+ return chats.containsKey(chat_id) && chats.get(chat_id).exists(list);
+ }
+
+ private void saveChat(long chat_id) throws SaveErrorChatException {
+ Persistence.getInstance().saveChat(chat_id, chats.get(chat_id));
+ }
private String getWarning(int warning_id) {
switch (warning_id) {