1. Update Telegram Bots API objects

This commit is contained in:
Rubenlagus 2016-09-29 00:44:03 +02:00
parent 732eb2850b
commit da2b7a083e
12 changed files with 228 additions and 50 deletions

View File

@ -6,7 +6,7 @@
<packaging>jar</packaging>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>2.3.8.BETA-SNAPSHOT</version>
<version>2.4.0.BETA2-SNAPSHOT</version>
<name>Telegram Bots</name>
<url>https://github.com/rubenlagus/TelegramBots</url>

View File

@ -11,6 +11,4 @@ public class Constants {
public static final int GETUPDATESTIMEOUT = 50;
public static final String RESPONSEFIELDOK = "ok";
public static final String RESPONSEFIELDRESULT = "result";
public static final String ERRORDESCRIPTIONFIELD = "description";
public static final String ERRORCODEFIELD = "error_code";
}

View File

@ -27,9 +27,6 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import static org.telegram.telegrambots.Constants.ERRORCODEFIELD;
import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD;
/**
* @author Ruben Bermudez
* @version 1.0
@ -52,10 +49,10 @@ public class TelegramBotsApi {
/**
*
* @param keyStore
* @param keyStorePassword
* @param externalUrl
* @param internalUrl
* @param keyStore KeyStore for the server
* @param keyStorePassword Key store password for the server
* @param externalUrl External base url for the webhook
* @param internalUrl Internal base url for the webhook
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiRequestException {
if (externalUrl == null || externalUrl.isEmpty()) {
@ -73,10 +70,10 @@ public class TelegramBotsApi {
/**
*
* @param keyStore
* @param keyStorePassword
* @param externalUrl
* @param internalUrl
* @param keyStore KeyStore for the server
* @param keyStorePassword Key store password for the server
* @param externalUrl External base url for the webhook
* @param internalUrl Internal base url for the webhook
* @param pathToCertificate Full path until .pem public certificate keys
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiRequestException {
@ -103,8 +100,8 @@ public class TelegramBotsApi {
}
/**
*
* @param bot
* Register a bot in the api that will receive updates using webhook method
* @param bot Bot to register
*/
public void registerBot(TelegramWebhookBot bot) throws TelegramApiRequestException {
if (useWebhook) {
@ -113,11 +110,6 @@ public class TelegramBotsApi {
}
}
/**
*
* @param externalUrl
* @return
*/
private static String fixExternalUrl(String externalUrl) {
if (externalUrl != null && !externalUrl.endsWith("/")) {
externalUrl = externalUrl + "/";
@ -165,7 +157,7 @@ public class TelegramBotsApi {
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException(webHookURL == null ? "Error removing old webhook" : "Error setting webhook", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException(webHookURL == null ? "Error removing old webhook" : "Error setting webhook", jsonObject);
}
}
} catch (JSONException e) {

View File

@ -38,7 +38,13 @@ public class AnswerCallbackQuery extends BotApiMethod<Boolean> {
@JsonProperty(SHOWALERT_FIELD)
private Boolean showAlert; ///< Optional. If true, an alert will be shown by the client instead of a notificaiton at the top of the chat screen. Defaults to false.
@JsonProperty(URL_FIELD)
private String url; ///< Optional. URL that will be opened by the user's client. To enable this option for your bot, please contact @Botfather, send the command /setcustomurls, and accept the terms.
/**
* Optional. URL that will be opened by the user's client.
* If you have created a Game and accepted the conditions via @Botfather,
* specify the URL that opens your game. Otherwise you may use links
* InlineQueryResultGamelike telegram.me/your_bot?start=XXXX that open your bot with a parameter.
*/
private String url;
public AnswerCallbackQuery() {
super();

View File

@ -36,11 +36,12 @@ import java.util.ArrayList;
* @brief Use this method to get data for high score tables.
* Will return the score of the specified user and several of his neighbors in a game.
* On success, returns an Array of GameHighScore objects.
* This method will currently return scores for the target user,
* plus two of his closest neighbors on each side. Will also return the top three users
* if he is not among the top three.
*
* @note This method will currently return scores for the target user,
* plus two of his closest neighbors on each side. Will also return the top three users
* if the user and his neighbors are not among them.
* Please note that this behavior is subject to change.
*
* @date 16 of September of 2016
*/
public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {

View File

@ -53,9 +53,16 @@ public class CallbackQuery implements IBotApiObject {
*/
private String data;
@JsonProperty(GAMESHORTNAME_FIELD)
private String gameShortName; ///< Optional. Game short name.
/**
* Optional. Short name of a Game to be returned, serves as the unique identifier for the game
*/
private String gameShortName;
@JsonProperty(CHAT_INSTANCE_FIELD)
private String chatInstance; ///< Identifier, uniquely corresponding to the chat a message with the callback button was sent to
/**
* Identifier, uniquely corresponding to the chat to which the message with the
* callback button was sent. Useful for high scores in games.
*/
private String chatInstance;
public CallbackQuery() {
super();

View File

@ -560,6 +560,13 @@ public class Message implements IBotApiObject {
if (game != null) {
gen.writeObjectField(GAME_FIELD, game);
}
if (entities != null) {
gen.writeArrayFieldStart(ENTITIES_FIELD);
for (MessageEntity entity : entities) {
gen.writeObject(entity);
}
gen.writeEndArray();
}
gen.writeEndObject();
gen.flush();
}

View File

@ -0,0 +1,91 @@
/*
* This file is part of TelegramBots.
*
* TelegramBots is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TelegramBots is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TelegramBots. If not, see <http://www.gnu.org/licenses/>.
*/
package org.telegram.telegrambots.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.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Contains information about why a request was unsuccessfull.
* @date 28 of September of 2016
*/
public class ResponseParameters implements IBotApiObject {
private static final String MIGRATETOCHATID_FIELD = "migrate_to_chat_id";
private static final String RETRYAFTER_FIELD = "retry_after";
@JsonProperty(MIGRATETOCHATID_FIELD)
/**
* Optional. The group has been migrated to a supergroup with the specified identifier.
* This number may be greater than 32 bits and some programming languages may have
* difficulty/silent defects in interpreting it. But it is smaller than 52 bits,
* so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
*/
private Integer migrateToChatId;
@JsonProperty(RETRYAFTER_FIELD)
/**
* Optional. In case of exceeding flood control a number of seconds to
* wait before the request can be repeated
*/
private Integer retryAfter;
public ResponseParameters(JSONObject object) {
if (object != null) {
if (object.has(MIGRATETOCHATID_FIELD)) {
migrateToChatId = object.getInt(MIGRATETOCHATID_FIELD);
}
if (object.has(RETRYAFTER_FIELD)) {
retryAfter = object.getInt(RETRYAFTER_FIELD);
}
}
}
public Integer getMigrateToChatId() {
return migrateToChatId;
}
public Integer getRetryAfter() {
return retryAfter;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
if (migrateToChatId != null) {
gen.writeNumberField(MIGRATETOCHATID_FIELD, migrateToChatId);
}
if (retryAfter != null) {
gen.writeNumberField(RETRYAFTER_FIELD, retryAfter);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

View File

@ -21,16 +21,21 @@ 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.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.objects.MessageEntity;
import org.telegram.telegrambots.api.objects.PhotoSize;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 2.4
* @brief This object represents a game.
* Use BotFather to create and edit games, their short names will act as unique identifiers.
* @date 27 of September of 2016
*/
public class Game implements IBotApiObject {
@ -38,13 +43,29 @@ public class Game implements IBotApiObject {
private static final String DESCRIPTION_FIELD = "description";
private static final String PHOTO_FIELD = "photo";
private static final String ANIMATION_FIELD = "animation";
private static final String TEXT_FIELD = "text";
private static final String TEXTENTITIES_FIELD = "text_entities";
@JsonProperty(TITLE_FIELD)
private String title; ///< Title of the game
@JsonProperty(DESCRIPTION_FIELD)
private String description; ///< Description of the game
@JsonProperty(PHOTO_FIELD)
private PhotoSize photo; ///< Photo
private List<PhotoSize> photo; ///< Photo
@JsonProperty(TEXT_FIELD)
/**
* Optional. Brief description of the game or high scores included in the game message.
* Can be automatically edited to include current high scores for the game
* when the bot calls setGameScore, or manually edited using editMessageText.
* 0-4096 characters.
*/
private String text;
@JsonProperty(TEXTENTITIES_FIELD)
/**
* Optional. Special entities that appear in text, such as usernames,
* URLs, bot commands, etc.
*/
private List<MessageEntity> entities;
@JsonProperty(ANIMATION_FIELD)
private Animation animation; ///< Optional. Animation
@ -56,8 +77,24 @@ public class Game implements IBotApiObject {
super();
title = object.getString(TITLE_FIELD);
description = object.getString(DESCRIPTION_FIELD);
photo = new PhotoSize(object.getJSONObject(PHOTO_FIELD));
animation = new Animation(object.getJSONObject(ANIMATION_FIELD));
this.photo = new ArrayList<>();
JSONArray photos = object.getJSONArray(PHOTO_FIELD);
for (int i = 0; i < photos.length(); i++) {
this.photo.add(new PhotoSize(photos.getJSONObject(i)));
}
if (object.has(TEXT_FIELD)) {
text = object.getString(TEXT_FIELD);
}
if (object.has(TEXTENTITIES_FIELD)) {
this.entities = new ArrayList<>();
JSONArray entities = object.getJSONArray(TEXTENTITIES_FIELD);
for (int i = 0; i < entities.length(); i++) {
this.entities.add(new MessageEntity(entities.getJSONObject(i)));
}
}
if (object.has(ANIMATION_FIELD)) {
animation = new Animation(object.getJSONObject(ANIMATION_FIELD));
}
}
public String getTitle() {
@ -68,7 +105,7 @@ public class Game implements IBotApiObject {
return description;
}
public PhotoSize getPhoto() {
public List<PhotoSize> getPhoto() {
return photo;
}
@ -76,13 +113,41 @@ public class Game implements IBotApiObject {
return animation;
}
public String getText() {
return text;
}
public boolean hasEntities() {
return entities != null && !entities.isEmpty();
}
public List<MessageEntity> getEntities() {
return entities;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TITLE_FIELD, title);
gen.writeStringField(DESCRIPTION_FIELD, description);
gen.writeObjectField(PHOTO_FIELD, photo);
gen.writeObjectField(ANIMATION_FIELD, animation);
gen.writeArrayFieldStart(PHOTO_FIELD);
for (PhotoSize photoSize : photo) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
if (animation != null) {
gen.writeObjectField(ANIMATION_FIELD, animation);
}
if (text != null) {
gen.writeStringField(TEXT_FIELD, text);
}
if (entities != null) {
gen.writeArrayFieldStart(TEXTENTITIES_FIELD);
for (MessageEntity entity : entities) {
gen.writeObject(entity);
}
gen.writeEndArray();
}
gen.writeEndObject();
gen.flush();
}

View File

@ -77,9 +77,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.telegram.telegrambots.Constants.ERRORCODEFIELD;
import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD;
/**
* @author Ruben Bermudez
* @version 1.0
@ -686,7 +683,7 @@ public abstract class AbsSender {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at sendDocument", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at sendDocument", jsonObject);
}
return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT));
@ -752,7 +749,7 @@ public abstract class AbsSender {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at sendPhoto", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at sendPhoto", jsonObject);
}
return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT));
@ -836,7 +833,7 @@ public abstract class AbsSender {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at sendVideo", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at sendVideo", jsonObject);
}
return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT));
@ -897,7 +894,7 @@ public abstract class AbsSender {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at sendSticker", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at sendSticker", jsonObject);
}
return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT));
@ -991,7 +988,7 @@ public abstract class AbsSender {
* {"description":"[Error]: Bad Request: chat not found","error_code":400,"ok":false}
*/
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at sendAudio", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at sendAudio", jsonObject);
}
// and if not, we can expect a "result" section. and out of this can a new Message object be built
@ -1072,7 +1069,7 @@ public abstract class AbsSender {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at sendVoice", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at sendVoice", jsonObject);
}
return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT));
@ -1131,7 +1128,7 @@ public abstract class AbsSender {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error at " + method.getPath(), jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD));
throw new TelegramApiRequestException("Error at " + method.getPath(), jsonObject);
}
return method.deserializeResponse(jsonObject);

View File

@ -17,6 +17,10 @@
package org.telegram.telegrambots.exceptions;
import org.json.JSONObject;
import org.telegram.telegrambots.api.objects.ResponseParameters;
/**
* @author Ruben Bermudez
* @version 1.0
@ -24,17 +28,25 @@ package org.telegram.telegrambots.exceptions;
* @date 14 of January of 2016
*/
public class TelegramApiRequestException extends TelegramApiException {
private static final String ERRORDESCRIPTIONFIELD = "description";
private static final String ERRORCODEFIELD = "error_code";
private static final String PARAMETERSFIELD = "parameters";
private String apiResponse = null;
private Integer errorCode = 0;
private ResponseParameters parameters;
public TelegramApiRequestException(String message) {
super(message);
}
public TelegramApiRequestException(String message, String apiResponse, Integer errorCode) {
public TelegramApiRequestException(String message, JSONObject object) {
super(message);
this.apiResponse = apiResponse;
this.errorCode = errorCode;
apiResponse = object.getString(ERRORDESCRIPTIONFIELD);
errorCode = object.getInt(ERRORCODEFIELD);
if (object.has(PARAMETERSFIELD)) {
parameters = new ResponseParameters(object.getJSONObject(PARAMETERSFIELD));
}
}
public TelegramApiRequestException(String message, Throwable cause) {
@ -49,6 +61,10 @@ public class TelegramApiRequestException extends TelegramApiException {
return errorCode;
}
public ResponseParameters getParameters() {
return parameters;
}
@Override
public String toString() {
if (apiResponse == null) {

View File

@ -123,9 +123,7 @@ public class BotSession {
try {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException("Error getting updates",
jsonObject.getString(Constants.ERRORDESCRIPTIONFIELD),
jsonObject.getInt(Constants.ERRORCODEFIELD));
throw new TelegramApiRequestException("Error getting updates", jsonObject);
}
JSONArray jsonArray = jsonObject.getJSONArray(Constants.RESPONSEFIELDRESULT);
if (jsonArray.length() != 0) {