Added some save functionality in Persistence layer.

Added some finishing touches to the Message classes.
Integrated some event support in input handling.
This commit is contained in:
vylion 2016-10-09 16:34:36 +02:00
parent 9c0d8c0fe0
commit ef2ea921cc
14 changed files with 410 additions and 211 deletions

View file

@ -41,13 +41,6 @@
<component name="EntryPointsManager"> <component name="EntryPointsManager">
<entry_points version="2.0" /> <entry_points version="2.0" />
</component> </component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="mavenHome" value="Bundled (Maven 3)" />
</MavenGeneralSettings>
</option>
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false"> <component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Remove" />

View file

@ -1,8 +1,9 @@
package elements; package elements;
import elements.exceptions.ReadErrorListException;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*; import java.util.*;
/** /**
@ -17,32 +18,29 @@ public class Chat {
public static final String MODE_COLORS = "mode_colors"; public static final String MODE_COLORS = "mode_colors";
public static final String MODE_FAR_WEST = "mode_far_west"; public static final String MODE_FAR_WEST = "mode_far_west";
private Map<String, Integer> users; private String name;
private LocalDate lastPole; private Map<String, ArrayList<ChatListItem>> lists;
private String poleWinner;
private String nextMode;
public Chat() { public Chat() {
users = new HashMap<String, Integer>(); lists = new HashMap<String, ArrayList<ChatListItem>>();
lastPole = null; name = null;
poleWinner = null;
nextMode = null;
} }
public boolean exists(String user) { public Chat(String n) {
return users.containsKey(user); lists = new HashMap<String, ArrayList<ChatListItem>>();
name = n;
} }
public boolean isModeChosen() { public boolean exists(String list) {
return (nextMode != null); return lists.containsKey(list);
} }
public void add(String user) { public void add(String listName, ArrayList<ChatListItem> list) {
users.put(user, 0); lists.put(listName, list);
} }
public void add(String user, int p) { public void add(String list) {
users.put(user, p); lists.put(list, new ArrayList<ChatListItem>());
} }
/* /*
@ -54,113 +52,90 @@ public class Chat {
} }
users.replace(user, users.get(user)+1); users.replace(user, users.get(user)+1);
Date d = new Date((new Long(date))*1000);
lastPole = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
poleWinner = user; poleWinner = user;
} }
*/ */
public void choseMode(String mode) { public String printList(String list) {
nextMode = mode; ArrayList<ChatListItem> l = lists.get(list);
String s = list + ":\n\n";
for(int i = 0; i < l.size(); i++) {
s += l.get(i) + "\n";
} }
public boolean availablePole() { return s.trim();
LocalDate today = LocalDate.now();
return (lastPole == null || today.isAfter(lastPole));
} }
public String getRanking() { public String orderAlphabetically(String list) {
List<Map.Entry<String, Integer>> top; ArrayList<ChatListItem> toOrder = lists.get(list);
String ranking = "";
Map.Entry<String, Integer>[] ts = new Map.Entry[users.size()];
top = Arrays.asList((users.entrySet().toArray(ts))); toOrder.sort(new ChatListItemComparator());
top.sort(new UserComparator());
for(int i = 0; i < top.size(); i++) { return "Lista ordenada.\n" + printList(list);
ranking += "[" + (i+1) + ".] " + getUsername(top.get(i)) + ": ";
ranking += getPoles(top.get(i)) + "\n";
} }
return ranking; public ArrayList<List<String>> saveLists() {
ArrayList<List<String>> listDocs = new ArrayList<List<String>>();
List<String> lines;
Iterator it = lists.entrySet().iterator();
if(name != null) {
lines = new ArrayList<String>();
lines.add("#Chat name:");
lines.add("#" + name);
listDocs.add(lines);
} }
public String toTxt() {
String s = DATE_TAG;
if(lastPole == null) s += "null\n";
else s += lastPole + "\n";
s += WINNER_TAG;
if(poleWinner == null) s += "null\n";
else s += poleWinner + "\n";
Iterator it = users.entrySet().iterator();
while(it.hasNext()) { while(it.hasNext()) {
Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next(); lines = new ArrayList<String>();
s += getUsername(entry) + ":" + getPoles(entry) + "\n";
Map.Entry<String, ArrayList<ChatListItem>> entry = (Map.Entry<String, ArrayList<ChatListItem>>) it.next();
lines.add("#List name:");
lines.add("#" + entry.getKey());
ArrayList<ChatListItem> list = entry.getValue();
for(int i = 0; i < list.size(); i++) {
lines.add(list.get(i).saveItem());
} }
return s; listDocs.add(lines);
} }
public static Chat fromTxt(List<String> lines) { return listDocs;
Chat c = new Chat(); }
int i = 0;
public void loadList(String listName, List<String> lines) throws ReadErrorListException {
ArrayList<ChatListItem> list = new ArrayList<ChatListItem>();
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)); System.out.println("Reading " + lines.get(i));
String[] reading = lines.get(i).split(";");
if(lines.get(i).startsWith(DATE_TAG)) { list.add(new ChatListItem(reading[0], Integer.parseInt(reading[1])));
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);
} }
i++;
} }
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++;
}
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<String, Integer> e) {
return e.getKey();
}
private int getPoles(Map.Entry<String, Integer> e) {
return e.getValue();
} }
} }
class UserComparator implements Comparator<Map.Entry> { class ChatListItemComparator implements Comparator<ChatListItem> {
@Override @Override
public int compare(Map.Entry entr1, Map.Entry entr2) { public int compare(ChatListItem entr1, ChatListItem entr2) {
return entr1.compareTo(entr2);
return ((Integer) entr2.getValue()).compareTo((Integer) entr1.getValue());
} }
} }

View file

@ -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;
}
}

View file

@ -1,10 +1,14 @@
package elements; package elements;
import elements.exceptions.ReadErrorChatException;
import elements.exceptions.SaveErrorChatException;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -25,25 +29,33 @@ public class Persistence {
return persistence; return persistence;
} }
/*
public void saveChat(long chat_id, Chat c) throws SaveErrorException {
try {
List<String> lines = Arrays.asList(c.toTxt().split("\n"));
Path file = Paths.get("chats/" + chat_id + ".txt"); public void saveChat(long chat_id, Chat c) throws SaveErrorChatException {
try {
ArrayList<List<String>> lists = c.saveLists();
List<String> 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())) if (!Files.exists(file.getParent()))
Files.createDirectories(file.getParent()); Files.createDirectories(file.getParent());
Files.write(file, lines, Charset.forName("UTF-8")); Files.write(file, lines, Charset.forName("UTF-8"));
}
} catch (IOException e) { } catch (IOException e) {
throw new SaveErrorException(chat_id); throw new SaveErrorChatException(e);
} }
return; return;
} }
*/
/* /*
public HashMap<Long, Chat> readChats() throws ReadErrorException { public HashMap<Long, Chat> readChats() throws ReadErrorChatException {
HashMap<Long, Chat> chats = new HashMap<Long, Chat>(); HashMap<Long, Chat> chats = new HashMap<Long, Chat>();
if(!Files.exists(Paths.get("chats/"))) return chats; if(!Files.exists(Paths.get("chats/"))) return chats;
@ -51,7 +63,7 @@ public class Persistence {
try { try {
String filename; String filename;
Chat chat; Chat chat;
List<Path> files = Files.walk(Paths.get("chats/"), 1).collect(Collectors.toList()); List<Path> files = Files.walk(Paths.get("geiserFiles/"), 1).collect(Collectors.toList());
Path file; Path file;
List<String> lines; List<String> lines;
@ -68,10 +80,11 @@ public class Persistence {
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
throw new ReadErrorException(); throw new ReadErrorChatException(e);
} }
return chats; return chats;
} }
*/ */
} }

View file

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

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 NoUsernameMessageException extends NoAuthorMessageException { public class NoUsernameMessageException extends MessageException {
public NoUsernameMessageException() { public NoUsernameMessageException() {
super("The user has no username."); super("The user has no username.");
} }

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -54,14 +54,6 @@ public class ChannelMessage extends Message {
consoleLog = message.toString(); consoleLog = message.toString();
} }
public long getCid() {
return cid;
}
public long getMid() {
return mid;
}
public String getChatType() { public String getChatType() {
return chatType; return chatType;
} }

View file

@ -1,5 +1,6 @@
package elements.messages; package elements.messages;
import elements.exceptions.NoTextMessageException;
import elements.exceptions.NoUsernameMessageException; import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject; import org.json.JSONObject;
@ -7,6 +8,10 @@ import org.json.JSONObject;
* Created by Guillermo Serrahima on 10/8/16. * Created by Guillermo Serrahima on 10/8/16.
*/ */
public class GroupMessage extends Message { 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 Long cid; //chat id
private Integer mid; //message id private Integer mid; //message id
private Integer uid; //user id private Integer uid; //user id
@ -16,12 +21,15 @@ public class GroupMessage extends Message {
private String chatName; //chat name private String chatName; //chat name
private String text; //the actual message private String text; //the actual message
private String consoleLog; private String consoleLog;
private Integer event;
public GroupMessage(JSONObject message) { public GroupMessage(JSONObject message) {
super(message); super(message);
fullName = message.getJSONObject("from").getString("first_name"); fullName = message.getJSONObject("from").getString("first_name");
uid = message.getJSONObject("from").getInt("id"); uid = message.getJSONObject("from").getInt("id");
event = 0;
text = null;
//Check for user last name //Check for user last name
if (message.getJSONObject("from").has("last_name")) if (message.getJSONObject("from").has("last_name"))
@ -39,19 +47,25 @@ public class GroupMessage extends Message {
if (message.has("text")) if (message.has("text"))
text = message.getString("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(); consoleLog = message.toString();
} }
public long getCid() {
return cid;
}
public long getMid() {
return mid;
}
@Override @Override
public boolean hasAuthor() { public boolean hasAuthor() {
return true; return true;
@ -75,6 +89,15 @@ public class GroupMessage extends Message {
return userName; return userName;
} }
public boolean hasText() {
return event != 0 || text != null;
}
public String getText() throws NoTextMessageException {
if(text == null) throw new NoTextMessageException();
return text;
}
@Override @Override
public String getChatName() { public String getChatName() {
return chatName; return chatName;
@ -99,4 +122,21 @@ public class GroupMessage extends Message {
public boolean isPrivate() { public boolean isPrivate() {
return false; 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;
}
} }

View file

@ -1,11 +1,11 @@
package elements.messages; package elements.messages;
import elements.exceptions.NoAuthorMessageException; import elements.exceptions.*;
import elements.exceptions.NoChatNameMessageException;
import elements.exceptions.NoTextMessageException;
import elements.exceptions.NoUsernameMessageException;
import org.json.JSONObject; import org.json.JSONObject;
import java.time.ZoneId;
import java.util.Date;
/** /**
* Created by Guillermo Serrahima on 10/8/16. * Created by Guillermo Serrahima on 10/8/16.
*/ */
@ -18,6 +18,7 @@ public abstract class Message {
protected String userName; //username protected String userName; //username
protected String chatName; //chat name protected String chatName; //chat name
protected String text; //the actual message protected String text; //the actual message
protected Date timestamp;
protected String consoleLog; protected String consoleLog;
public Message(JSONObject message) { public Message(JSONObject message) {
@ -30,13 +31,15 @@ public abstract class Message {
else text = null; else text = null;
consoleLog = message.toString(); consoleLog = message.toString();
timestamp = new Date(new Long(message.getInt("date"))*1000);
} }
public long getCid() { public long getCid() {
return cid; return cid;
} }
public long getMid() { public int getMid() {
return mid; return mid;
} }
@ -52,7 +55,7 @@ public abstract class Message {
public abstract String getUsername() throws NoUsernameMessageException, NoAuthorMessageException; public abstract String getUsername() throws NoUsernameMessageException, NoAuthorMessageException;
private boolean hasText() { public boolean hasText() {
return text != null; return text != null;
} }
@ -61,7 +64,7 @@ public abstract class Message {
return text; 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"); String type = message.getJSONObject("chat").getString("type");
if(type.equals("group")) if(type.equals("group"))
@ -71,7 +74,7 @@ public abstract class Message {
if(type.equals("channel")) if(type.equals("channel"))
return new ChannelMessage(message); return new ChannelMessage(message);
if(!type.equals("private")) if(!type.equals("private"))
throw new Exception("Unidentified message."); throw new MessageException("Unidentified message.");
return new PrivateMessage(message); return new PrivateMessage(message);
} }
@ -88,7 +91,7 @@ public abstract class Message {
return chatName != null; return chatName != null;
} }
public abstract String getChatName() throws NoChatNameMessageException; public abstract String getChatName();
public boolean isGroup() { public boolean isGroup() {
return isBasicGroup() || isSupergroup(); return isBasicGroup() || isSupergroup();
@ -98,4 +101,12 @@ public abstract class Message {
public String toString() { public String toString() {
return consoleLog; return consoleLog;
} }
public String getTimestamp() {
return String.valueOf(timestamp);
}
public String getDate() {
return String.valueOf(timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
}
} }

View file

@ -27,7 +27,7 @@ public class PrivateMessage extends Message {
//Get group chat name //Get group chat name
if (message.getJSONObject("chat").has("title")) if (message.getJSONObject("chat").has("title"))
chatName = message.getJSONObject("chat").getString("title"); chatName = message.getJSONObject("chat").getString("title");
else chatName = null; else chatName = message.getJSONObject("from").getString("first_name");
if (message.has("text")) if (message.has("text"))
text = message.getString("text"); text = message.getString("text");
@ -78,8 +78,7 @@ public class PrivateMessage extends Message {
} }
@Override @Override
public String getChatName() throws NoChatNameMessageException { public String getChatName() {
if(!hasChatName()) throw new NoChatNameMessageException();
return chatName; return chatName;
} }
} }

View file

@ -5,18 +5,19 @@ 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.exceptions.NoAuthorMessageException; import elements.Persistence;
import elements.exceptions.NoTextMessageException; import elements.exceptions.*;
import elements.messages.ChannelMessage;
import elements.messages.GroupMessage; import elements.messages.GroupMessage;
import elements.messages.Message; import elements.messages.Message;
import elements.exceptions.NoChatNameMessageException;
import elements.exceptions.NoUsernameMessageException;
import elements.messages.PrivateMessage; 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.security.PrivateKey;
import java.security.acl.Group;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*; import java.util.*;
/** /**
@ -25,7 +26,7 @@ import java.util.*;
public class Geiserbot { 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 = "gserbot";
private static final String BASE_URL = "https://api.telegram.org/bot" + TOKEN; private static final String BASE_URL = "https://api.telegram.org/bot" + TOKEN;
private static final String PARSE_MARKDOWN = "Markdown"; private static final String PARSE_MARKDOWN = "Markdown";
private static final String PARSE_HTML = "HTML"; 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_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 Geiserbot() { public Geiserbot() {
chats = new HashMap<Long, Chat>();
} }
public String getUsername() { public String getUsername() {
@ -151,20 +152,16 @@ public class Geiserbot {
Message m = null; Message m = null;
try { try {
m = Message.getMessage(message); m = Message.getMessage(message);
} catch (Exception e) { } catch (MessageException e) {
System.out.println(e.getMessage()); System.out.println(e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
//Console log //Console log
printLog(false, m); printLog(true, m);
//Actually read the message //Actually read the message
if (message.has("text")) {
String text = message.getString("text");
handleInput(m); handleInput(m);
return;
}
} }
private void printLog(boolean full_log, Message m) { private void printLog(boolean full_log, Message m) {
@ -172,11 +169,9 @@ public class Geiserbot {
else { else {
String log = "\nMessage"; String log = "\nMessage";
try { if(m.isPrivate()) log += " received from a private chat";
log += " received from chat " + m.getChatName(); else log += " received from chat " + m.getChatName();
} catch (NoChatNameMessageException e) {
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();
@ -195,26 +190,72 @@ public class Geiserbot {
//--- Command handling //--- Command handling
private void handleInput(Message m) throws UnirestException { 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.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 { try {
if (!m.isChannel()) {
if (m.getText().startsWith("/start") && 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") && else 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("/whoami") && else 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);
}
else if (m.getText().startsWith("/list") &&
(!m.getText().substring("/list".length()).startsWith("@") ||
m.getText().substring("/list".length()).startsWith("@" + USERNAME)))
handleList(m);
} catch (NoTextMessageException ignored) {} } catch (NoTextMessageException ignored) {}
} }
private void handleInputChannel(ChannelMessage m) throws UnirestException {
}
private void handleStart(long chat_id) throws UnirestException { private void handleStart(long chat_id) throws UnirestException {
sendMessage(chat_id, "Hola. Soy el bot personal de Guillermo Serrahima."); sendMessage(chat_id, "Hola. Soy el bot personal de Guillermo Serrahima.");
return; return;
@ -225,52 +266,103 @@ public class Geiserbot {
"/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" +
"\n_GeiserPBot v1.0.0_"; "/list [nombre de la lista] - Permite crear, mostrar o " +
"modificar una lista\n";
sendMessage(chat_id, help, PARSE_MARKDOWN); sendMessage(chat_id, help.trim());
return; sendMessage(chat_id, "_" + myName() + " v1.0.0_", PARSE_MARKDOWN);
} }
private void handleWhoami(Message m) throws UnirestException { private void handleWhoami(Message m) throws UnirestException {
String s = "Estamos en"; String s = "Estamos en";
try { if(m.isPrivate()) s+= " un chat privado";
s += " el chat " + m.getChatName(); else s += " el chat " + m.getChatName();
} catch (NoChatNameMessageException e) {
s += " un chat"; s += " de ID " + m.getCid() + ".\n";
if(m.isPrivate()) s+= " privado";
}
s += " de id " + m.getCid() + ".\n";
try { try {
s += "Eres " + m.getAuthor(); s += "Eres " + m.getAuthor() + ", con";
try { try {
s += ", con nombre de usuario @" + m.getUsername(); s += " nombre de usuario @" + m.getUsername() +" e";
} catch (NoUsernameMessageException ignored) {} } catch (NoUsernameMessageException ignored) {}
s += " e id de usuario " + m.getUid() + ".\n"; s += " ID de usuario " + m.getUid() + ".\n";
} catch (NoAuthorMessageException ignored) {} } catch (NoAuthorMessageException ignored) {}
s += "En el PC que me mantiene, la fecha actual es " + LocalDate.now() + 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) { private void handleGroupEvent(GroupMessage m) throws NoTextMessageException, UnirestException {
return chats.containsKey(chat_id) && chats.get(chat_id).exists(user); 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 {
private void saveChat(long chat_id) throws SaveErrorException { 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 { 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)); Persistence.getInstance().saveChat(chat_id, chats.get(chat_id));
} catch (SaveErrorException e) {
e.printStackTrace();
throw e;
} }
}
*/
private String getWarning(int warning_id) { private String getWarning(int warning_id) {
switch (warning_id) { switch (warning_id) {