TelegramAPI/src/de/mrbesen/telegram/MessageBuilder.java

117 lines
2.5 KiB
Java

package de.mrbesen.telegram;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import de.mrbesen.telegram.objects.TReplyMarkup;
public class MessageBuilder {
private String text;
private Formatting format = Formatting.None;
private boolean silent = false;
private boolean no_web_view = false;
private int reciver_id = 0;
private int reply_to_message_id = 0;
private TReplyMarkup markup = null;
public MessageBuilder setReciver(int id) {
reciver_id = id;
return this;
}
public MessageBuilder setText(String txt) {
txt = txt.trim();
if(txt.isEmpty()) {
throw new IllegalArgumentException("text is not allowed to be empty");
}
try {
text = URLEncoder.encode(txt, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
public MessageBuilder setFormatting(Formatting form) {
format = form;
return this;
}
public MessageBuilder setSilent(boolean b) {
silent = b;
return this;
}
public MessageBuilder setNoWebView(boolean b) {
no_web_view = b;
return this;
}
public MessageBuilder setMarkup(TReplyMarkup markup) {
this.markup = markup;
return this;
}
public SendableMessage build() {
if(reciver_id == 0) {
throw new MissingException("Reciver");
}
if(text != null) {
if(text.trim().isEmpty()) {
throw new MissingException("Text");
}
} else {
throw new MissingException("Text");
}
String optionals = "";
if(format != Formatting.None) {
optionals += "&parse_mode=" + format.getname().toLowerCase();
}
if(reply_to_message_id != 0) {
optionals += "&reply_to_message_id=" + reply_to_message_id;
}
if(markup != null) {
optionals += "&reply_markup=" + markup.toJSONString();
}
return new SendableMessage("chat_id=" + reciver_id + "&text=" + text.trim() + optionals + "&disable_web_page_preview=" + no_web_view + "&disable_notification=" + silent);
}
class SendableMessage {
private String q;
public SendableMessage(String q) {
this.q = q;
}
String getQ() {
return q;
}
}
public enum Formatting {
None(""),
HTML("HTML"),
MD("Markdown");
private String apiname;
private Formatting(String s) {
apiname = s;
}
public String getname() {
return apiname;
}
}
public class MissingException extends RuntimeException {
private static final long serialVersionUID = 2750912631502103642L;
public MissingException(String missing_obj) {
super("The Object " + missing_obj + " is missing or invalid.");
}
}
}