Browse Source

1. Added Inline support

master
Rubenlagu 10 years ago
committed by Rubenlagus
parent
commit
2652636879
  1. 35
      .gitignore
  2. 2
      src/main/java/org/telegram/BotConfig.java
  3. 7
      src/main/java/org/telegram/Main.java
  4. 138
      src/main/java/org/telegram/api/methods/AnswerInlineQuery.java
  5. 66
      src/main/java/org/telegram/api/objects/ChosenInlineQuery.java
  6. 76
      src/main/java/org/telegram/api/objects/InlineQuery.java
  7. 13
      src/main/java/org/telegram/api/objects/InlineQueryResult.java
  8. 233
      src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java
  9. 213
      src/main/java/org/telegram/api/objects/InlineQueryResultGif.java
  10. 214
      src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java
  11. 249
      src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java
  12. 245
      src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java
  13. 52
      src/main/java/org/telegram/api/objects/Update.java
  14. 2
      src/main/java/org/telegram/services/BotLogger.java
  15. 231
      src/main/java/org/telegram/services/RaeService.java
  16. 151
      src/main/java/org/telegram/updateshandlers/RaeHandlers.java
  17. 20
      src/main/java/org/telegram/updateshandlers/WeatherHandlers.java

35
.gitignore

@ -0,0 +1,35 @@
### Maven template
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
### Java template
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# unneeded files
.idea/dataSources.*
.idea/workspace.xml
# logs files
*.log
# Certs
*.jks
*.cer
*.pem

2
src/main/java/org/telegram/BotConfig.java

@ -17,4 +17,6 @@ public class BotConfig {
public static final String USERNAMEDIRECTIONS = "directionsbot"; public static final String USERNAMEDIRECTIONS = "directionsbot";
public static final String TOKENCHANNEL = "<token>"; public static final String TOKENCHANNEL = "<token>";
public static final String USERNAMECHANNEL = "channelupdatesbot"; public static final String USERNAMECHANNEL = "channelupdatesbot";
public static final String TOKENRAE = "<token>";
public static final String USERNAMERAE = "raebot";
} }

7
src/main/java/org/telegram/Main.java

@ -3,9 +3,6 @@ package org.telegram;
import org.telegram.updateshandlers.*; import org.telegram.updateshandlers.*;
import org.telegram.updatesreceivers.Webhook; import org.telegram.updatesreceivers.Webhook;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
@ -24,8 +21,7 @@ public class Main {
initBots(); initBots();
if (BuildVars.useWebHook) { if (BuildVars.useWebHook) {
webhook.startDebugServer(); webhook.startServer();
//webhook.startServer();
} }
} }
@ -35,5 +31,6 @@ public class Main {
UpdatesCallback transifexBot = new TransifexHandlers(webhook); UpdatesCallback transifexBot = new TransifexHandlers(webhook);
UpdatesCallback filesBot = new FilesHandlers(webhook); UpdatesCallback filesBot = new FilesHandlers(webhook);
UpdatesCallback directionsBot = new DirectionsHandlers(webhook); UpdatesCallback directionsBot = new DirectionsHandlers(webhook);
UpdatesCallback raeBot = new RaeHandlers(webhook);
} }
} }

138
src/main/java/org/telegram/api/methods/AnswerInlineQuery.java

@ -0,0 +1,138 @@
package org.telegram.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.api.objects.InlineQueryResult;
import java.io.IOException;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send answers to an inline query. On success, True is returned.
* @date 01 of January of 2016
*/
public class AnswerInlineQuery extends BotApiMethod<Boolean> {
public static final String PATH = "answerInlineQuery";
public static final String INLINEQUERYID_FIELD = "inline_query_id";
private String inlineQueryId; ///< Unique identifier for answered query
public static final String RESULTS_FIELD = "results";
private List<InlineQueryResult> results; ///< A JSON-serialized array of results for the inline query
public static final String CACHETIME_FIELD = "cache_time";
private Integer cacheTime; ///< Optional The maximum amount of time the result of the inline query may be cached on the server
public static final String ISPERSONAL_FIELD = "is_personal";
private Boolean isPersonal; ///< Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query
public static final String NEXTOFFSET_FIELD = "next_offset";
private String nextOffset; ///< Optional Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes.
public AnswerInlineQuery() {
super();
}
public String getInlineQueryId() {
return inlineQueryId;
}
public void setInlineQueryId(String inlineQueryId) {
this.inlineQueryId = inlineQueryId;
}
public List<InlineQueryResult> getResults() {
return results;
}
public void setResults(List<InlineQueryResult> results) {
this.results = results;
}
public Integer getCacheTime() {
return cacheTime;
}
public void setCacheTime(Integer cacheTime) {
this.cacheTime = cacheTime;
}
public Boolean getPersonal() {
return isPersonal;
}
public void setPersonal(Boolean personal) {
isPersonal = personal;
}
public String getNextOffset() {
return nextOffset;
}
public void setNextOffset(String nextOffset) {
this.nextOffset = nextOffset;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(INLINEQUERYID_FIELD, inlineQueryId);
JSONArray JSONResults = new JSONArray();
for (InlineQueryResult result: results) {
JSONResults.put(result.toJson());
}
jsonObject.put(RESULTS_FIELD, JSONResults);
if (cacheTime != null) {
jsonObject.put(CACHETIME_FIELD, cacheTime);
}
if (isPersonal != null) {
jsonObject.put(ISPERSONAL_FIELD, isPersonal);
}
if (nextOffset != null) {
jsonObject.put(NEXTOFFSET_FIELD, nextOffset);
}
return jsonObject;
}
@Override
public String getPath() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return answer.getBoolean("result");
}
return null;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeArrayFieldStart(RESULTS_FIELD);
for (InlineQueryResult result: results) {
gen.writeObject(result);
}
gen.writeEndArray();
if (cacheTime != null) {
gen.writeNumberField(CACHETIME_FIELD, cacheTime);
}
if (isPersonal != null) {
gen.writeBooleanField(ISPERSONAL_FIELD, isPersonal);
}
if (nextOffset != null) {
gen.writeStringField(NEXTOFFSET_FIELD, nextOffset);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

66
src/main/java/org/telegram/api/objects/ChosenInlineQuery.java

@ -0,0 +1,66 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a result of an inline query that was chosen by the user and sent to their chat partner.
* @date 01 of January of 2016
*/
public class ChosenInlineQuery implements BotApiObject {
public static final String RESULTID_FIELD = "id";
@JsonProperty(RESULTID_FIELD)
private String resultId; ///< The unique identifier for the result that was chosen.
public static final String FROM_FIELD = "from";
@JsonProperty(FROM_FIELD)
private User from; ///< The user that chose the result.
public static final String QUERY_FIELD = "query";
@JsonProperty(QUERY_FIELD)
private String query; ///< The query that was used to obtain the result.
public ChosenInlineQuery() {
super();
}
public ChosenInlineQuery(JSONObject jsonObject) {
super();
this.resultId = jsonObject.getString(RESULTID_FIELD);
this.from = new User(jsonObject.getJSONObject(FROM_FIELD));
this.query = jsonObject.getString(QUERY_FIELD);
}
public String getResultId() {
return resultId;
}
public User getFrom() {
return from;
}
public String getQuery() {
return query;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(RESULTID_FIELD, resultId);
gen.writeObjectField(FROM_FIELD, from);
gen.writeStringField(QUERY_FIELD, query);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

76
src/main/java/org/telegram/api/objects/InlineQuery.java

@ -0,0 +1,76 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents an incoming inline query.
* When the user sends an empty query, your bot could return some default or trending results.
* @date 01 of January of 2016
*/
public class InlineQuery implements BotApiObject {
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier for this query
public static final String FROM_FIELD = "from";
@JsonProperty(FROM_FIELD)
private User from; ///< Sender
public static final String QUERY_FIELD = "query";
@JsonProperty(QUERY_FIELD)
private String query; ///< Text of the query
public static final String OFFSET_FIELD = "offset";
@JsonProperty(OFFSET_FIELD)
private String offset; ///< Offset of the results to be returned, can be controlled by the bot
public InlineQuery() {
super();
}
public InlineQuery(JSONObject jsonObject) {
super();
this.id = jsonObject.getString(ID_FIELD);
this.from = new User(jsonObject.getJSONObject(FROM_FIELD));
this.query = jsonObject.getString(QUERY_FIELD);
this.offset = jsonObject.getString(OFFSET_FIELD);
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(ID_FIELD, id);
gen.writeObjectField(FROM_FIELD, from);
gen.writeStringField(QUERY_FIELD, query);
gen.writeStringField(OFFSET_FIELD, offset);
gen.writeEndObject();
gen.flush();
}
public String getId() {
return id;
}
public User getFrom() {
return from;
}
public String getQuery() {
return query;
}
public String getOffset() {
return offset;
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

13
src/main/java/org/telegram/api/objects/InlineQueryResult.java

@ -0,0 +1,13 @@
package org.telegram.api.objects;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents one result of an inline query.
* @date 01 of January of 2016
*/
public interface InlineQueryResult extends BotApiObject, IToJson {
}

233
src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java

@ -0,0 +1,233 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Represents a link to an article or web page.
* @date 01 of January of 2016
*/
public class InlineQueryResultArticle implements InlineQueryResult {
public static final String TYPE_FIELD = "type";
@JsonProperty(TYPE_FIELD)
private final String type = "article"; ///< Type of the result, must be “article”
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier of this result
public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD)
private String title; ///< Title of the result
public static final String MESSAGETEXT_FIELD = "message_text";
@JsonProperty(MESSAGETEXT_FIELD)
private String messageText; ///< Text of a message to be sent
public static final String PARSEMODE_FIELD = "parse_mode";
@JsonProperty(PARSEMODE_FIELD)
private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message.
public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview";
@JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message
public static final String URL_FIELD = "url";
@JsonProperty(URL_FIELD)
private String url; ///< Optional. URL of the result
public static final String HIDEURL_FIELD = "hide_url";
@JsonProperty(HIDEURL_FIELD)
private Boolean hideUrl; ///< Optional. Pass True, if you don't want the URL to be shown in the message
public static final String DESCRIPTION_FIELD = "description";
@JsonProperty(DESCRIPTION_FIELD)
private String description; ///< Optional. Short description of the result
public static final String THUMBURL_FIELD = "thumb_url";
@JsonProperty(THUMBURL_FIELD)
private String thumbUrl; ///< Optional. Url of the thumbnail for the result
public static final String THUMBWIDTH_FIELD = "thumb_width";
@JsonProperty(THUMBWIDTH_FIELD)
private Integer thumbWidth; ///< Optional. Thumbnail width
public static final String THUMBHEIGHT_FIELD = "thumb_height";
@JsonProperty(THUMBHEIGHT_FIELD)
private Integer thumbHeight; ///< Optional. Thumbnail height
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
public void setMarkdown(boolean enabled) {
if (enabled) {
parseMode = "Markdown";
} else {
parseMode = null;
}
}
public Boolean getDisableWebPagePreview() {
return disableWebPagePreview;
}
public void setDisableWebPagePreview(Boolean disableWebPagePreview) {
this.disableWebPagePreview = disableWebPagePreview;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getHideUrl() {
return hideUrl;
}
public void setHideUrl(Boolean hideUrl) {
this.hideUrl = hideUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public Integer getThumbWidth() {
return thumbWidth;
}
public void setThumbWidth(Integer thumbWidth) {
this.thumbWidth = thumbWidth;
}
public Integer getThumbHeight() {
return thumbHeight;
}
public void setThumbHeight(Integer thumbHeight) {
this.thumbHeight = thumbHeight;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(TYPE_FIELD, this.type);
jsonObject.put(ID_FIELD, this.id);
jsonObject.put(TITLE_FIELD, this.title);
jsonObject.put(MESSAGETEXT_FIELD, this.messageText);
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (url != null) {
jsonObject.put(URL_FIELD, this.url);
}
if (hideUrl != null) {
jsonObject.put(HIDEURL_FIELD, this.hideUrl);
}
if (description != null) {
jsonObject.put(DESCRIPTION_FIELD, this.description);
}
if (thumbUrl != null) {
jsonObject.put(THUMBURL_FIELD, this.thumbUrl);
}
if (thumbWidth != null) {
jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth);
}
if (thumbHeight != null) {
jsonObject.put(THUMBHEIGHT_FIELD, this.thumbHeight);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TYPE_FIELD, type);
gen.writeStringField(ID_FIELD, id);
gen.writeStringField(TITLE_FIELD, title);
gen.writeStringField(MESSAGETEXT_FIELD, messageText);
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (url != null) {
gen.writeStringField(URL_FIELD, this.url);
}
if (hideUrl != null) {
gen.writeBooleanField(HIDEURL_FIELD, this.hideUrl);
}
if (description != null) {
gen.writeStringField(DESCRIPTION_FIELD, this.description);
}
if (thumbUrl != null) {
gen.writeStringField(THUMBURL_FIELD, this.thumbUrl);
}
if (thumbWidth != null) {
gen.writeNumberField(THUMBWIDTH_FIELD, this.thumbWidth);
}
if (thumbHeight != null) {
gen.writeNumberField(THUMBHEIGHT_FIELD, this.thumbHeight);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

213
src/main/java/org/telegram/api/objects/InlineQueryResultGif.java

@ -0,0 +1,213 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption.
* Alternatively, you can provide message_text to send it instead of the animation.
* @date 01 of January of 2016
*/
public class InlineQueryResultGif implements InlineQueryResult {
public static final String TYPE_FIELD = "type";
@JsonProperty(TYPE_FIELD)
private final String type = "gif"; ///< Type of the result, must be "gif"
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier of this result
public static final String GIFURL_FIELD = "gif_url";
@JsonProperty(GIFURL_FIELD)
private String gifUrl; ///< A valid URL for the GIF file. File size must not exceed 1MB
public static final String GIFWIDTH_FIELD = "gif_width";
@JsonProperty(GIFWIDTH_FIELD)
private Integer gifWidth; ///< Optional. Width of the GIF
public static final String GIFHEIGHT_FIELD = "gif_height";
@JsonProperty(GIFHEIGHT_FIELD)
private Integer gifHeight; ///< Optional. Height of the GIF
public static final String THUMBURL_FIELD = "thumb_url";
@JsonProperty(THUMBURL_FIELD)
private String thumbUrl; ///< Optional. URL of a static thumbnail for the result (jpeg or gif)
public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Title for the result
public static final String CAPTION_FIELD = "caption";
@JsonProperty(CAPTION_FIELD)
private String caption; ///< Optional. Caption of the GIF file to be sent
public static final String MESSAGETEXT_FIELD = "message_text";
@JsonProperty(MESSAGETEXT_FIELD)
private String messageText; ///< Optional. Text of a message to be sent instead of the animation
public static final String PARSEMODE_FIELD = "parse_mode";
@JsonProperty(PARSEMODE_FIELD)
private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message.
public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview";
@JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
public Boolean getDisableWebPagePreview() {
return disableWebPagePreview;
}
public void setDisableWebPagePreview(Boolean disableWebPagePreview) {
this.disableWebPagePreview = disableWebPagePreview;
}
public String getGifUrl() {
return gifUrl;
}
public void setGifUrl(String gifUrl) {
this.gifUrl = gifUrl;
}
public Integer getGifWidth() {
return gifWidth;
}
public void setGifWidth(Integer gifWidth) {
this.gifWidth = gifWidth;
}
public Integer getGifHeight() {
return gifHeight;
}
public void setGifHeight(Integer gifHeight) {
this.gifHeight = gifHeight;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(TYPE_FIELD, this.type);
jsonObject.put(ID_FIELD, this.id);
jsonObject.put(GIFURL_FIELD, this.gifUrl);
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (gifWidth != null) {
jsonObject.put(GIFWIDTH_FIELD, this.gifWidth);
}
if (gifHeight != null) {
jsonObject.put(GIFHEIGHT_FIELD, this.gifHeight);
}
if (thumbUrl != null) {
jsonObject.put(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
jsonObject.put(TITLE_FIELD, this.title);
}
if (caption != null) {
jsonObject.put(CAPTION_FIELD, this.caption);
}
if (messageText != null) {
jsonObject.put(MESSAGETEXT_FIELD, this.messageText);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TYPE_FIELD, type);
gen.writeStringField(ID_FIELD, id);
gen.writeStringField(GIFURL_FIELD, this.gifUrl);
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (gifWidth != null) {
gen.writeNumberField(GIFWIDTH_FIELD, this.gifWidth);
}
if (gifHeight != null) {
gen.writeNumberField(GIFHEIGHT_FIELD, this.gifHeight);
}
if (thumbUrl != null) {
gen.writeStringField(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
gen.writeStringField(TITLE_FIELD, this.title);
}
if (caption != null) {
gen.writeStringField(CAPTION_FIELD, this.caption);
}
if (messageText != null) {
gen.writeStringField(MESSAGETEXT_FIELD, this.messageText);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

214
src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java

@ -0,0 +1,214 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Represents a link to a video animation (H.264/MPEG-4 AVC video without sound).
* By default, this animated MPEG-4 file will be sent by the user with optional caption.
* Alternatively, you can provide message_text to send it instead of the animation.
* @date 01 of January of 2016
*/
public class InlineQueryResultMpeg4Gif implements InlineQueryResult {
public static final String TYPE_FIELD = "type";
@JsonProperty(TYPE_FIELD)
private final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif"
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier of this result
public static final String MPEG4URL_FIELD = "mpeg4_url";
@JsonProperty(MPEG4URL_FIELD)
private String mpeg4Url; ///< A valid URL for the MP4 file. File size must not exceed 1MB
public static final String MPEG4WIDTH_FIELD = "mpeg4_width";
@JsonProperty(MPEG4WIDTH_FIELD)
private Integer mpeg4Width; ///< Optional. Video width
public static final String MPEG4HEIGHT_FIELD = "mpeg4_height";
@JsonProperty(MPEG4HEIGHT_FIELD)
private Integer mpeg4Height; ///< Optional. Video height
public static final String THUMBURL_FIELD = "thumb_url";
@JsonProperty(THUMBURL_FIELD)
private String thumbUrl; ///< Optional. URL of the static thumbnail (jpeg or gif) for the result
public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Title for the result
public static final String CAPTION_FIELD = "caption";
@JsonProperty(CAPTION_FIELD)
private String caption; ///< Optional. Caption of the MPEG-4 file to be sent
public static final String MESSAGETEXT_FIELD = "message_text";
@JsonProperty(MESSAGETEXT_FIELD)
private String messageText; ///< Optional. Text of a message to be sent instead of the animation
public static final String PARSEMODE_FIELD = "parse_mode";
@JsonProperty(PARSEMODE_FIELD)
private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message.
public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview";
@JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
public Boolean getDisableWebPagePreview() {
return disableWebPagePreview;
}
public void setDisableWebPagePreview(Boolean disableWebPagePreview) {
this.disableWebPagePreview = disableWebPagePreview;
}
public String getMpeg4Url() {
return mpeg4Url;
}
public void setMpeg4Url(String mpeg4Url) {
this.mpeg4Url = mpeg4Url;
}
public Integer getMpeg4Width() {
return mpeg4Width;
}
public void setMpeg4Width(Integer mpeg4Width) {
this.mpeg4Width = mpeg4Width;
}
public Integer getMpeg4Height() {
return mpeg4Height;
}
public void setMpeg4Height(Integer mpeg4Height) {
this.mpeg4Height = mpeg4Height;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(TYPE_FIELD, this.type);
jsonObject.put(ID_FIELD, this.id);
jsonObject.put(MPEG4URL_FIELD, this.mpeg4Url);
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (mpeg4Width != null) {
jsonObject.put(MPEG4WIDTH_FIELD, this.mpeg4Width);
}
if (mpeg4Height != null) {
jsonObject.put(MPEG4HEIGHT_FIELD, this.mpeg4Height);
}
if (thumbUrl != null) {
jsonObject.put(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
jsonObject.put(TITLE_FIELD, this.title);
}
if (caption != null) {
jsonObject.put(CAPTION_FIELD, this.caption);
}
if (messageText != null) {
jsonObject.put(MESSAGETEXT_FIELD, this.messageText);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TYPE_FIELD, type);
gen.writeStringField(ID_FIELD, id);
gen.writeStringField(MPEG4URL_FIELD, this.mpeg4Url);
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (mpeg4Width != null) {
gen.writeNumberField(MPEG4WIDTH_FIELD, this.mpeg4Width);
}
if (mpeg4Height != null) {
gen.writeNumberField(MPEG4HEIGHT_FIELD, this.mpeg4Height);
}
if (thumbUrl != null) {
gen.writeStringField(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
gen.writeStringField(TITLE_FIELD, this.title);
}
if (caption != null) {
gen.writeStringField(CAPTION_FIELD, this.caption);
}
if (messageText != null) {
gen.writeStringField(MESSAGETEXT_FIELD, this.messageText);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

249
src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java

@ -0,0 +1,249 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Represents a link to a photo. By default, this photo will be sent by the user with optional caption.
* Alternatively, you can provide message_text to send it instead of photo.
* @date 01 of January of 2016
*/
public class InlineQueryResultPhoto implements InlineQueryResult {
public static final String TYPE_FIELD = "type";
@JsonProperty(TYPE_FIELD)
private final String type = "photo"; ///< Type of the result, must be “photo”
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier of this result
public static final String PHOTOURL_FIELD = "photo_url";
@JsonProperty(PHOTOURL_FIELD)
private String photoUrl; ///< A valid URL of the photo. Photo size must not exceed 5MB
public static final String MIMETYPE_FIELD = "mime_type";
@JsonProperty(MIMETYPE_FIELD)
private String mimeType; ///< Optional. MIME type of the photo, defaults to image/jpeg
public static final String PHOTOWIDTH_FIELD = "photo_width";
@JsonProperty(PHOTOWIDTH_FIELD)
private Integer photoWidth; ///< Optional. Width of the photo
public static final String PHOTOHEIGHT_FIELD = "photo_height";
@JsonProperty(PHOTOHEIGHT_FIELD)
private Integer photoHeight; ///< Optional. Height of the photo
public static final String THUMBURL_FIELD = "thumb_url";
@JsonProperty(THUMBURL_FIELD)
private String thumbUrl; ///< Optional. URL of the thumbnail for the photo
public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Title for the result
public static final String DESCRIPTION_FIELD = "description";
@JsonProperty(DESCRIPTION_FIELD)
private String description; ///< Optional. Short description of the result
public static final String CAPTION_FIELD = "caption";
@JsonProperty(CAPTION_FIELD)
private String caption; ///< Optional. Caption of the photo to be sent
public static final String MESSAGETEXT_FIELD = "message_text";
@JsonProperty(MESSAGETEXT_FIELD)
private String messageText; ///< Optional. Text of a message to be sent instead of the photo
public static final String PARSEMODE_FIELD = "parse_mode";
@JsonProperty(PARSEMODE_FIELD)
private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message.
public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview";
@JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
public Boolean getDisableWebPagePreview() {
return disableWebPagePreview;
}
public void setDisableWebPagePreview(Boolean disableWebPagePreview) {
this.disableWebPagePreview = disableWebPagePreview;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public Integer getPhotoWidth() {
return photoWidth;
}
public void setPhotoWidth(Integer photoWidth) {
this.photoWidth = photoWidth;
}
public Integer getPhotoHeight() {
return photoHeight;
}
public void setPhotoHeight(Integer photoHeight) {
this.photoHeight = photoHeight;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(TYPE_FIELD, this.type);
jsonObject.put(ID_FIELD, this.id);
jsonObject.put(PHOTOURL_FIELD, this.photoUrl);
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (mimeType != null) {
jsonObject.put(MIMETYPE_FIELD, this.mimeType);
}
if (photoWidth != null) {
jsonObject.put(PHOTOWIDTH_FIELD, this.photoWidth);
}
if (photoHeight != null) {
jsonObject.put(PHOTOHEIGHT_FIELD, this.photoHeight);
}
if (description != null) {
jsonObject.put(DESCRIPTION_FIELD, this.description);
}
if (thumbUrl != null) {
jsonObject.put(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
jsonObject.put(TITLE_FIELD, this.title);
}
if (description != null) {
jsonObject.put(DESCRIPTION_FIELD, this.description);
}
if (caption != null) {
jsonObject.put(CAPTION_FIELD, this.caption);
}
if (messageText != null) {
jsonObject.put(MESSAGETEXT_FIELD, this.messageText);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TYPE_FIELD, type);
gen.writeStringField(ID_FIELD, id);
gen.writeStringField(PHOTOURL_FIELD, this.photoUrl);
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, this.mimeType);
}
if (photoWidth != null) {
gen.writeNumberField(PHOTOWIDTH_FIELD, this.photoWidth);
}
if (photoHeight != null) {
gen.writeNumberField(PHOTOHEIGHT_FIELD, this.photoHeight);
}
if (thumbUrl != null) {
gen.writeStringField(THUMBURL_FIELD, this.thumbUrl);
}
if (description != null) {
gen.writeStringField(DESCRIPTION_FIELD, this.description);
}
if (title != null) {
gen.writeStringField(TITLE_FIELD, this.title);
}
if (caption != null) {
gen.writeStringField(CAPTION_FIELD, this.caption);
}
if (messageText != null) {
gen.writeStringField(MESSAGETEXT_FIELD, this.messageText);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

245
src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java

@ -0,0 +1,245 @@
package org.telegram.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Represents link to a page containing an embedded video player or a video file.
* @date 01 of January of 2016
*/
public class InlineQueryResultVideo implements InlineQueryResult {
public static final String TYPE_FIELD = "type";
@JsonProperty(TYPE_FIELD)
private final String type = "video"; ///< Type of the result, must be "video"
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier of this result
public static final String MIMETYPE_FIELD = "mime_type";
@JsonProperty(MIMETYPE_FIELD)
private String mimeType; ///< Mime type of the content of video url, i.e. “text/html” or “video/mp4”
public static final String VIDEOURL_FIELD = "video_url";
@JsonProperty(VIDEOURL_FIELD)
private String videoUrl; ///< A valid URL for the embedded video player or video file
public static final String VIDEOWIDTH_FIELD = "video_width";
@JsonProperty(VIDEOWIDTH_FIELD)
private Integer videoWidth; ///< Optional. Video width
public static final String VIDEOHEIGHT_FIELD = "video_height";
@JsonProperty(VIDEOHEIGHT_FIELD)
private Integer videoHeight; ///< Optional. Video height
public static final String VIDEODURATION_FIELD = "video_duration";
@JsonProperty(VIDEODURATION_FIELD)
private Integer videoDuration; ///< Optional. Video duration in seconds
public static final String THUMBURL_FIELD = "thumb_url";
@JsonProperty(THUMBURL_FIELD)
private String thumbUrl; ///< Optional. URL of the thumbnail (jpeg only) for the video
public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Title for the result
public static final String DESCRIPTION_FIELD = "description";
@JsonProperty(DESCRIPTION_FIELD)
private String description; ///< Optional. Short description of the result
public static final String MESSAGETEXT_FIELD = "message_text";
@JsonProperty(MESSAGETEXT_FIELD)
private String messageText; ///< Optional. Text of a message to be sent instead of the video
public static final String PARSEMODE_FIELD = "parse_mode";
@JsonProperty(PARSEMODE_FIELD)
private String parseMode; ///< Optional. Send “Markdown”, if you want Telegram apps to show bold, italic and inline URLs in your bot's message.
public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview";
@JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
public Boolean getDisableWebPagePreview() {
return disableWebPagePreview;
}
public void setDisableWebPagePreview(Boolean disableWebPagePreview) {
this.disableWebPagePreview = disableWebPagePreview;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public Integer getVideoWidth() {
return videoWidth;
}
public void setVideoWidth(Integer videoWidth) {
this.videoWidth = videoWidth;
}
public Integer getVideoHeight() {
return videoHeight;
}
public void setVideoHeight(Integer videoHeight) {
this.videoHeight = videoHeight;
}
public Integer getVideoDuration() {
return videoDuration;
}
public void setVideoDuration(Integer videoDuration) {
this.videoDuration = videoDuration;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(TYPE_FIELD, this.type);
jsonObject.put(ID_FIELD, this.id);
jsonObject.put(VIDEOURL_FIELD, this.videoUrl);
if (mimeType != null) {
jsonObject.put(MIMETYPE_FIELD, this.mimeType);
}
if (messageText != null) {
jsonObject.put(MESSAGETEXT_FIELD, this.messageText);
}
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (videoWidth != null) {
jsonObject.put(VIDEOWIDTH_FIELD, this.videoWidth);
}
if (videoHeight != null) {
jsonObject.put(VIDEOHEIGHT_FIELD, this.videoHeight);
}
if (videoDuration != null) {
jsonObject.put(VIDEODURATION_FIELD, this.videoDuration);
}
if (thumbUrl != null) {
jsonObject.put(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
jsonObject.put(TITLE_FIELD, this.title);
}
if (description != null) {
jsonObject.put(DESCRIPTION_FIELD, this.description);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TYPE_FIELD, type);
gen.writeStringField(ID_FIELD, id);
gen.writeStringField(VIDEOURL_FIELD, this.videoUrl);
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, this.mimeType);
}
if (messageText != null) {
gen.writeStringField(MESSAGETEXT_FIELD, this.messageText);
}
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, this.parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
}
if (videoWidth != null) {
gen.writeNumberField(VIDEOWIDTH_FIELD, this.videoWidth);
}
if (videoHeight != null) {
gen.writeNumberField(VIDEOHEIGHT_FIELD, this.videoHeight);
}
if (videoDuration != null) {
gen.writeNumberField(VIDEODURATION_FIELD, this.videoDuration);
}
if (thumbUrl != null) {
gen.writeStringField(THUMBURL_FIELD, this.thumbUrl);
}
if (title != null) {
gen.writeStringField(TITLE_FIELD, this.title);
}
if (description != null) {
gen.writeStringField(DESCRIPTION_FIELD, this.description);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

52
src/main/java/org/telegram/api/objects/Update.java

@ -12,23 +12,27 @@ import java.io.IOException;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief TODO * @brief This object represents an incoming update.
* Only one of the optional parameters can be present in any given update.
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class Update implements BotApiObject { public class Update implements BotApiObject {
public static final String UPDATEID_FIELD = "update_id"; public static final String UPDATEID_FIELD = "update_id";
/**
* The updates unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if youre using Webhooks,
* since it allows you to ignore repeated updates or to restore the
* correct update sequence, should they get out of order.
*/
@JsonProperty(UPDATEID_FIELD) @JsonProperty(UPDATEID_FIELD)
private Integer updateId; private Integer updateId;
public static final String MESSAGE_FIELD = "message"; public static final String MESSAGE_FIELD = "message";
@JsonProperty(MESSAGE_FIELD) @JsonProperty(MESSAGE_FIELD)
private Message message; ///< Optional. New incoming message of any kind — text, photo, sticker, etc. private Message message; ///< Optional. New incoming message of any kind — text, photo, sticker, etc.
public static final String INLINEQUERY_FIELD = "inline_query";
@JsonProperty(INLINEQUERY_FIELD)
private InlineQuery inlineQuery; ///< Optional. New incoming inline query
public static final String CHOSENINLINEQUERY_FIELD = "chosen_inline_result";
@JsonProperty(CHOSENINLINEQUERY_FIELD)
private ChosenInlineQuery chosenInlineQuery; ///< Optional. The result of a inline query that was chosen by a user and sent to their chat partner
/*
ChosenInlineResult
*/
public Update() { public Update() {
super(); super();
@ -40,6 +44,12 @@ public class Update implements BotApiObject {
if (jsonObject.has(MESSAGE_FIELD)) { if (jsonObject.has(MESSAGE_FIELD)) {
this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD)); this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD));
} }
if (jsonObject.has(INLINEQUERY_FIELD)) {
this.inlineQuery = new InlineQuery(jsonObject.getJSONObject(INLINEQUERY_FIELD));
}
if (jsonObject.has(CHOSENINLINEQUERY_FIELD)) {
this.chosenInlineQuery = new ChosenInlineQuery(jsonObject.getJSONObject(CHOSENINLINEQUERY_FIELD));
}
} }
public Integer getUpdateId() { public Integer getUpdateId() {
@ -50,6 +60,26 @@ public class Update implements BotApiObject {
return message; return message;
} }
public InlineQuery getInlineQuery() {
return inlineQuery;
}
public ChosenInlineQuery getChosenInlineQuery() {
return chosenInlineQuery;
}
public boolean hasMessage() {
return message != null;
}
public boolean hasInlineQuery() {
return inlineQuery != null;
}
public boolean hasChosenInlineQuery() {
return chosenInlineQuery != null;
}
@Override @Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
@ -57,6 +87,12 @@ public class Update implements BotApiObject {
if (message != null) { if (message != null) {
gen.writeObjectField(MESSAGE_FIELD, message); gen.writeObjectField(MESSAGE_FIELD, message);
} }
if (inlineQuery != null) {
gen.writeObjectField(INLINEQUERY_FIELD, inlineQuery);
}
if (chosenInlineQuery != null) {
gen.writeObjectField(CHOSENINLINEQUERY_FIELD, chosenInlineQuery);
}
gen.writeEndObject(); gen.writeEndObject();
gen.flush(); gen.flush();
} }

2
src/main/java/org/telegram/services/BotLogger.java

@ -6,6 +6,7 @@ import javax.validation.constraints.NotNull;
import java.io.*; import java.io.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -26,6 +27,7 @@ public class BotLogger {
static { static {
logger.setLevel(Level.ALL); logger.setLevel(Level.ALL);
logger.addHandler(new ConsoleHandler());
loggerThread.start(); loggerThread.start();
lastFileDate = LocalDateTime.now(); lastFileDate = LocalDateTime.now();
if ((currentFileName == null) || (currentFileName.compareTo("") == 0)) { if ((currentFileName == null) || (currentFileName.compareTo("") == 0)) {

231
src/main/java/org/telegram/services/RaeService.java

@ -0,0 +1,231 @@
package org.telegram.services;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Rae service
* @date 20 of June of 2015
*/
public class RaeService {
private static final String LOGTAG = "RAESERVICE";
private static final String BASEURL = "http://dle.rae.es/srv/"; ///< Base url for REST
private static final String SEARCHEXACTURL = "search?m=30&w=";
private static final String SEARCHWORDURL = "search?m=form&w=";
private static final String WORDLINKBYID = "http://dle.rae.es/?id=";
public List<RaeResult> getResults(String query) {
List<RaeResult> results = new ArrayList<>();
String completeURL;
try {
completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, "UTF-8");
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completeURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
Document document = Jsoup.parse(responseString);
Element article = document.getElementsByTag("article").first();
String articleId = null;
if (article != null) {
articleId = article.attributes().get("id");
}
Elements elements = document.select(".j");
if (elements.isEmpty()) {
results = getResultsWordSearch(query);
} else {
results = getResultsFromExactMatch(elements, query, articleId);
}
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
return results;
}
private List<RaeResult> getResultsWordSearch(String query) {
List<RaeResult> results = new ArrayList<>();
String completeURL;
try {
completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, "UTF-8");
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completeURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
Document document = Jsoup.parse(responseString);
Element list = document.select("body div ul").first();
if (list != null) {
Elements links = list.getElementsByTag("a");
if (!links.isEmpty()) {
for (Element link : links) {
List<RaeResult> partialResults = fetchWord(link.attributes().get("href"), link.text());
if (!partialResults.isEmpty()) {
results.addAll(partialResults);
}
}
}
}
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
return results;
}
private List<RaeResult> fetchWord(String link, String word) {
List<RaeResult> results = new ArrayList<>();
String completeURL;
try {
completeURL = BASEURL + link;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completeURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
Document document = Jsoup.parse(responseString);
Element article = document.getElementsByTag("article").first();
String articleId = null;
if (article != null) {
articleId = article.attributes().get("id");
}
Elements elements = document.select(".j");
if (!elements.isEmpty()) {
results = getResultsFromExactMatch(elements, word, articleId);
}
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
return results;
}
private List<RaeResult> getResultsFromExactMatch(Elements elements, String word, String link) {
List<RaeResult> results = new ArrayList<>();
for (int i = 0; i < elements.size(); i++) {
Element element = elements.get(i);
RaeResult result = new RaeResult();
if (link != null && !link.isEmpty()) {
result.link = WORDLINKBYID + link;
}
result.index = i;
result.word = capitalizeFirstLetter(word);
Elements tags = element.getElementsByTag("abbr");
tags.removeIf(x -> !x.parent().equals(element));
for (Element tag : tags) {
result.tags.put(tag.text(), tag.attributes().get("title"));
}
Elements definition = element.getElementsByTag("mark");
definition.removeIf(x -> !x.parent().equals(element));
if (definition.isEmpty()) {
results.addAll(findResultsFromRedirect(element, word));
} else {
StringBuilder definitionBuilder = new StringBuilder();
definition.stream().forEachOrdered(y -> {
String partialText = y.text();
if (definitionBuilder.length() > 0) {
definitionBuilder.append(" ");
partialText = partialText.toLowerCase();
}
definitionBuilder.append(partialText);
});
result.definition = capitalizeFirstLetter(definitionBuilder.toString());
results.add(result);
}
}
return results;
}
private List<RaeResult> findResultsFromRedirect(Element element, String word) {
List<RaeResult> results = new ArrayList<>();
Element redirect = element.getElementsByTag("a").first();
if (redirect != null) {
String link = redirect.attributes().get("href");
results = fetchWord(link, word);
}
return results;
}
private static String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
public static class RaeResult {
public int index;
public String word;
public Map<String, String> tags = new HashMap<>();
public String definition;
public String link;
public String getDefinition() {
final StringBuilder builder = new StringBuilder();
if (link != null && !link.isEmpty()) {
builder.append("[").append(word).append("](");
builder.append(link).append(")\n");
}
for (Map.Entry<String, String> tag : tags.entrySet()) {
builder.append("*").append(tag.getKey()).append("*");
builder.append(" (_").append(tag.getValue()).append("_)\n");
}
builder.append(definition);
return builder.toString();
}
public String getDescription() {
return definition;
}
public String getTitle() {
final StringBuilder builder = new StringBuilder();
builder.append(index).append(". ").append(word);
return builder.toString();
}
}
}

151
src/main/java/org/telegram/updateshandlers/RaeHandlers.java

@ -0,0 +1,151 @@
package org.telegram.updateshandlers;
import org.telegram.BotConfig;
import org.telegram.BuildVars;
import org.telegram.SenderHelper;
import org.telegram.api.methods.AnswerInlineQuery;
import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.*;
import org.telegram.services.BotLogger;
import org.telegram.services.RaeService;
import org.telegram.updatesreceivers.UpdatesThread;
import org.telegram.updatesreceivers.Webhook;
import java.io.InvalidObjectException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Handler for inline queries in Raebot
* This is a use case that works with both Webhooks and GetUpdates methods
* @date 24 of June of 2015
*/
public class RaeHandlers implements UpdatesCallback {
private static final String LOGTAG = "RAEHANDLERS";
private static final String TOKEN = BotConfig.TOKENRAE;
private static final String BOTNAME = BotConfig.USERNAMERAE;
private static final Integer CACHETIME = 86400;
private static final boolean USEWEBHOOK = true;
private final RaeService raeService;
private final Object webhookLock = new Object();
private final String THUMBNAILBLUE = "https://lh5.ggpht.com/-kSFHGvQkFivERzyCNgKPIECtIOELfPNWAQdXqQ7uqv2xztxqll4bVibI0oHJYAuAas=w300";
private static final String helpMessage = "Este bot puede ayudarte a buscar definiciones de palabras según el diccionario de la RAE.\n\n" +
"Funciona automáticamente, no hay necesidad de añadirlo a ningún sitio.\n" +
"Simplemente abre cualquiera de tus chats y escribe `@raebot loquesea` en la zona de escribir mensajes.\n" +
"Finalmente pulsa sobre un resultado para enviarlo." +
"\n\n" +
"Por ejemplo, intenta escribir `@raebot Punto` aquí.";
public RaeHandlers(Webhook webhook) {
raeService = new RaeService();
if (USEWEBHOOK && BuildVars.useWebHook) {
webhook.registerWebhook(this, BOTNAME);
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else {
SenderHelper.SendWebhook("", TOKEN);
new UpdatesThread(TOKEN, this);
}
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasInlineQuery()) {
BotApiMethod botApiMethod = handleIncomingInlineQuery(update.getInlineQuery());
try {
SenderHelper.SendApiMethod(botApiMethod, TOKEN);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} else if (update.hasMessage() && update.getMessage().isUserMessage()) {
try {
SenderHelper.SendApiMethod(getHelpMessage(update.getMessage()), TOKEN);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
}
}
@Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
if (update.hasInlineQuery()) {
synchronized (webhookLock) {
return handleIncomingInlineQuery(update.getInlineQuery());
}
} else if (update.hasMessage() && update.getMessage().isUserMessage()) {
synchronized (webhookLock) {
return getHelpMessage(update.getMessage());
}
}
return null;
}
/**
* For an InlineQuery, results from RAE dictionariy are fetch and returned
* @param inlineQuery InlineQuery recieved
* @return BotApiMethod as response to the inline query
*/
private BotApiMethod handleIncomingInlineQuery(InlineQuery inlineQuery) {
String query = inlineQuery.getQuery();
BotLogger.debug(LOGTAG, "Searching: " + query);
if (!query.isEmpty()) {
List<RaeService.RaeResult> results = raeService.getResults(query);
return converteResultsToResponse(inlineQuery, results);
} else {
return converteResultsToResponse(inlineQuery, new ArrayList<>());
}
}
/**
* Converts resutls from RaeService to an answer to an inline query
* @param inlineQuery Original inline query
* @param results Results from RAE service
* @return AnswerInlineQuery method to answer the query
*/
private BotApiMethod converteResultsToResponse(InlineQuery inlineQuery, List<RaeService.RaeResult> results) {
AnswerInlineQuery answerInlineQuery = new AnswerInlineQuery();
answerInlineQuery.setInlineQueryId(inlineQuery.getId());
answerInlineQuery.setCacheTime(CACHETIME);
answerInlineQuery.setResults(convertRaeResults(results));
return answerInlineQuery;
}
/**
* Converts results from RaeService to a list of InlineQueryResultArticles
* @param raeResults Results from rae service
* @return List of InlineQueryResult
*/
private List<InlineQueryResult> convertRaeResults(List<RaeService.RaeResult> raeResults) {
List<InlineQueryResult> results = new ArrayList<>();
for (int i = 0; i < raeResults.size(); i++) {
RaeService.RaeResult raeResult = raeResults.get(i);
InlineQueryResultArticle article = new InlineQueryResultArticle();
article.setDisableWebPagePreview(true);
article.setMarkdown(true);
article.setId(Integer.toString(i));
article.setMessageText(raeResult.getDefinition());
article.setTitle(raeResult.getTitle());
article.setDescription(raeResult.getDescription());
article.setThumbUrl(THUMBNAILBLUE);
results.add(article);
}
return results;
}
/**
* Create a help message when an user try to send messages directly to the bot
* @param message Received message
* @return SendMessage method
*/
public BotApiMethod getHelpMessage(Message message) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId().toString());
sendMessage.enableMarkdown(true);
sendMessage.setText(helpMessage);
return sendMessage;
}
}

20
src/main/java/org/telegram/updateshandlers/WeatherHandlers.java

@ -97,21 +97,23 @@ public class WeatherHandlers implements UpdatesCallback {
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
Message message = update.getMessage(); if (update.hasMessage()) {
if (message != null && (message.hasText() || message.hasLocation())) { Message message = update.getMessage();
BotApiMethod botApiMethod = handleIncomingMessage(message); if (message.hasText() || message.hasLocation()) {
try { BotApiMethod botApiMethod = handleIncomingMessage(message);
SenderHelper.SendApiMethod(botApiMethod, TOKEN); try {
} catch (InvalidObjectException e) { SenderHelper.SendApiMethod(botApiMethod, TOKEN);
BotLogger.error(LOGTAG, e); } catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }
} }
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public BotApiMethod onWebhookUpdateReceived(Update update) {
Message message = update.getMessage(); if (update.hasMessage()) {
if (message != null) { Message message = update.getMessage();
synchronized (webhookLock) { synchronized (webhookLock) {
return handleIncomingMessage(message); return handleIncomingMessage(message);
} }

Loading…
Cancel
Save