Browse Source

Merge dev branch

master
Rubenlagus 10 years ago
parent
commit
835a71166b
  1. 35
      .gitignore
  2. 1
      .idea/dataSources.xml
  3. 11
      .idea/resourceBundles.xml
  4. 870
      .idea/workspace.xml
  5. 12
      src/main/java/org/telegram/BotConfig.java
  6. 8
      src/main/java/org/telegram/Main.java
  7. 60
      src/main/java/org/telegram/SenderHelper.java
  8. 138
      src/main/java/org/telegram/api/methods/AnswerInlineQuery.java
  9. 16
      src/main/java/org/telegram/api/methods/ForwardMessage.java
  10. 7
      src/main/java/org/telegram/api/methods/GetFile.java
  11. 4
      src/main/java/org/telegram/api/methods/GetMe.java
  12. 11
      src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java
  13. 6
      src/main/java/org/telegram/api/methods/SendAudio.java
  14. 13
      src/main/java/org/telegram/api/methods/SendChatAction.java
  15. 6
      src/main/java/org/telegram/api/methods/SendDocument.java
  16. 24
      src/main/java/org/telegram/api/methods/SendLocation.java
  17. 30
      src/main/java/org/telegram/api/methods/SendMessage.java
  18. 6
      src/main/java/org/telegram/api/methods/SendPhoto.java
  19. 6
      src/main/java/org/telegram/api/methods/SendSticker.java
  20. 6
      src/main/java/org/telegram/api/methods/SendVideo.java
  21. 18
      src/main/java/org/telegram/api/objects/Audio.java
  22. 90
      src/main/java/org/telegram/api/objects/Chat.java
  23. 66
      src/main/java/org/telegram/api/objects/ChosenInlineQuery.java
  24. 12
      src/main/java/org/telegram/api/objects/Contact.java
  25. 15
      src/main/java/org/telegram/api/objects/Document.java
  26. 11
      src/main/java/org/telegram/api/objects/File.java
  27. 6
      src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java
  28. 76
      src/main/java/org/telegram/api/objects/InlineQuery.java
  29. 13
      src/main/java/org/telegram/api/objects/InlineQueryResult.java
  30. 233
      src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java
  31. 213
      src/main/java/org/telegram/api/objects/InlineQueryResultGif.java
  32. 214
      src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java
  33. 249
      src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java
  34. 245
      src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java
  35. 6
      src/main/java/org/telegram/api/objects/Location.java
  36. 170
      src/main/java/org/telegram/api/objects/Message.java
  37. 10
      src/main/java/org/telegram/api/objects/PhotoSize.java
  38. 6
      src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java
  39. 22
      src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java
  40. 13
      src/main/java/org/telegram/api/objects/Sticker.java
  41. 60
      src/main/java/org/telegram/api/objects/Update.java
  42. 12
      src/main/java/org/telegram/api/objects/User.java
  43. 16
      src/main/java/org/telegram/api/objects/UserProfilePhotos.java
  44. 17
      src/main/java/org/telegram/api/objects/Video.java
  45. 12
      src/main/java/org/telegram/api/objects/Voice.java
  46. 8
      src/main/java/org/telegram/database/ConectionDB.java
  47. 4
      src/main/java/org/telegram/database/CreationStrings.java
  48. 25
      src/main/java/org/telegram/database/DatabaseManager.java
  49. 378
      src/main/java/org/telegram/services/BotLogger.java
  50. 5
      src/main/java/org/telegram/services/DirectionsService.java
  51. 11
      src/main/java/org/telegram/services/LocalisationService.java
  52. 231
      src/main/java/org/telegram/services/RaeService.java
  53. 14
      src/main/java/org/telegram/services/TimerExecutor.java
  54. 32
      src/main/java/org/telegram/services/TransifexService.java
  55. 26
      src/main/java/org/telegram/services/WeatherService.java
  56. 184
      src/main/java/org/telegram/updateshandlers/ChannelHandlers.java
  57. 42
      src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java
  58. 61
      src/main/java/org/telegram/updateshandlers/FilesHandlers.java
  59. 151
      src/main/java/org/telegram/updateshandlers/RaeHandlers.java
  60. 31
      src/main/java/org/telegram/updateshandlers/TransifexHandlers.java
  61. 155
      src/main/java/org/telegram/updateshandlers/WeatherHandlers.java
  62. 20
      src/main/java/org/telegram/updatesreceivers/UpdatesThread.java
  63. 6
      src/main/java/org/telegram/updatesreceivers/Webhook.java
  64. 75
      src/main/resources/localisation/strings_eo.properties

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

1
.idea/dataSources.xml

@ -13,6 +13,7 @@
<property name="characterSetResults" value="utf8" /> <property name="characterSetResults" value="utf8" />
<property name="yearIsDateType" value="false" /> <property name="yearIsDateType" value="false" />
</driver-properties> </driver-properties>
<libraries />
</data-source> </data-source>
</component> </component>
</project> </project>

11
.idea/resourceBundles.xml

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ResourceBundleManager">
<file url="file://$PROJECT_DIR$/src/main/resources/localisation/strings.properties" />
<file url="file://$PROJECT_DIR$/src/main/resources/localisation/strings_eo.properties" />
<file url="file://$PROJECT_DIR$/src/main/resources/localisation/strings_es.properties" />
<file url="file://$PROJECT_DIR$/src/main/resources/localisation/strings_it.properties" />
<file url="file://$PROJECT_DIR$/src/main/resources/localisation/strings_nl.properties" />
<file url="file://$PROJECT_DIR$/src/main/resources/localisation/strings_pt.properties" />
</component>
</project>

870
.idea/workspace.xml

File diff suppressed because it is too large

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

@ -7,12 +7,16 @@ package org.telegram;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class BotConfig { public class BotConfig {
public static final String TOKENWEATHER = "<bot-token>"; public static final String TOKENWEATHER = "<token>";
public static final String USERNAMEWEATHER = "weatherbot"; public static final String USERNAMEWEATHER = "weatherbot";
public static final String TOKENTRANSIFEX = "<bot-token>"; public static final String TOKENTRANSIFEX = "<token>";
public static final String USERNAMETRANSIFEX = "TGlanguagesbot"; public static final String USERNAMETRANSIFEX = "TGlanguagesbot";
public static final String TOKENFILES = "<bot-token>"; public static final String TOKENFILES = "<token>";
public static final String USERNAMEFILES = "filesbot"; public static final String USERNAMEFILES = "filesbot";
public static final String TOKENDIRECTIONS = "<bot-token>"; public static final String TOKENDIRECTIONS = "<token>";
public static final String USERNAMEDIRECTIONS = "directionsbot"; public static final String USERNAMEDIRECTIONS = "directionsbot";
public static final String TOKENCHANNEL = "<token>";
public static final String USERNAMECHANNEL = "channelupdatesbot";
public static final String TOKENRAE = "<token>";
public static final String USERNAMERAE = "raebot";
} }

8
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,15 +21,16 @@ public class Main {
initBots(); initBots();
if (BuildVars.useWebHook) { if (BuildVars.useWebHook) {
webhook.startDebugServer(); webhook.startServer();
//webhook.startServer();
} }
} }
private static void initBots() { private static void initBots() {
UpdatesCallback weatherBot = new WeatherHandlers(webhook); UpdatesCallback weatherBot = new WeatherHandlers(webhook);
UpdatesCallback channelBot = new ChannelHandlers(webhook);
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);
} }
} }

60
src/main/java/org/telegram/SenderHelper.java

@ -16,7 +16,6 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.api.methods.*; import org.telegram.api.methods.*;
import org.telegram.services.BotLogger; import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.SentCallback; import org.telegram.updateshandlers.SentCallback;
@ -24,10 +23,8 @@ import org.telegram.updateshandlers.SentCallback;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -38,7 +35,7 @@ import java.util.concurrent.Executors;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class SenderHelper { public class SenderHelper {
private static volatile BotLogger log = BotLogger.getLogger(SenderHelper.class.getName()); private static final String LOGTAG = "SENDERHELPER";
private static final ExecutorService exe = Executors.newSingleThreadExecutor(); private static final ExecutorService exe = Executors.newSingleThreadExecutor();
public static void SendDocument(SendDocument sendDocument, String botToken) { public static void SendDocument(SendDocument sendDocument, String botToken) {
@ -49,7 +46,7 @@ public class SenderHelper {
if (sendDocument.isNewDocument()) { if (sendDocument.isNewDocument()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId().toString()); builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId());
builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName());
if (sendDocument.getReplayMarkup() != null) { if (sendDocument.getReplayMarkup() != null) {
builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString()); builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString());
@ -61,7 +58,7 @@ public class SenderHelper {
httppost.setEntity(multipart); httppost.setEntity(multipart);
} else { } else {
List<NameValuePair> nameValuePairs = new ArrayList<>(); List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId().toString())); nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendDocument.DOCUMENT_FIELD, sendDocument.getDocument())); nameValuePairs.add(new BasicNameValuePair(SendDocument.DOCUMENT_FIELD, sendDocument.getDocument()));
if (sendDocument.getReplayMarkup() != null) { if (sendDocument.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toString())); nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toString()));
@ -73,12 +70,13 @@ public class SenderHelper {
} }
CloseableHttpResponse response = httpClient.execute(httppost); CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
} finally {
if (sendDocument.isNewDocument()) { if (sendDocument.isNewDocument()) {
File fileToDelete = new File(sendDocument.getDocument()); File fileToDelete = new File(sendDocument.getDocument());
fileToDelete.delete(); fileToDelete.delete();
} }
} catch (IOException e) {
log.error(e);
} }
} }
@ -90,7 +88,7 @@ public class SenderHelper {
if (sendPhoto.isNewPhoto()) { if (sendPhoto.isNewPhoto()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId().toString()); builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId());
builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName());
if (sendPhoto.getReplayMarkup() != null) { if (sendPhoto.getReplayMarkup() != null) {
builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString()); builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString());
@ -105,7 +103,7 @@ public class SenderHelper {
httppost.setEntity(multipart); httppost.setEntity(multipart);
} else { } else {
List<NameValuePair> nameValuePairs = new ArrayList<>(); List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId().toString())); nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendPhoto.PHOTO_FIELD, sendPhoto.getPhoto())); nameValuePairs.add(new BasicNameValuePair(SendPhoto.PHOTO_FIELD, sendPhoto.getPhoto()));
if (sendPhoto.getReplayMarkup() != null) { if (sendPhoto.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toString())); nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toString()));
@ -121,7 +119,7 @@ public class SenderHelper {
CloseableHttpResponse response = httpClient.execute(httppost); CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
@ -133,7 +131,7 @@ public class SenderHelper {
if (sendVideo.isNewVideo()) { if (sendVideo.isNewVideo()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId().toString()); builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId());
builder.addBinaryBody(SendVideo.VIDEO_FIELD, new File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); builder.addBinaryBody(SendVideo.VIDEO_FIELD, new File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName());
if (sendVideo.getReplayMarkup() != null) { if (sendVideo.getReplayMarkup() != null) {
builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString()); builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString());
@ -151,7 +149,7 @@ public class SenderHelper {
httppost.setEntity(multipart); httppost.setEntity(multipart);
} else { } else {
List<NameValuePair> nameValuePairs = new ArrayList<>(); List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId().toString())); nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendVideo.VIDEO_FIELD, sendVideo.getVideo())); nameValuePairs.add(new BasicNameValuePair(SendVideo.VIDEO_FIELD, sendVideo.getVideo()));
if (sendVideo.getReplayMarkup() != null) { if (sendVideo.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toString())); nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toString()));
@ -170,7 +168,7 @@ public class SenderHelper {
CloseableHttpResponse response = httpClient.execute(httppost); CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
@ -182,7 +180,7 @@ public class SenderHelper {
if (sendSticker.isNewSticker()) { if (sendSticker.isNewSticker()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId().toString()); builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId());
builder.addBinaryBody(SendSticker.STICKER_FIELD, new File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); builder.addBinaryBody(SendSticker.STICKER_FIELD, new File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName());
if (sendSticker.getReplayMarkup() != null) { if (sendSticker.getReplayMarkup() != null) {
builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString()); builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString());
@ -194,7 +192,7 @@ public class SenderHelper {
httppost.setEntity(multipart); httppost.setEntity(multipart);
} else { } else {
List<NameValuePair> nameValuePairs = new ArrayList<>(); List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId().toString())); nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendSticker.STICKER_FIELD, sendSticker.getSticker())); nameValuePairs.add(new BasicNameValuePair(SendSticker.STICKER_FIELD, sendSticker.getSticker()));
if (sendSticker.getReplayMarkup() != null) { if (sendSticker.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toString())); nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toString()));
@ -206,14 +204,14 @@ public class SenderHelper {
} }
CloseableHttpResponse response = httpClient.execute(httppost); CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
} finally {
if (sendSticker.isNewSticker()) { if (sendSticker.isNewSticker()) {
File fileToDelete = new File(sendSticker.getSticker()); File fileToDelete = new File(sendSticker.getSticker());
fileToDelete.delete(); fileToDelete.delete();
} }
} catch (IOException e) {
log.error(e);
} }
} }
public static void SendWebhook(String webHookURL, String botToken) { public static void SendWebhook(String webHookURL, String botToken) {
@ -233,14 +231,15 @@ public class SenderHelper {
HttpEntity ht = response.getEntity(); HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht); BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8"); String responseContent = EntityUtils.toString(buf, "UTF-8");
log.debug(responseContent); BotLogger.debug(LOGTAG, responseContent);
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
public static void SendApiMethod(BotApiMethod method, String botToken) { public static void SendApiMethod(BotApiMethod method, String botToken) throws InvalidObjectException {
String responseContent = "{}";
try { try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + method.getPath(); String url = Constants.BASEURL + botToken + "/" + method.getPath();
@ -250,15 +249,16 @@ public class SenderHelper {
CloseableHttpResponse response = httpclient.execute(httppost); CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity(); HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht); BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8"); responseContent = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new InvalidObjectException(jsonObject.toString());
}
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new InvalidObjectException(jsonObject.getString("description"));
}
} }
public static void SendApiMethodAsync(BotApiMethod method, String botToken, SentCallback callback) { public static void SendApiMethodAsync(BotApiMethod method, String botToken, SentCallback callback) {
@ -280,7 +280,7 @@ public class SenderHelper {
} }
callback.onResult(method, jsonObject); callback.onResult(method, jsonObject);
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
}); });
} }

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

16
src/main/java/org/telegram/api/methods/ForwardMessage.java

@ -18,7 +18,7 @@ public class ForwardMessage extends BotApiMethod<Message> {
public static final String PATH = "forwardmessage"; public static final String PATH = "forwardmessage";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels)
public static final String FROMCHATID_FIELD = "from_chat_id"; public static final String FROMCHATID_FIELD = "from_chat_id";
private Integer fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id private Integer fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id
public static final String MESSAGEID_FIELD = "message_id"; public static final String MESSAGEID_FIELD = "message_id";
@ -28,11 +28,11 @@ public class ForwardMessage extends BotApiMethod<Message> {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }
@ -56,7 +56,7 @@ public class ForwardMessage extends BotApiMethod<Message> {
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH); gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(CHATID_FIELD, chatId); gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(FROMCHATID_FIELD, fromChatId); gen.writeNumberField(FROMCHATID_FIELD, fromChatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId); gen.writeNumberField(MESSAGEID_FIELD, messageId);
gen.writeEndObject(); gen.writeEndObject();
@ -65,13 +65,7 @@ public class ForwardMessage extends BotApiMethod<Message> {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(CHATID_FIELD, chatId);
gen.writeNumberField(FROMCHATID_FIELD, fromChatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
gen.writeEndObject();
gen.flush();
} }
@Override @Override

7
src/main/java/org/telegram/api/methods/GetFile.java

@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.api.objects.File; import org.telegram.api.objects.File;
import org.telegram.api.objects.Message;
import java.io.IOException; import java.io.IOException;
@ -50,11 +49,7 @@ public class GetFile extends BotApiMethod<File> {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeEndObject();
gen.flush();
} }
@Override @Override

4
src/main/java/org/telegram/api/methods/GetMe.java

@ -45,8 +45,6 @@ public class GetMe extends BotApiMethod<User> {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeEndObject();
} }
} }

11
src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java

@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.UserProfilePhotos; import org.telegram.api.objects.UserProfilePhotos;
import java.io.IOException; import java.io.IOException;
@ -98,14 +97,6 @@ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(USERID_FIELD, userId);
gen.writeNumberField(OFFSET_FIELD, offset);
if (limit != null) {
gen.writeNumberField(LIMIT_FIELD, limit);
}
gen.writeEndObject();
gen.flush();
} }
} }

6
src/main/java/org/telegram/api/methods/SendAudio.java

@ -21,7 +21,7 @@ public class SendAudio {
public static final String PATH = "sendaudio"; public static final String PATH = "sendaudio";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (or Username fro channels)
public static final String AUDIO_FIELD = "audio"; public static final String AUDIO_FIELD = "audio";
private String audio; ///< Audio file to send. file_id as String to resend an audio that is already on the Telegram servers private String audio; ///< Audio file to send. file_id as String to resend an audio that is already on the Telegram servers
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
@ -39,11 +39,11 @@ public class SendAudio {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }

13
src/main/java/org/telegram/api/methods/SendChatAction.java

@ -20,7 +20,7 @@ public class SendChatAction extends BotApiMethod<Boolean>{
public static final String PATH = "sendChatAction"; public static final String PATH = "sendChatAction";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public static final String ACTION_FIELD = "action"; public static final String ACTION_FIELD = "action";
/** /**
* Type of action to broadcast. * Type of action to broadcast.
@ -34,11 +34,11 @@ public class SendChatAction extends BotApiMethod<Boolean>{
*/ */
private String action; private String action;
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }
@ -74,16 +74,13 @@ public class SendChatAction extends BotApiMethod<Boolean>{
@Override @Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
gen.writeNumberField(CHATID_FIELD, chatId); gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(ACTION_FIELD, action); gen.writeStringField(ACTION_FIELD, action);
gen.writeEndObject(); gen.writeEndObject();
} }
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeNumberField(CHATID_FIELD, chatId);
gen.writeStringField(ACTION_FIELD, action);
gen.writeEndObject();
} }
} }

6
src/main/java/org/telegram/api/methods/SendDocument.java

@ -12,7 +12,7 @@ public class SendDocument {
public static final String PATH = "senddocument"; public static final String PATH = "senddocument";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to or Username for the channel to send the message to
public static final String DOCUMENT_FIELD = "document"; public static final String DOCUMENT_FIELD = "document";
private String document; ///< File file to send. file_id as String to resend a file that is already on the Telegram servers private String document; ///< File file to send. file_id as String to resend a file that is already on the Telegram servers
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
@ -27,11 +27,11 @@ public class SendDocument {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }

24
src/main/java/org/telegram/api/methods/SendLocation.java

@ -19,7 +19,7 @@ public class SendLocation extends BotApiMethod<Message> {
public static final String PATH = "sendlocation"; public static final String PATH = "sendlocation";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public static final String LATITUDE_FIELD = "latitude"; public static final String LATITUDE_FIELD = "latitude";
private Float latitude; ///< Latitude of location private Float latitude; ///< Latitude of location
public static final String LONGITUDE_FIELD = "longitude"; public static final String LONGITUDE_FIELD = "longitude";
@ -29,11 +29,11 @@ public class SendLocation extends BotApiMethod<Message> {
public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }
@ -85,7 +85,6 @@ public class SendLocation extends BotApiMethod<Message> {
@Override @Override
public JSONObject toJson() { public JSONObject toJson() {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId); jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(LATITUDE_FIELD, latitude); jsonObject.put(LATITUDE_FIELD, latitude);
jsonObject.put(LONGITUDE_FIELD, longitude); jsonObject.put(LONGITUDE_FIELD, longitude);
@ -103,7 +102,7 @@ public class SendLocation extends BotApiMethod<Message> {
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH); gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(CHATID_FIELD, chatId); gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(LATITUDE_FIELD, latitude); gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeNumberField(LONGITUDE_FIELD, longitude); gen.writeNumberField(LONGITUDE_FIELD, longitude);
if (replayToMessageId != null) { if (replayToMessageId != null) {
@ -119,19 +118,6 @@ public class SendLocation extends BotApiMethod<Message> {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(CHATID_FIELD, chatId);
gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeNumberField(LONGITUDE_FIELD, longitude);
if (replayToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId);
}
if (replayMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup);
}
gen.writeEndObject();
gen.flush();
} }
} }

30
src/main/java/org/telegram/api/methods/SendMessage.java

@ -19,7 +19,7 @@ public class SendMessage extends BotApiMethod<Message> {
public static final String PATH = "sendmessage"; public static final String PATH = "sendmessage";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public static final String TEXT_FIELD = "text"; public static final String TEXT_FIELD = "text";
private String text; ///< Text of the message to be sent private String text; ///< Text of the message to be sent
public static final String PARSEMODE_FIELD = "parse_mode"; public static final String PARSEMODE_FIELD = "parse_mode";
@ -35,11 +35,11 @@ public class SendMessage extends BotApiMethod<Message> {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }
@ -86,7 +86,6 @@ public class SendMessage extends BotApiMethod<Message> {
@Override @Override
public JSONObject toJson() { public JSONObject toJson() {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId); jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(TEXT_FIELD, text); jsonObject.put(TEXT_FIELD, text);
if (parseMode != null) { if (parseMode != null) {
@ -122,7 +121,7 @@ public class SendMessage extends BotApiMethod<Message> {
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH); gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(CHATID_FIELD, chatId); gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(TEXT_FIELD, text); gen.writeStringField(TEXT_FIELD, text);
if (parseMode != null) { if (parseMode != null) {
@ -144,25 +143,6 @@ public class SendMessage extends BotApiMethod<Message> {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(CHATID_FIELD, chatId);
gen.writeStringField(TEXT_FIELD, text);
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview);
}
if (replayToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId);
}
if (replayMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup);
}
gen.writeEndObject();
gen.flush();
} }
} }

6
src/main/java/org/telegram/api/methods/SendPhoto.java

@ -12,7 +12,7 @@ public class SendPhoto {
public static final String PATH = "sendphoto"; public static final String PATH = "sendphoto";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public static final String PHOTO_FIELD = "photo"; public static final String PHOTO_FIELD = "photo";
private String photo; ///< Photo to send. file_id as String to resend a photo that is already on the Telegram servers private String photo; ///< Photo to send. file_id as String to resend a photo that is already on the Telegram servers
public static final String CAPTION_FIELD = "photo"; public static final String CAPTION_FIELD = "photo";
@ -30,11 +30,11 @@ public class SendPhoto {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }

6
src/main/java/org/telegram/api/methods/SendSticker.java

@ -12,7 +12,7 @@ public class SendSticker {
public static final String PATH = "sendsticker"; public static final String PATH = "sendsticker";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public static final String STICKER_FIELD = "sticker"; public static final String STICKER_FIELD = "sticker";
private String sticker; ///< Sticker file to send. file_id as String to resend a sticker that is already on the Telegram servers private String sticker; ///< Sticker file to send. file_id as String to resend a sticker that is already on the Telegram servers
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
@ -27,11 +27,11 @@ public class SendSticker {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }

6
src/main/java/org/telegram/api/methods/SendVideo.java

@ -14,7 +14,7 @@ public class SendVideo {
public static final String PATH = "sendvideo"; public static final String PATH = "sendvideo";
public static final String CHATID_FIELD = "chat_id"; public static final String CHATID_FIELD = "chat_id";
private Integer chatId; ///< Unique identifier for the message recepient — User or GroupChat id private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public static final String VIDEO_FIELD = "video"; public static final String VIDEO_FIELD = "video";
private String video; ///< Video to send. file_id as String to resend a video that is already on the Telegram servers private String video; ///< Video to send. file_id as String to resend a video that is already on the Telegram servers
public static final String DURATION_FIELD = "duration"; public static final String DURATION_FIELD = "duration";
@ -33,11 +33,11 @@ public class SendVideo {
super(); super();
} }
public Integer getChatId() { public String getChatId() {
return chatId; return chatId;
} }
public void setChatId(Integer chatId) { public void setChatId(String chatId) {
this.chatId = chatId; this.chatId = chatId;
} }

18
src/main/java/org/telegram/api/objects/Audio.java

@ -129,22 +129,6 @@ public class Audio implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(DURATION_FIELD, duration);
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
if (title != null) {
gen.writeStringField(TITLE_FIELD, title);
}
if (performer != null) {
gen.writeStringField(PERFORMER_FIELD, performer);
}
gen.writeEndObject();
gen.flush();
} }
} }

90
src/main/java/org/telegram/api/objects/Chat.java

@ -16,22 +16,29 @@ import java.io.IOException;
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class Chat implements BotApiObject { public class Chat implements BotApiObject {
private static final String USERCHATTYPE = "private";
private static final String GROUPCHATTYPE = "group";
private static final String CHANNELCHATTYPE = "channel";
private static final String SUPERGROUPCHATTYPE = "supergroup";
public static final String ID_FIELD = "id"; public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD) @JsonProperty(ID_FIELD)
private Integer id; ///< Unique identifier for this chat private Long id; ///< Unique identifier for this chat, not exciding 1e13 by absolute value
public static final String TYPE_FIELD = "type";
@JsonProperty(TYPE_FIELD)
private String type; ///< Type of the chat, one of “private”, “group” or “channel”
public static final String TITLE_FIELD = "title"; public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD) @JsonProperty(TITLE_FIELD)
private String title; ///< Group name private String title; ///< Optional. Title of the chat, only for channels and group chat
public static final String FIRSTNAME_FIELD = "first_name"; public static final String FIRSTNAME_FIELD = "first_name";
@JsonProperty(FIRSTNAME_FIELD) @JsonProperty(FIRSTNAME_FIELD)
private String firstName; ///< User‘s or bot’s first name private String firstName; ///< Optional. Username of the chat, only for private chats and channels if available
public static final String LASTNAME_FIELD = "last_name"; public static final String LASTNAME_FIELD = "last_name";
@JsonProperty(LASTNAME_FIELD) @JsonProperty(LASTNAME_FIELD)
private String lastName; ///< Optional. User‘s or bot’s last name private String lastName; ///< Optional. Interlocutor's first name for private chats
public static final String USERNAME_FIELD = "username"; public static final String USERNAME_FIELD = "username";
@JsonProperty(USERNAME_FIELD) @JsonProperty(USERNAME_FIELD)
private String userName; ///< Optional. User‘s or bot’s username private String userName; ///< Optional. Interlocutor's last name for private chats
public Chat() { public Chat() {
super(); super();
@ -39,30 +46,40 @@ public class Chat implements BotApiObject {
public Chat(JSONObject jsonObject) { public Chat(JSONObject jsonObject) {
super(); super();
this.id = jsonObject.getInt(ID_FIELD); this.id = jsonObject.getLong(ID_FIELD);
if (this.id > 0) { this.type = jsonObject.getString(TYPE_FIELD);
this.firstName = jsonObject.getString(FIRSTNAME_FIELD); if (jsonObject.has(TITLE_FIELD)) {
if (jsonObject.has(LASTNAME_FIELD)) {
this.lastName = jsonObject.getString(LASTNAME_FIELD);
}
if (jsonObject.has(USERNAME_FIELD)) {
this.userName = jsonObject.getString(USERNAME_FIELD);
}
} else {
this.title = jsonObject.getString(TITLE_FIELD); this.title = jsonObject.getString(TITLE_FIELD);
} }
if (jsonObject.has(FIRSTNAME_FIELD)) {
this.firstName = jsonObject.getString(FIRSTNAME_FIELD);
}
if (jsonObject.has(LASTNAME_FIELD)) {
this.lastName = jsonObject.getString(LASTNAME_FIELD);
}
if (jsonObject.has(USERNAME_FIELD)) {
this.userName = jsonObject.getString(USERNAME_FIELD);
}
} }
public Integer getId() { public Long getId() {
return id; return id;
} }
public Boolean isGroupChat() { public Boolean isGroupChat() {
if (id < 0) { return GROUPCHATTYPE.equals(type);
return true; }
} else {
return false; public Boolean isChannelChat() {
} return CHANNELCHATTYPE.equals(type);
}
public Boolean isUserChat() {
return USERCHATTYPE.equals(type);
}
public Boolean isSuperGroupChat() {
return SUPERGROUPCHATTYPE.equals(type);
} }
public String getTitle() { public String getTitle() {
@ -85,12 +102,21 @@ public class Chat implements BotApiObject {
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
gen.writeNumberField(ID_FIELD, id); gen.writeNumberField(ID_FIELD, id);
if (id > 0) { gen.writeStringField(TYPE_FIELD, type);
gen.writeStringField(FIRSTNAME_FIELD, firstName); if (isUserChat()) {
gen.writeStringField(LASTNAME_FIELD, lastName); if (firstName != null) {
gen.writeStringField(USERNAME_FIELD, userName); gen.writeStringField(FIRSTNAME_FIELD, firstName);
}
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
} else { } else {
gen.writeStringField(TITLE_FIELD, title); if (title != null) {
gen.writeStringField(TITLE_FIELD, title);
}
}
if (!isGroupChat() && userName != null) {
gen.writeStringField(USERNAME_FIELD, userName);
} }
gen.writeEndObject(); gen.writeEndObject();
gen.flush(); gen.flush();
@ -98,16 +124,6 @@ public class Chat implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeNumberField(ID_FIELD, id);
if (id > 0) {
gen.writeStringField(FIRSTNAME_FIELD, firstName);
gen.writeStringField(LASTNAME_FIELD, lastName);
gen.writeStringField(USERNAME_FIELD, userName);
} else {
gen.writeStringField(TITLE_FIELD, title);
}
gen.writeEndObject();
gen.flush();
} }
} }

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

12
src/main/java/org/telegram/api/objects/Contact.java

@ -63,16 +63,6 @@ public class Contact implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(PHONENUMBER_FIELD, phoneNumber);
gen.writeStringField(FIRSTNAME_FIELD, firstName);
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
if (userID != null) {
gen.writeNumberField(USERID_FIELD, userID);
}
gen.writeEndObject();
gen.flush();
} }
} }

15
src/main/java/org/telegram/api/objects/Document.java

@ -114,19 +114,6 @@ public class Document implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeObjectField(THUMB_FIELD, thumb);
if (fileName != null) {
gen.writeStringField(FILENAME_FIELD, fileName);
}
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
} }
} }

11
src/main/java/org/telegram/api/objects/File.java

@ -81,15 +81,6 @@ public class File implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILE_ID, fileId);
if (fileSize != null) {
gen.writeNumberField(FILE_SIZE_FIELD, fileSize);
}
if (filePath != null) {
gen.writeStringField(FILE_PATH_FIELD, filePath);
}
gen.writeEndObject();
gen.flush();
} }
} }

6
src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java

@ -89,10 +89,6 @@ public class ForceReplyKeyboard implements ReplyKeyboard {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeBooleanField(FORCEREPLY_FIELD, forceReply);
gen.writeBooleanField(SELECTIVE_FIELD, selective);
gen.writeEndObject();
gen.flush();
} }
} }

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

6
src/main/java/org/telegram/api/objects/Location.java

@ -61,10 +61,6 @@ public class Location implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeNumberField(LONGITUDE_FIELD, longitude);
gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeEndObject();
gen.flush();
} }
} }

170
src/main/java/org/telegram/api/objects/Message.java

@ -24,17 +24,13 @@ public class Message implements BotApiObject {
private Integer messageId; ///< Integer Unique message identifier private Integer messageId; ///< Integer Unique message identifier
public static final String FROM_FIELD = "from"; public static final String FROM_FIELD = "from";
@JsonProperty(FROM_FIELD) @JsonProperty(FROM_FIELD)
private User from; ///< Sender private User from; ///< Optional. Sender, can be empty for messages sent to channels
public static final String DATE_FIELD = "date"; public static final String DATE_FIELD = "date";
@JsonProperty(DATE_FIELD) @JsonProperty(DATE_FIELD)
private Integer date; ///< Date the message was sent in Unix time private Integer date; ///< Date the message was sent in Unix time
public static final String CHAT_FIELD = "chat"; public static final String CHAT_FIELD = "chat";
/**
* Conversation the message belongs to in case of a private message (@see User)or
* Conversation the message belongs to in case of a group (@see GroupChat)
*/
@JsonProperty(CHAT_FIELD) @JsonProperty(CHAT_FIELD)
private Chat chat; ///< Conversation the message belongs to in case of a private message private Chat chat; ///< Conversation the message belongs to
public static final String FORWARDFROM_FIELD = "forward_from"; public static final String FORWARDFROM_FIELD = "forward_from";
@JsonProperty(FORWARDFROM_FIELD) @JsonProperty(FORWARDFROM_FIELD)
private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message
@ -73,13 +69,13 @@ public class Message implements BotApiObject {
private User leftChatParticipant; ///< Optional. A member was removed from the group, information about them (this member may be bot itself) private User leftChatParticipant; ///< Optional. A member was removed from the group, information about them (this member may be bot itself)
public static final String NEWCHATTITLE_FIELD = "new_chat_title"; public static final String NEWCHATTITLE_FIELD = "new_chat_title";
@JsonProperty(NEWCHATTITLE_FIELD) @JsonProperty(NEWCHATTITLE_FIELD)
private String newChatTitle; ///< Optional. A group title was changed to this value private String newChatTitle; ///< Optional. A chat title was changed to this value
public static final String NEWCHATPHOTO_FIELD = "new_chat_photo"; public static final String NEWCHATPHOTO_FIELD = "new_chat_photo";
@JsonProperty(NEWCHATPHOTO_FIELD) @JsonProperty(NEWCHATPHOTO_FIELD)
private List<PhotoSize> newChatPhoto; ///< Optional. A group photo was change to this value private List<PhotoSize> newChatPhoto; ///< Optional. A chat photo was change to this value
public static final String DELETECHATPHOTO_FIELD = "delete_chat_photo"; public static final String DELETECHATPHOTO_FIELD = "delete_chat_photo";
@JsonProperty(DELETECHATPHOTO_FIELD) @JsonProperty(DELETECHATPHOTO_FIELD)
private Boolean deleteChatPhoto; ///< Optional. Informs that the group photo was deleted private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted
public static final String GROUPCHATCREATED_FIELD = "group_chat_created"; public static final String GROUPCHATCREATED_FIELD = "group_chat_created";
@JsonProperty(GROUPCHATCREATED_FIELD) @JsonProperty(GROUPCHATCREATED_FIELD)
private Boolean groupchatCreated; ///< Optional. Informs that the group has been created private Boolean groupchatCreated; ///< Optional. Informs that the group has been created
@ -89,6 +85,18 @@ public class Message implements BotApiObject {
public static final String VOICE_FIELD = "voice"; public static final String VOICE_FIELD = "voice";
@JsonProperty(VOICE_FIELD) @JsonProperty(VOICE_FIELD)
private Voice voice; ///< Optional. Message is a voice message, information about the file private Voice voice; ///< Optional. Message is a voice message, information about the file
public static final String SUPERGROUPCREATED_FIELD = "supergroup_chat_created";
@JsonProperty(SUPERGROUPCREATED_FIELD)
private Boolean superGroupCreated; ///< Optional. Informs that the supergroup has been created
public static final String CHANNELCHATCREATED_FIELD = "channel_chat_created";
@JsonProperty(CHANNELCHATCREATED_FIELD)
private Boolean channelChatCreated; ///< Optional. Informs that the channel has been created
public static final String MIGRATETOCHAT_FIELD = "migrate_to_chat_id";
@JsonProperty(MIGRATETOCHAT_FIELD)
private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
public static final String MIGRATEFROMCHAT_FIELD = "migrate_from_chat_id";
@JsonProperty(MIGRATEFROMCHAT_FIELD)
private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
public Message() { public Message() {
super(); super();
@ -97,7 +105,9 @@ public class Message implements BotApiObject {
public Message(JSONObject jsonObject) { public Message(JSONObject jsonObject) {
super(); super();
this.messageId = jsonObject.getInt(MESSAGEID_FIELD); this.messageId = jsonObject.getInt(MESSAGEID_FIELD);
this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); if (jsonObject.has(FROM_FIELD)) {
this.from = new User(jsonObject.getJSONObject(FROM_FIELD));
}
this.date = jsonObject.getInt(DATE_FIELD); this.date = jsonObject.getInt(DATE_FIELD);
this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD)); this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD));
if (jsonObject.has(FORWARDFROM_FIELD)) { if (jsonObject.has(FORWARDFROM_FIELD)) {
@ -157,10 +167,22 @@ public class Message implements BotApiObject {
} }
} }
if (jsonObject.has(DELETECHATPHOTO_FIELD)) { if (jsonObject.has(DELETECHATPHOTO_FIELD)) {
this.deleteChatPhoto = jsonObject.getBoolean(DELETECHATPHOTO_FIELD); this.deleteChatPhoto = true;
} }
if (jsonObject.has(GROUPCHATCREATED_FIELD)) { if (jsonObject.has(GROUPCHATCREATED_FIELD)) {
this.groupchatCreated = jsonObject.getBoolean(GROUPCHATCREATED_FIELD); this.groupchatCreated = true;
}
if (jsonObject.has(SUPERGROUPCREATED_FIELD)) {
this.superGroupCreated = true;
}
if (jsonObject.has(CHANNELCHATCREATED_FIELD)) {
this.channelChatCreated = true;
}
if (jsonObject.has(MIGRATETOCHAT_FIELD)) {
this.migrateToChatId = jsonObject.getLong(MIGRATETOCHAT_FIELD);
}
if (jsonObject.has(MIGRATEFROMCHAT_FIELD)) {
this.migrateFromChatId = jsonObject.getLong(MIGRATEFROMCHAT_FIELD);
} }
} }
@ -192,7 +214,19 @@ public class Message implements BotApiObject {
return chat.isGroupChat(); return chat.isGroupChat();
} }
public Integer getChatId() { public boolean isUserMessage() {
return chat.isUserChat();
}
public boolean isChannelMessage() {
return chat.isChannelChat();
}
public boolean isSuperGroupMessage() {
return chat.isSuperGroupChat();
}
public Long getChatId() {
return chat.getId(); return chat.getId();
} }
@ -221,7 +255,7 @@ public class Message implements BotApiObject {
} }
public boolean hasText() { public boolean hasText() {
return text != null; return text != null && !text.isEmpty();
} }
public String getText() { public String getText() {
@ -368,6 +402,38 @@ public class Message implements BotApiObject {
this.voice = voice; this.voice = voice;
} }
public Boolean getSuperGroupCreated() {
return superGroupCreated;
}
public void setSuperGroupCreated(Boolean superGroupCreated) {
this.superGroupCreated = superGroupCreated;
}
public Boolean getChannelChatCreated() {
return channelChatCreated;
}
public void setChannelChatCreated(Boolean channelChatCreated) {
this.channelChatCreated = channelChatCreated;
}
public Long getMigrateToChatId() {
return migrateToChatId;
}
public void setMigrateToChatId(Long migrateToChatId) {
this.migrateToChatId = migrateToChatId;
}
public Long getMigrateFromChatId() {
return migrateFromChatId;
}
public void setMigrateFromChatId(Long migrateFromChatId) {
this.migrateFromChatId = migrateFromChatId;
}
@Override @Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); gen.writeStartObject();
@ -439,76 +505,24 @@ public class Message implements BotApiObject {
if (groupchatCreated != null) { if (groupchatCreated != null) {
gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated); gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated);
} }
gen.writeEndObject(); if (superGroupCreated != null) {
gen.flush(); gen.writeBooleanField(SUPERGROUPCREATED_FIELD, superGroupCreated);
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
if (forwardFrom != null) {
gen.writeObjectField(FORWARDFROM_FIELD, forwardFrom);
}
if (forwardDate != null) {
gen.writeNumberField(FORWARDDATE_FIELD, forwardDate);
}
if (text != null) {
gen.writeStringField(TEXT_FIELD, text);
}
if (audio != null) {
gen.writeObjectField(AUDIO_FIELD, audio);
}
if (document != null) {
gen.writeObjectField(DOCUMENT_FIELD, document);
}
if (photo != null && photo.size() > 0) {
gen.writeArrayFieldStart(PHOTO_FIELD);
for (PhotoSize photoSize : photo) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
}
if (sticker != null) {
gen.writeObjectField(STICKER_FIELD, sticker);
}
if (video != null) {
gen.writeObjectField(VIDEO_FIELD, video);
}
if (contact != null) {
gen.writeObjectField(CONTACT_FIELD, contact);
} }
if (location != null) { if (channelChatCreated != null) {
gen.writeObjectField(LOCATION_FIELD, location); gen.writeBooleanField(CHANNELCHATCREATED_FIELD, channelChatCreated);
} }
if (voice != null) { if (migrateToChatId != null) {
gen.writeObjectField(VOICE_FIELD, voice); gen.writeNumberField(MIGRATETOCHAT_FIELD, migrateToChatId);
} }
if (newChatParticipant != null) { if (migrateFromChatId != null) {
gen.writeObjectField(NEWCHATPARTICIPANT_FIELD, newChatParticipant); gen.writeNumberField(MIGRATEFROMCHAT_FIELD, migrateFromChatId);
}
if (leftChatParticipant != null) {
gen.writeObjectField(LEFTCHATPARTICIPANT_FIELD, leftChatParticipant);
}
if (replyToMessage != null) {
gen.writeObjectField(REPLYTOMESSAGE_FIELD, replyToMessage);
}
if (newChatTitle != null) {
gen.writeStringField(NEWCHATTITLE_FIELD, newChatTitle);
}
if (newChatPhoto != null && newChatPhoto.size() > 0) {
gen.writeArrayFieldStart(NEWCHATPHOTO_FIELD);
for (PhotoSize photoSize: newChatPhoto) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
}
if (deleteChatPhoto != null) {
gen.writeBooleanField(DELETECHATPHOTO_FIELD, deleteChatPhoto);
}
if (groupchatCreated != null) {
gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated);
} }
gen.writeEndObject(); gen.writeEndObject();
gen.flush(); gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
} }
} }

10
src/main/java/org/telegram/api/objects/PhotoSize.java

@ -91,14 +91,6 @@ public class PhotoSize implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
} }
} }

6
src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java

@ -83,10 +83,6 @@ public class ReplyKeyboardHide implements ReplyKeyboard {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeBooleanField(HIDEKEYBOARD_FIELD, hideKeyboard);
gen.writeBooleanField(SELECTIVE_FIELD, selective);
gen.writeEndObject();
gen.flush();
} }
} }

22
src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java

@ -151,26 +151,6 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeArrayFieldStart(KEYBOARD_FIELD);
for (List<String> innerRow : keyboard) {
gen.writeStartArray();
for (String element: innerRow) {
gen.writeString(element);
}
gen.writeEndArray();
}
gen.writeEndArray();
if (this.oneTimeKeyboad != null) {
gen.writeBooleanField(ONETIMEKEYBOARD_FIELD, oneTimeKeyboad);
}
if (this.resizeKeyboard != null) {
gen.writeBooleanField(RESIZEKEYBOARD_FIELD, resizeKeyboard);
}
if (this.selective != null) {
gen.writeBooleanField(SELECTIVE_FIELD, selective);
}
gen.writeEndObject();
gen.flush();
} }
} }

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

@ -68,17 +68,6 @@ public class Sticker implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
if (thumb != null) {
gen.writeObjectField(THUMB_FIELD, thumb);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
} }
} }

60
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,18 +87,18 @@ 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();
} }
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeNumberField(UPDATEID_FIELD, updateId);
if (message != null) {
gen.writeObjectField(MESSAGE_FIELD, message);
}
gen.writeEndObject();
gen.flush();
} }
} }

12
src/main/java/org/telegram/api/objects/User.java

@ -79,16 +79,6 @@ public class User implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeNumberField(ID_FIELD, id);
gen.writeStringField(FIRSTNAME_FIELD, firstName);
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
if (userName != null) {
gen.writeStringField(USERNAME_FIELD, userName);
}
gen.writeEndObject();
gen.flush();
} }
} }

16
src/main/java/org/telegram/api/objects/UserProfilePhotos.java

@ -85,20 +85,6 @@ public class UserProfilePhotos implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeNumberField(TOTALCOUNT_FIELD, totalCount);
if (totalCount > 0) {
gen.writeArrayFieldStart(PHOTOS_FIELD);
for (List<PhotoSize> photoSizeList : photos) {
gen.writeStartArray();
for (PhotoSize photoSize: photoSizeList) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
}
gen.writeEndArray();
}
gen.writeEndObject();
gen.flush();
} }
} }

17
src/main/java/org/telegram/api/objects/Video.java

@ -137,21 +137,6 @@ public class Video implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
gen.writeNumberField(DURATION_FIELD, duration);
if (thumb != null) {
gen.writeObjectField(THUMB_FIELD, thumb);
}
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
} }
} }

12
src/main/java/org/telegram/api/objects/Voice.java

@ -94,16 +94,6 @@ public class Voice implements BotApiObject {
@Override @Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
gen.writeStartObject(); serialize(gen, serializers);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(DURATION_FIELD, duration);
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
} }
} }

8
src/main/java/org/telegram/database/ConectionDB.java

@ -19,7 +19,7 @@ import java.sql.*;
* @date 3/12/14 * @date 3/12/14
*/ */
public class ConectionDB { public class ConectionDB {
private static volatile BotLogger log = BotLogger.getLogger(ConectionDB.class.getName()); private static final String LOGTAG = "CONNECTIONDB";
private Connection currentConection; private Connection currentConection;
public ConectionDB() { public ConectionDB() {
@ -32,7 +32,7 @@ public class ConectionDB {
Class.forName(BuildVars.controllerDB).newInstance(); Class.forName(BuildVars.controllerDB).newInstance();
connection = DriverManager.getConnection(BuildVars.linkDB, BuildVars.userDB, BuildVars.password); connection = DriverManager.getConnection(BuildVars.linkDB, BuildVars.userDB, BuildVars.password);
} catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) { } catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return connection; return connection;
@ -42,7 +42,7 @@ public class ConectionDB {
try { try {
this.currentConection.close(); this.currentConection.close();
} catch (SQLException e) { } catch (SQLException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
@ -81,7 +81,7 @@ public class ConectionDB {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return max; return max;
} }

4
src/main/java/org/telegram/database/CreationStrings.java

@ -7,7 +7,7 @@ package org.telegram.database;
* @date 15 of May of 2015 * @date 15 of May of 2015
*/ */
public class CreationStrings { public class CreationStrings {
public static final int version = 6; public static final int version = 7;
public static final String createVersionTable = "CREATE TABLE IF NOT EXISTS Versions(ID INTEGER PRIMARY KEY AUTO_INCREMENT, Version INTEGER);"; public static final String createVersionTable = "CREATE TABLE IF NOT EXISTS Versions(ID INTEGER PRIMARY KEY AUTO_INCREMENT, Version INTEGER);";
public static final String insertCurrentVersion = "INSERT IGNORE INTO Versions (Version) VALUES(%d);"; public static final String insertCurrentVersion = "INSERT IGNORE INTO Versions (Version) VALUES(%d);";
public static final String createFilesTable = "CREATE TABLE IF NOT EXISTS Files (fileId VARCHAR(100) PRIMARY KEY, userId INTEGER NOT NULL, caption TEXT NOT NULL)"; public static final String createFilesTable = "CREATE TABLE IF NOT EXISTS Files (fileId VARCHAR(100) PRIMARY KEY, userId INTEGER NOT NULL, caption TEXT NOT NULL)";
@ -21,7 +21,7 @@ public class CreationStrings {
public static final String createUserLanguageDatabase = "CREATE TABLE IF NOT EXISTS UserLanguage (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL)"; public static final String createUserLanguageDatabase = "CREATE TABLE IF NOT EXISTS UserLanguage (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL)";
public static final String createUserWeatherOptionDatabase = "CREATE TABLE IF NOT EXISTS UserWeatherOptions (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " + public static final String createUserWeatherOptionDatabase = "CREATE TABLE IF NOT EXISTS UserWeatherOptions (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " +
"units VARCHAR(10) NOT NULL DEFAULT 'metric')"; "units VARCHAR(10) NOT NULL DEFAULT 'metric')";
public static final String createWeatherStateTable = "CREATE TABLE IF NOT EXISTS WeatherState (userId INTEGER NOT NULL, chatId INTEGER NOT NULL, state INTEGER NOT NULL DEFAULT 0, " + public static final String createWeatherStateTable = "CREATE TABLE IF NOT EXISTS WeatherState (userId INTEGER NOT NULL, chatId BIGINT NOT NULL, state INTEGER NOT NULL DEFAULT 0, " +
"languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " + "languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " +
"CONSTRAINT `watherPrimaryKey` PRIMARY KEY(userId,chatId));"; "CONSTRAINT `watherPrimaryKey` PRIMARY KEY(userId,chatId));";
public static final String createWeatherAlertTable = "CREATE TABLE IF NOT EXISTS WeatherAlert (id INTEGER PRIMARY KEY AUTO_INCREMENT, userId INTEGER NOT NULL, cityId INTEGER NOT NULL, " + public static final String createWeatherAlertTable = "CREATE TABLE IF NOT EXISTS WeatherAlert (id INTEGER PRIMARY KEY AUTO_INCREMENT, userId INTEGER NOT NULL, cityId INTEGER NOT NULL, " +

25
src/main/java/org/telegram/database/DatabaseManager.java

@ -9,7 +9,6 @@ package org.telegram.database;
import org.telegram.services.BotLogger; import org.telegram.services.BotLogger;
import org.telegram.structure.WeatherAlert; import org.telegram.structure.WeatherAlert;
import org.telegram.updateshandlers.WeatherHandlers;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -26,7 +25,8 @@ import java.util.List;
* @date 3/12/14 * @date 3/12/14
*/ */
public class DatabaseManager { public class DatabaseManager {
private static volatile BotLogger log = BotLogger.getLogger(DatabaseManager.class.getName()); ///< Logger private static final String LOGTAG = "DATABASEMANAGER";
private static volatile DatabaseManager instance; private static volatile DatabaseManager instance;
private static volatile ConectionDB connetion; private static volatile ConectionDB connetion;
@ -36,7 +36,7 @@ public class DatabaseManager {
private DatabaseManager() { private DatabaseManager() {
connetion = new ConectionDB(); connetion = new ConectionDB();
final int currentVersion = connetion.checkVersion(); final int currentVersion = connetion.checkVersion();
log.info("Current db version: " + currentVersion); BotLogger.info(LOGTAG, "Current db version: " + currentVersion);
if (currentVersion < CreationStrings.version) { if (currentVersion < CreationStrings.version) {
recreateTable(currentVersion); recreateTable(currentVersion);
} }
@ -86,9 +86,12 @@ public class DatabaseManager {
if (currentVersion == 5) { if (currentVersion == 5) {
currentVersion = updateToVersion6(); currentVersion = updateToVersion6();
} }
if (currentVersion == 6) {
currentVersion = updateToVersion7();
}
connetion.commitTransaction(); connetion.commitTransaction();
} catch (SQLException e) { } catch (SQLException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
@ -124,6 +127,12 @@ public class DatabaseManager {
return 6; return 6;
} }
private int updateToVersion7() throws SQLException {
connetion.executeQuery("ALTER TABLE WeatherState MODIFY chatId BIGINT NOT NULL");
connetion.executeQuery(String.format(CreationStrings.insertCurrentVersion, 7));
return 7;
}
private int createNewTables() throws SQLException { private int createNewTables() throws SQLException {
connetion.executeQuery(CreationStrings.createVersionTable); connetion.executeQuery(CreationStrings.createVersionTable);
connetion.executeQuery(CreationStrings.createFilesTable); connetion.executeQuery(CreationStrings.createFilesTable);
@ -411,12 +420,12 @@ public class DatabaseManager {
return updatedRows > 0; return updatedRows > 0;
} }
public int getWeatherState(Integer userId, Integer chatId) { public int getWeatherState(Integer userId, Long chatId) {
int state = 0; int state = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT state FROM WeatherState WHERE userId = ? AND chatId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT state FROM WeatherState WHERE userId = ? AND chatId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setInt(1, userId);
preparedStatement.setInt(2, chatId); preparedStatement.setLong(2, chatId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
state = result.getInt("state"); state = result.getInt("state");
@ -427,12 +436,12 @@ public class DatabaseManager {
return state; return state;
} }
public boolean insertWeatherState(Integer userId, Integer chatId, int state) { public boolean insertWeatherState(Integer userId, Long chatId, int state) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO WeatherState (userId, chatId, state) VALUES (?, ?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO WeatherState (userId, chatId, state) VALUES (?, ?, ?)");
preparedStatement.setInt(1, userId); preparedStatement.setInt(1, userId);
preparedStatement.setInt(2, chatId); preparedStatement.setLong(2, chatId);
preparedStatement.setInt(3, state); preparedStatement.setInt(3, state);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {

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

@ -4,9 +4,7 @@ import org.telegram.BuildVars;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.io.*; import java.io.*;
import java.util.Calendar; import java.time.LocalDateTime;
import java.util.GregorianCalendar;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.ConsoleHandler; import java.util.logging.ConsoleHandler;
import java.util.logging.Level; import java.util.logging.Level;
@ -14,57 +12,38 @@ import java.util.logging.Logger;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 2.0
* @brief Logger * @brief Logger to file
* @date 21/01/15 * @date 21/01/15
*/ */
public class BotLogger { public class BotLogger {
private volatile Object lockToWrite = new Object(); private static final Object lockToWrite = new Object();
private final Logger logger;
private static volatile PrintWriter logginFile; private static volatile PrintWriter logginFile;
private Calendar lastFileDate;
private static volatile String currentFileName; private static volatile String currentFileName;
private static final Logger logger = Logger.getLogger("Tsupport Bot");
private static volatile LocalDateTime lastFileDate;
private static LoggerThread loggerThread = new LoggerThread(); private static LoggerThread loggerThread = new LoggerThread();
private static volatile ConcurrentHashMap<String, BotLogger> instances = new ConcurrentHashMap<>(); private static final ConcurrentLinkedQueue<String> logsToFile = new ConcurrentLinkedQueue<>();
private final static ConcurrentLinkedQueue<String> logsToFile = new ConcurrentLinkedQueue<>();
static { static {
loggerThread.start();
}
public static BotLogger getLogger(@NotNull String className) {
if (!instances.containsKey(className)) {
synchronized (BotLogger.class) {
if (!instances.containsKey(className)) {
BotLogger instance = new BotLogger(className);
instances.put(className, instance);
return instance;
} else {
return instances.get(className);
}
}
} else {
return instances.get(className);
}
}
private BotLogger(String classname) {
logger = Logger.getLogger(classname);
logger.setLevel(Level.ALL); logger.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler(); logger.addHandler(new ConsoleHandler());
handler.setLevel(Level.ALL); loggerThread.start();
logger.addHandler(handler); lastFileDate = LocalDateTime.now();
lastFileDate = new GregorianCalendar(); if ((currentFileName == null) || (currentFileName.compareTo("") == 0)) {
if (currentFileName == null || currentFileName.length() == 0) { currentFileName = dateFormatterForFileName(lastFileDate) + ".log";
currentFileName = BuildVars.pathToLogs + dateFormaterForFileName(lastFileDate) + ".log";
try { try {
File file = new File(currentFileName); final File file = new File(currentFileName);
if (!file.exists()) { if (file.exists()) {
file.createNewFile(); logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
final boolean created = file.createNewFile();
if (created) {
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
throw new NullPointerException("File for logging error");
}
} }
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -72,271 +51,261 @@ public class BotLogger {
} }
} }
public static void log(@NotNull Level level, String tag, String msg) {
public void log(@NotNull Level level, String msg) { logger.log(level, String.format("[%s] %s", tag, msg));
logger.log(level, msg); logToFile(level, tag, msg);
logToFile(level, msg);
} }
public void severe(String msg) { public static void severe(String tag, String msg) {
logger.severe(msg); logger.severe(String.format("[%s] %s", tag, msg));
logToFile(Level.SEVERE, msg); logToFile(Level.SEVERE, tag, msg);
} }
public void warn(String msg) { public static void warn(String tag, String msg) {
warning(msg); warning(tag, msg);
} }
public void debug(String msg) { public static void debug(String tag, String msg) {
fine(msg); fine(tag, msg);
} }
public void error(String msg) { public static void error(String tag, String msg) {
severe(msg); severe(tag, msg);
} }
public void trace(String msg) { public static void trace(String tag, String msg) {
finer(msg); finer(tag, msg);
} }
public void warning(String msg) { public static void warning(String tag, String msg) {
logger.warning(msg); logger.warning(String.format("[%s] %s", tag, msg));
logToFile(Level.WARNING, msg); logToFile(Level.WARNING, tag, msg);
} }
public void info(String msg) { public static void info(String tag, String msg) {
logger.info(msg); logger.info(String.format("[%s] %s", tag, msg));
logToFile(Level.INFO, msg); logToFile(Level.INFO, tag, msg);
} }
public void config(String msg) { public static void config(String tag, String msg) {
logger.config(msg); logger.config(String.format("[%s] %s", tag, msg));
logToFile(Level.CONFIG, msg); logToFile(Level.CONFIG, tag, msg);
} }
public void fine(String msg) { public static void fine(String tag, String msg) {
logger.fine(msg); logger.fine(String.format("[%s] %s", tag, msg));
logToFile(Level.FINE, msg); logToFile(Level.FINE, tag, msg);
} }
public void finer(String msg) { public static void finer(String tag, String msg) {
logger.finer(msg); logger.finer(String.format("[%s] %s", tag, msg));
logToFile(Level.FINER, msg); logToFile(Level.FINER, tag, msg);
} }
public void finest(String msg) { public static void finest(String tag, String msg) {
logger.finest(msg); logger.finest(String.format("[%s] %s", tag, msg));
logToFile(Level.FINEST, msg); logToFile(Level.FINEST, tag, msg);
} }
public void log(@NotNull Level level, @NotNull Throwable throwable) { public static void log(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable) {
throwable.printStackTrace(); logger.log(level, String.format("[%s] Exception", tag), throwable);
logToFile(level, throwable); logToFile(level, tag, throwable);
} }
public void log(@NotNull Level level, String msg, Throwable thrown) { public static void log(@NotNull Level level, @NotNull String tag, @NotNull String msg, @NotNull Throwable thrown) {
logger.log(level, msg, thrown); logger.log(level, msg, thrown);
logToFile(level, msg ,thrown); logToFile(level, msg, thrown);
} }
public void severe(@NotNull Throwable throwable) { public static void severe(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.SEVERE, throwable); logToFile(Level.SEVERE, tag, throwable);
} }
public void warning(@NotNull Throwable throwable) { public static void warning(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.WARNING, throwable); logToFile(Level.WARNING, tag, throwable);
} }
public void info(@NotNull Throwable throwable) { public static void info(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.INFO, throwable); logToFile(Level.INFO, tag, throwable);
} }
public void config(@NotNull Throwable throwable) { public static void config(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.CONFIG, throwable); logToFile(Level.CONFIG, tag, throwable);
} }
public void fine(@NotNull Throwable throwable) { public static void fine(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.FINE, throwable); logToFile(Level.FINE, tag, throwable);
} }
public void finer(@NotNull Throwable throwable) { public static void finer(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.FINER, throwable); logToFile(Level.FINER, tag, throwable);
} }
public void finest(@NotNull Throwable throwable) { public static void finest(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.FINEST, throwable); logToFile(Level.FINEST, tag, throwable);
} }
public void warn(Throwable throwable) { public static void warn(@NotNull String tag, Throwable throwable) {
warning(throwable); warning(tag, throwable);
} }
public void debug(Throwable throwable) { public static void debug(@NotNull String tag, Throwable throwable) {
fine(throwable); fine(tag, throwable);
} }
public void error(Throwable throwable) { public static void error(@NotNull String tag, Throwable throwable) {
severe(throwable); severe(tag, throwable);
} }
public void trace(Throwable throwable) { public static void trace(@NotNull String tag, Throwable throwable) {
finer(throwable); finer(tag, throwable);
} }
public void severe(String msg, @NotNull Throwable throwable) { public static void severe(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.SEVERE, msg, throwable); log(Level.SEVERE, tag, msg, throwable);
} }
public void warning(String msg, @NotNull Throwable throwable) { public static void warning(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.WARNING, msg, throwable); log(Level.WARNING, tag, msg, throwable);
} }
public void info(String msg, @NotNull Throwable throwable) { public static void info(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.INFO, msg, throwable); log(Level.INFO, tag, msg, throwable);
} }
public void config(String msg, @NotNull Throwable throwable) { public static void config(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.CONFIG, msg, throwable); log(Level.CONFIG, tag, msg, throwable);
} }
public void fine(String msg, @NotNull Throwable throwable) { public static void fine(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINE, msg, throwable); log(Level.FINE, tag, msg, throwable);
} }
public void finer(String msg, @NotNull Throwable throwable) { public static void finer(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINER, msg, throwable); log(Level.FINER, tag, msg, throwable);
} }
public void finest(String msg, @NotNull Throwable throwable) { public static void finest(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINEST, msg, throwable); log(Level.FINEST, msg, throwable);
} }
public void warn(String msg, @NotNull Throwable throwable) { public static void warn(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.WARNING, msg, throwable); log(Level.WARNING, tag, msg, throwable);
} }
public void debug(String msg, @NotNull Throwable throwable) { public static void debug(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINE, msg, throwable); log(Level.FINE, tag, msg, throwable);
} }
public void error(String msg, @NotNull Throwable throwable) { public static void error(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.SEVERE, msg, throwable); log(Level.SEVERE, tag, msg, throwable);
} }
public void trace(String msg, @NotNull Throwable throwable) { public static void trace(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINER, msg, throwable); log(Level.FINER, tag, msg, throwable);
} }
private boolean isCurrentDate(Calendar calendar) { private static boolean isCurrentDate(LocalDateTime dateTime) {
if (calendar.get(Calendar.DAY_OF_MONTH) != lastFileDate.get(Calendar.DAY_OF_MONTH)) { return dateTime.toLocalDate().isEqual(lastFileDate.toLocalDate());
return false;
}
if (calendar.get(Calendar.MONTH) != lastFileDate.get(Calendar.MONTH)) {
return false;
}
if (calendar.get(Calendar.YEAR) != lastFileDate.get(Calendar.YEAR)) {
return false;
}
return true;
} }
private String dateFormaterForFileName(@NotNull Calendar calendar) { private static String dateFormatterForFileName(@NotNull LocalDateTime dateTime) {
String dateString = ""; String dateString = "";
dateString += calendar.get(Calendar.DAY_OF_MONTH); dateString += dateTime.getDayOfMonth();
dateString += calendar.get(Calendar.MONTH) + 1; dateString += dateTime.getMonthValue();
dateString += calendar.get(Calendar.YEAR); dateString += dateTime.getYear();
return dateString; return dateString;
} }
private String dateFormaterForLogs(@NotNull Calendar calendar) { private static String dateFormatterForLogs(@NotNull LocalDateTime dateTime) {
String dateString = "["; String dateString = "[";
dateString += calendar.get(Calendar.DAY_OF_MONTH) + "_"; dateString += dateTime.getDayOfMonth() + "_";
dateString += (calendar.get(Calendar.MONTH) + 1) + "_"; dateString += dateTime.getMonthValue() + "_";
dateString += calendar.get(Calendar.YEAR) + "_"; dateString += dateTime.getYear() + "_";
dateString += calendar.get(Calendar.HOUR_OF_DAY) + "_"; dateString += dateTime.getHour() + ":";
dateString += calendar.get(Calendar.MINUTE) + ":"; dateString += dateTime.getMinute() + ":";
dateString += calendar.get(Calendar.SECOND); dateString += dateTime.getSecond();
dateString += "] "; dateString += "] ";
return dateString; return dateString;
} }
private void updateAndCreateFile(Calendar calendar) { private static void updateAndCreateFile(LocalDateTime dateTime) {
if (isCurrentDate(calendar)) { if (!isCurrentDate(dateTime)) {
return; lastFileDate = LocalDateTime.now();
} currentFileName = BuildVars.pathToLogs + dateFormatterForFileName(lastFileDate) + ".log";
lastFileDate = new GregorianCalendar(); try {
currentFileName = BuildVars.pathToLogs + dateFormaterForFileName(lastFileDate) + ".log"; logginFile.flush();
try { logginFile.close();
logginFile.flush(); final File file = new File(currentFileName);
logginFile.close(); if (file.exists()) {
File file = new File(currentFileName); logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
if (!file.exists()) { } else {
file.createNewFile(); final boolean created = file.createNewFile();
if (created) {
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
throw new NullPointerException("Error updating log file");
}
}
} catch (IOException ignored) {
} }
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
} }
private void logToFile(@NotNull Level level, Throwable throwable) {
if (!isLoggable(level)){ private static void logToFile(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable) {
return; if (isLoggable(level)) {
} synchronized (lockToWrite) {
synchronized (lockToWrite) { final LocalDateTime currentDate = LocalDateTime.now();
Calendar currentDate = new GregorianCalendar(); final String dateForLog = dateFormatterForLogs(currentDate);
String dateForLog = dateFormaterForLogs(currentDate); updateAndCreateFile(currentDate);
updateAndCreateFile(currentDate); logThrowableToFile(level, tag, throwable, dateForLog);
logThrowableToFile(level, throwable, dateForLog); }
} }
} }
private void logToFile(@NotNull Level level, String msg) { private static void logToFile(@NotNull Level level, @NotNull String tag, @NotNull String msg) {
if (!isLoggable(level)){ if (isLoggable(level)) {
return; synchronized (lockToWrite) {
} final LocalDateTime currentDate = LocalDateTime.now();
synchronized (lockToWrite) { updateAndCreateFile(currentDate);
Calendar currentDate = new GregorianCalendar(); final String dateForLog = dateFormatterForLogs(currentDate);
updateAndCreateFile(currentDate); logMsgToFile(level, tag, msg, dateForLog);
String dateForLog = dateFormaterForLogs(currentDate); }
logMsgToFile(level, msg, dateForLog);
} }
} }
private void logToFile(Level level, String msg, Throwable throwable) { private static void logToFile(Level level, @NotNull String tag, @NotNull String msg, @NotNull Throwable throwable) {
if (!isLoggable(level)){ if (isLoggable(level)) {
return; synchronized (lockToWrite) {
} final LocalDateTime currentDate = LocalDateTime.now();
synchronized (lockToWrite) { updateAndCreateFile(currentDate);
Calendar currentDate = new GregorianCalendar(); final String dateForLog = dateFormatterForLogs(currentDate);
updateAndCreateFile(currentDate); logMsgToFile(level, tag, msg, dateForLog);
String dateForLog = dateFormaterForLogs(currentDate); logThrowableToFile(level, tag, throwable, dateForLog);
logMsgToFile(level, msg, dateForLog); }
logThrowableToFile(level, throwable, dateForLog);
} }
} }
private void logMsgToFile(Level level, String msg, String dateForLog) { private static void logMsgToFile(@NotNull Level level, @NotNull String tag, @NotNull String msg, @NotNull String dateForLog) {
dateForLog += " [" + logger.getName() + "]" + level.toString() + " - " + msg; final String logMessage = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, msg);
logsToFile.add(dateForLog); logsToFile.add(logMessage);
synchronized (logsToFile) { synchronized (logsToFile) {
logsToFile.notifyAll(); logsToFile.notifyAll();
} }
} }
private void logThrowableToFile(Level level, Throwable throwable, String dateForLog) { private static void logThrowableToFile(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable, @NotNull String dateForLog) {
String throwableLog = dateForLog + level.getName() + " - " + throwable + "\n"; String throwableLog = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, throwable.toString());
for (StackTraceElement element : throwable.getStackTrace()) { for (StackTraceElement element : throwable.getStackTrace()) {
throwableLog += "\tat " + element + "\n"; throwableLog += "\tat " + element + "\n";
} }
@ -346,23 +315,16 @@ public class BotLogger {
} }
} }
private boolean isLoggable(Level level) { private static boolean isLoggable(Level level) {
return logger.isLoggable(level) && BuildVars.debug; return logger.isLoggable(level) && BuildVars.debug;
} }
@Override
protected void finalize() throws Throwable {
logginFile.flush();
logginFile.close();
super.finalize();
}
private static class LoggerThread extends Thread { private static class LoggerThread extends Thread {
@Override @Override
public void run() { public void run() {
setPriority(Thread.MIN_PRIORITY);
while(true) { while(true) {
ConcurrentLinkedQueue<String> stringsToLog = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue<String> stringsToLog = new ConcurrentLinkedQueue<>();
synchronized (logsToFile) { synchronized (logsToFile) {
if (logsToFile.isEmpty()) { if (logsToFile.isEmpty()) {
try { try {
@ -378,9 +340,7 @@ public class BotLogger {
logsToFile.clear(); logsToFile.clear();
} }
for (String stringToLog: stringsToLog) { stringsToLog.stream().forEach(logginFile::println);
logginFile.println(stringToLog);
}
logginFile.flush(); logginFile.flush();
} }
} }

5
src/main/java/org/telegram/services/DirectionsService.java

@ -13,7 +13,6 @@ import org.json.JSONObject;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@ -27,7 +26,7 @@ import java.util.List;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class DirectionsService { public class DirectionsService {
private static volatile BotLogger log = BotLogger.getLogger(DirectionsService.class.getName()); private static final String LOGTAG = "DIRECTIONSSERVICE";
private static final String BASEURL = "https://maps.googleapis.com/maps/api/directions/json"; ///< Base url for REST private static final String BASEURL = "https://maps.googleapis.com/maps/api/directions/json"; ///< Base url for REST
private static final String APIIDEND = "&key=" + BuildVars.DirectionsApiKey; private static final String APIIDEND = "&key=" + BuildVars.DirectionsApiKey;
@ -98,7 +97,7 @@ public class DirectionsService {
responseToUser.add(LocalisationService.getInstance().getString("directionsNotFound", language)); responseToUser.add(LocalisationService.getInstance().getString("directionsNotFound", language));
} }
} catch (Exception e) { } catch (Exception e) {
log.warning(e); BotLogger.warn(LOGTAG, e);
responseToUser.add(LocalisationService.getInstance().getString("errorFetchingDirections", language)); responseToUser.add(LocalisationService.getInstance().getString("errorFetchingDirections", language));
} }
return responseToUser; return responseToUser;

11
src/main/java/org/telegram/services/LocalisationService.java

@ -3,7 +3,10 @@ package org.telegram.services;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.*; import java.util.HashMap;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
@ -31,6 +34,7 @@ public class LocalisationService {
private ResourceBundle galician; private ResourceBundle galician;
private ResourceBundle persian; private ResourceBundle persian;
private ResourceBundle turkish; private ResourceBundle turkish;
private ResourceBundle esperanto;
private class CustomClassLoader extends ClassLoader { private class CustomClassLoader extends ClassLoader {
public CustomClassLoader(ClassLoader parent) { public CustomClassLoader(ClassLoader parent) {
@ -92,6 +96,8 @@ public class LocalisationService {
supportedLanguages.put("nl", "Nederlands"); supportedLanguages.put("nl", "Nederlands");
italian = ResourceBundle.getBundle("localisation.strings", new Locale("it", "IT"), loader); italian = ResourceBundle.getBundle("localisation.strings", new Locale("it", "IT"), loader);
supportedLanguages.put("it", "Italiano"); supportedLanguages.put("it", "Italiano");
esperanto = ResourceBundle.getBundle("localisation.strings", new Locale("eo", "EO"), loader);
supportedLanguages.put("eo", "Esperanto");
/* /*
german = ResourceBundle.getBundle("localisation.strings", new Locale("de", "DE"), loader); german = ResourceBundle.getBundle("localisation.strings", new Locale("de", "DE"), loader);
supportedLanguages.put("de", "Deutsch"); supportedLanguages.put("de", "Deutsch");
@ -155,6 +161,9 @@ public class LocalisationService {
case "it": case "it":
result = italian.getString(key); result = italian.getString(key);
break; break;
case "eo":
result = esperanto.getString(key);
break;
/*case "de": /*case "de":
result = german.getString(key); result = german.getString(key);
break; break;

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

14
src/main/java/org/telegram/services/TimerExecutor.java

@ -1,6 +1,8 @@
package org.telegram.services; package org.telegram.services;
import java.time.*; import java.time.Clock;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -12,7 +14,7 @@ import java.util.concurrent.TimeUnit;
* @date 27/01/25 * @date 27/01/25
*/ */
public class TimerExecutor { public class TimerExecutor {
private static volatile BotLogger log = BotLogger.getLogger(TimerExecutor.class.getName()); private static final String LOGTAG = "TIMEREXECUTOR";
private static volatile TimerExecutor instance; ///< Instance private static volatile TimerExecutor instance; ///< Instance
private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); ///< Thread to execute operations private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); ///< Thread to execute operations
@ -52,14 +54,14 @@ public class TimerExecutor {
* @param targetSec Second to execute it * @param targetSec Second to execute it
*/ */
public void startExecutionEveryDayAt(CustomTimerTask task, int targetHour, int targetMin, int targetSec) { public void startExecutionEveryDayAt(CustomTimerTask task, int targetHour, int targetMin, int targetSec) {
log.warn("Posting new task" + task.getTaskName()); BotLogger.warn(LOGTAG, "Posting new task" + task.getTaskName());
final Runnable taskWrapper = () -> { final Runnable taskWrapper = () -> {
try { try {
task.execute(); task.execute();
task.reduceTimes(); task.reduceTimes();
startExecutionEveryDayAt(task, targetHour, targetMin, targetSec); startExecutionEveryDayAt(task, targetHour, targetMin, targetSec);
} catch (Exception e) { } catch (Exception e) {
log.severe("Bot threw an unexpected exception at TimerExecutor", e); BotLogger.severe(LOGTAG, "Bot threw an unexpected exception at TimerExecutor", e);
} }
}; };
if (task.getTimes() != 0) { if (task.getTimes() != 0) {
@ -100,9 +102,9 @@ public class TimerExecutor {
try { try {
executorService.awaitTermination(1, TimeUnit.DAYS); executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
log.severe(ex); BotLogger.severe(LOGTAG, ex);
} catch (Exception e) { } catch (Exception e) {
log.severe("Bot threw an unexpected exception at TimerExecutor", e); BotLogger.severe(LOGTAG, "Bot threw an unexpected exception at TimerExecutor", e);
} }
} }
} }

32
src/main/java/org/telegram/services/TransifexService.java

@ -19,7 +19,7 @@ import java.io.*;
* @date 21 of June of 2015 * @date 21 of June of 2015
*/ */
public class TransifexService { public class TransifexService {
private static volatile BotLogger log = BotLogger.getLogger(TransifexService.class.getName()); private static final String LOGTAG = "TRANSIFEXSERVICE";
private static final String BASEURLAndroid = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram/resource/stringsxml-48/translation/@language?file"; ///< Base url for REST private static final String BASEURLAndroid = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram/resource/stringsxml-48/translation/@language?file"; ///< Base url for REST
private static final String BASEURLiOS = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/iphone-1/resource/localizablestrings/translation/@language?file"; ///< Base url for REST private static final String BASEURLiOS = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/iphone-1/resource/localizablestrings/translation/@language?file"; ///< Base url for REST
@ -76,7 +76,7 @@ public class TransifexService {
result = responseString; result = responseString;
} }
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -89,7 +89,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"));
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -102,7 +102,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"));
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -115,7 +115,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"));
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -128,7 +128,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -141,7 +141,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"));
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -154,7 +154,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE")); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"));
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return result; return result;
} }
@ -194,11 +194,11 @@ public class TransifexService {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
return sendDocument; return sendDocument;
} }
@ -221,11 +221,11 @@ public class TransifexService {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); BotLogger.error(LOGTAG, e);
} }
return sendDocument; return sendDocument;
} }
@ -249,11 +249,11 @@ public class TransifexService {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); BotLogger.error(LOGTAG, e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); BotLogger.error(LOGTAG, e);
} }
return sendDocument; return sendDocument;
} }
@ -276,11 +276,11 @@ public class TransifexService {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName); sendDocument.setNewDocument(fileToUpload.getAbsolutePath(), fileName);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); BotLogger.error(LOGTAG, e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); BotLogger.error(LOGTAG, e);
} }
return sendDocument; return sendDocument;
} }

26
src/main/java/org/telegram/services/WeatherService.java

@ -26,7 +26,7 @@ import java.time.format.DateTimeFormatter;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class WeatherService { public class WeatherService {
private static volatile BotLogger log = BotLogger.getLogger(WeatherService.class.getName()); private static final String LOGTAG = "WEATHERSERVICE";
public static final String METRICSYSTEM = "metric"; public static final String METRICSYSTEM = "metric";
public static final String IMPERIALSYSTEM = "imperial"; public static final String IMPERIALSYSTEM = "imperial";
@ -90,7 +90,7 @@ public class WeatherService {
String responseString = EntityUtils.toString(buf, "UTF-8"); String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString); JSONObject jsonObject = new JSONObject(responseString);
log.warning(jsonObject.toString()); BotLogger.info(LOGTAG, jsonObject.toString());
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")"; jsonObject.getJSONObject("city").getString("country") + ")";
@ -98,11 +98,11 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getInstance().getString("weatherAlert", language), responseToUser = String.format(LocalisationService.getInstance().getString("weatherAlert", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, false)); cityFound, convertListOfForecastToString(jsonObject, language, units, false));
} else { } else {
log.warning(jsonObject.toString()); BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -131,7 +131,7 @@ public class WeatherService {
String responseString = EntityUtils.toString(buf, "UTF-8"); String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString); JSONObject jsonObject = new JSONObject(responseString);
log.warning(jsonObject.toString()); BotLogger.info(LOGTAG, jsonObject.toString());
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")"; jsonObject.getJSONObject("city").getString("country") + ")";
@ -139,11 +139,11 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getInstance().getString("weatherForcast", language), responseToUser = String.format(LocalisationService.getInstance().getString("weatherForcast", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, true)); cityFound, convertListOfForecastToString(jsonObject, language, units, true));
} else { } else {
log.warning(jsonObject.toString()); BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -178,11 +178,11 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getInstance().getString("weatherForcast", language), responseToUser = String.format(LocalisationService.getInstance().getString("weatherForcast", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, true)); cityFound, convertListOfForecastToString(jsonObject, language, units, true));
} else { } else {
log.warning(jsonObject.toString()); BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -219,11 +219,11 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getInstance().getString("weatherCurrent", language), responseToUser = String.format(LocalisationService.getInstance().getString("weatherCurrent", language),
cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji)); cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji));
} else { } else {
log.warning(jsonObject.toString()); BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -258,11 +258,11 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getInstance().getString("weatherCurrent", language), responseToUser = String.format(LocalisationService.getInstance().getString("weatherCurrent", language),
cityFound, convertCurrentWeatherToString(jsonObject, language, units, null)); cityFound, convertCurrentWeatherToString(jsonObject, language, units, null));
} else { } else {
log.warning(jsonObject.toString()); BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getInstance().getString("cityNotFound", language); responseToUser = LocalisationService.getInstance().getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language); responseToUser = LocalisationService.getInstance().getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;

184
src/main/java/org/telegram/updateshandlers/ChannelHandlers.java

@ -0,0 +1,184 @@
package org.telegram.updateshandlers;
import org.telegram.BotConfig;
import org.telegram.BuildVars;
import org.telegram.SenderHelper;
import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.ForceReplyKeyboard;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.ReplyKeyboardMarkup;
import org.telegram.api.objects.Update;
import org.telegram.services.BotLogger;
import org.telegram.updatesreceivers.UpdatesThread;
import org.telegram.updatesreceivers.Webhook;
import java.io.InvalidObjectException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Handler for updates to channel updates bot
* This is a use case that will send a message to a channel if it is added as an admin to it.
* @date 24 of June of 2015
*/
public class ChannelHandlers implements UpdatesCallback {
private static final String LOGTAG = "CHANNELHANDLERS";
private static final String TOKEN = BotConfig.TOKENCHANNEL;
private static final String BOTNAME = BotConfig.USERNAMECHANNEL;
private static final boolean USEWEBHOOK = false;
private static final int WAITINGCHANNEL = 1;
private static final String HELP_TEXT = "Send me the channel username where you added me as admin.";
private static final String CANCEL_COMMAND = "/stop";
private static final String AFTER_CHANNEL_TEXT = "A message to provided channel will be sent if the bot was added to it as admin.";
private static final String WRONG_CHANNEL_TEXT = "Wrong username, please remember to add *@* before the username and send only the username.";
private static final String CHANNEL_MESSAGE_TEXT = "This message was sent by *@updateschannelbot*. Enjoy!";
private static final String ERROR_MESSAGE_TEXT = "There was an error sending the message to channel *%s*, the error was: ```%s```";
private final ConcurrentHashMap<Integer, Integer> userState = new ConcurrentHashMap<>();
private final Object webhookLock = new Object();
public ChannelHandlers(Webhook webhook) {
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) {
Message message = update.getMessage();
if (message != null && message.hasText()) {
try {
BotApiMethod botApiMethod = handleIncomingMessage(message);
if (botApiMethod != null) {
SenderHelper.SendApiMethod(botApiMethod, TOKEN);
}
} catch (InvalidObjectException e) {
BotLogger.severe(LOGTAG, e);
}
}
}
@Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
throw new NoSuchMethodError();
}
// region Incoming messages handlers
private BotApiMethod handleIncomingMessage(Message message) throws InvalidObjectException {
int state = userState.getOrDefault(message.getFrom().getId(), 0);
BotApiMethod botApiMethod;
switch(state) {
case WAITINGCHANNEL:
botApiMethod = onWaitingChannelMessage(message);
break;
default:
botApiMethod = sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null);
userState.put(message.getFrom().getId(), WAITINGCHANNEL);
break;
}
return botApiMethod;
}
private BotApiMethod onWaitingChannelMessage(Message message) throws InvalidObjectException {
BotApiMethod sendMessage = null;
if (message.getText().equals(CANCEL_COMMAND)) {
userState.remove(message.getFrom().getId());
sendMessage = sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null);
} else {
if (message.getText().startsWith("@") && !message.getText().trim().contains(" ")) {
sendBuiltMessage(getMessageToChannelSent(message));
sendMessageToChannel(message.getText(), message);
userState.remove(message.getFrom().getId());
} else {
sendMessage = getWrongUsernameMessage(message);
}
}
return sendMessage;
}
private static void sendMessageToChannel(String username, Message message) {
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(username.trim());
sendMessage.setText(CHANNEL_MESSAGE_TEXT);
sendMessage.enableMarkdown(true);
try {
sendBuiltMessage(sendMessage);
} catch (InvalidObjectException e) {
sendErrorMessage(message, e.getMessage());
}
}
private static void sendErrorMessage(Message message, String errorText) {
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setText(String.format(ERROR_MESSAGE_TEXT, message.getText().trim(), errorText.replace("\"", "\\\"")));
sendMessage.enableMarkdown(true);
try {
sendBuiltMessage(sendMessage);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
}
private static BotApiMethod getWrongUsernameMessage(Message message) {
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
forceReplyKeyboard.setSelective(true);
forceReplyKeyboard.setForceReply(true);
sendMessage.setReplayMarkup(forceReplyKeyboard);
sendMessage.setText(WRONG_CHANNEL_TEXT);
sendMessage.enableMarkdown(true);
return sendMessage;
}
private static SendMessage getMessageToChannelSent(Message message) {
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setText(AFTER_CHANNEL_TEXT);
return sendMessage;
}
private static BotApiMethod sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup) {
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId);
sendMessage.setReplayToMessageId(messageId);
if (replyKeyboardMarkup != null) {
sendMessage.setReplayMarkup(replyKeyboardMarkup);
}
sendMessage.setText(HELP_TEXT);
return sendMessage;
}
private static void sendBuiltMessage(SendMessage sendMessage) throws InvalidObjectException {
SenderHelper.SendApiMethod(sendMessage, TOKEN);
}
}

42
src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java

@ -1,16 +1,21 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.*; import org.telegram.BotConfig;
import org.telegram.api.objects.*; import org.telegram.BuildVars;
import org.telegram.database.DatabaseManager; import org.telegram.Commands;
import org.telegram.SenderHelper;
import org.telegram.api.methods.BotApiMethod; import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendMessage; import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.*;
import org.telegram.database.DatabaseManager;
import org.telegram.services.BotLogger;
import org.telegram.services.DirectionsService; import org.telegram.services.DirectionsService;
import org.telegram.services.LocalisationService; import org.telegram.services.LocalisationService;
import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.UpdatesThread;
import org.telegram.updatesreceivers.Webhook; import org.telegram.updatesreceivers.Webhook;
import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -24,6 +29,7 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class DirectionsHandlers implements UpdatesCallback { public class DirectionsHandlers implements UpdatesCallback {
private static final String LOGTAG = "DIRECTIONSHANDLERS";
private static final String TOKEN = BotConfig.TOKENDIRECTIONS; private static final String TOKEN = BotConfig.TOKENDIRECTIONS;
private static final String BOTNAME = BotConfig.USERNAMEDIRECTIONS; private static final String BOTNAME = BotConfig.USERNAMEDIRECTIONS;
private static final boolean USEWEBHOOK = false; private static final boolean USEWEBHOOK = false;
@ -33,7 +39,7 @@ public class DirectionsHandlers implements UpdatesCallback {
private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>();
public DirectionsHandlers(Webhook webhook) { public DirectionsHandlers(Webhook webhook) {
if (USEWEBHOOK) { if (USEWEBHOOK && BuildVars.useWebHook) {
webhook.registerWebhook(this, BOTNAME); webhook.registerWebhook(this, BOTNAME);
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else { } else {
@ -44,7 +50,11 @@ public class DirectionsHandlers implements UpdatesCallback {
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
handleDirections(update); try {
handleDirections(update);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} }
@Override @Override
@ -53,7 +63,7 @@ public class DirectionsHandlers implements UpdatesCallback {
return null; return null;
} }
public void handleDirections(Update update) { public void handleDirections(Update update) throws InvalidObjectException {
Message message = update.getMessage(); Message message = update.getMessage();
if (message != null && message.hasText()) { if (message != null && message.hasText()) {
if (languageMessages.contains(message.getFrom().getId())) { if (languageMessages.contains(message.getFrom().getId())) {
@ -84,7 +94,7 @@ public class DirectionsHandlers implements UpdatesCallback {
} else { } else {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getInstance().getString("youNeedReplyDirections", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("youNeedReplyDirections", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
} }
@ -98,7 +108,7 @@ public class DirectionsHandlers implements UpdatesCallback {
String destiny = message.getText(); String destiny = message.getText();
List<String> directions = DirectionsService.getInstance().getDirections(origin, destiny, language); List<String> directions = DirectionsService.getInstance().getDirections(origin, destiny, language);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide(); ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
replyKeyboardHide.setSelective(true); replyKeyboardHide.setSelective(true);
sendMessageRequest.setReplayMarkup(replyKeyboardHide); sendMessageRequest.setReplayMarkup(replyKeyboardHide);
@ -125,7 +135,7 @@ public class DirectionsHandlers implements UpdatesCallback {
private void onOriginReceived(Message message, String language) { private void onOriginReceived(Message message, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setReplayToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
forceReplyKeyboard.setSelective(true); forceReplyKeyboard.setSelective(true);
@ -149,19 +159,19 @@ public class DirectionsHandlers implements UpdatesCallback {
} }
private void sendHelpMessage(Message message, String language) { private void sendHelpMessage(Message message, String language) throws InvalidObjectException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
String helpDirectionsFormated = String.format( String helpDirectionsFormated = String.format(
LocalisationService.getInstance().getString("helpDirections", language), LocalisationService.getInstance().getString("helpDirections", language),
Commands.startDirectionCommand); Commands.startDirectionCommand);
sendMessageRequest.setText(helpDirectionsFormated); sendMessageRequest.setText(helpDirectionsFormated);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
private void onStartdirectionsCommand(Message message, String language) { private void onStartdirectionsCommand(Message message, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setReplayToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
forceReplyKeyboard.setSelective(true); forceReplyKeyboard.setSelective(true);
@ -185,9 +195,9 @@ public class DirectionsHandlers implements UpdatesCallback {
} }
private void onSetLanguageCommand(Message message, String language) { private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
HashMap<String, String> languages = LocalisationService.getInstance().getSupportedLanguages(); HashMap<String, String> languages = LocalisationService.getInstance().getSupportedLanguages();
List<List<String>> commands = new ArrayList<>(); List<List<String>> commands = new ArrayList<>();
@ -206,10 +216,10 @@ public class DirectionsHandlers implements UpdatesCallback {
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} }
private void onLanguageSelected(Message message) { private void onLanguageSelected(Message message) throws InvalidObjectException {
String[] parts = message.getText().split("-->", 2); String[] parts = message.getText().split("-->", 2);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) { if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) {
DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim()); DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim());
sendMessageRequest.setText(LocalisationService.getInstance().getString("languageModified", parts[0].trim())); sendMessageRequest.setText(LocalisationService.getInstance().getString("languageModified", parts[0].trim()));

61
src/main/java/org/telegram/updateshandlers/FilesHandlers.java

@ -4,19 +4,21 @@ import org.telegram.BotConfig;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.SenderHelper; import org.telegram.SenderHelper;
import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendDocument;
import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.Message; import org.telegram.api.objects.Message;
import org.telegram.api.objects.ReplyKeyboardHide; import org.telegram.api.objects.ReplyKeyboardHide;
import org.telegram.api.objects.ReplyKeyboardMarkup; import org.telegram.api.objects.ReplyKeyboardMarkup;
import org.telegram.api.objects.Update; import org.telegram.api.objects.Update;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.api.methods.BotApiMethod; import org.telegram.services.BotLogger;
import org.telegram.api.methods.SendDocument;
import org.telegram.api.methods.SendMessage;
import org.telegram.services.Emoji; import org.telegram.services.Emoji;
import org.telegram.services.LocalisationService; import org.telegram.services.LocalisationService;
import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.UpdatesThread;
import org.telegram.updatesreceivers.Webhook; import org.telegram.updatesreceivers.Webhook;
import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -31,6 +33,7 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class FilesHandlers implements UpdatesCallback { public class FilesHandlers implements UpdatesCallback {
private static final String LOGTAG = "FILESHANDLERS";
private static final String TOKEN = BotConfig.TOKENFILES; private static final String TOKEN = BotConfig.TOKENFILES;
private static final String BOTNAME = BotConfig.USERNAMEFILES; private static final String BOTNAME = BotConfig.USERNAMEFILES;
private static final boolean USEWEBHOOK = false; private static final boolean USEWEBHOOK = false;
@ -40,7 +43,7 @@ public class FilesHandlers implements UpdatesCallback {
private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>();
public FilesHandlers(Webhook webhook) { public FilesHandlers(Webhook webhook) {
if (USEWEBHOOK) { if (USEWEBHOOK && BuildVars.useWebHook) {
webhook.registerWebhook(this, BOTNAME); webhook.registerWebhook(this, BOTNAME);
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else { } else {
@ -51,7 +54,11 @@ public class FilesHandlers implements UpdatesCallback {
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
handleFileUpdate(update); try {
handleFileUpdate(update);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} }
@Override @Override
@ -60,7 +67,7 @@ public class FilesHandlers implements UpdatesCallback {
return null; return null;
} }
public void handleFileUpdate(Update update) { public void handleFileUpdate(Update update) throws InvalidObjectException {
Message message = update.getMessage(); Message message = update.getMessage();
if (message != null && message.hasText()) { if (message != null && message.hasText()) {
if (languageMessages.contains(message.getFrom().getId())) { if (languageMessages.contains(message.getFrom().getId())) {
@ -99,12 +106,12 @@ public class FilesHandlers implements UpdatesCallback {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getInstance().getString("fileUploaded", language) + sendMessageRequest.setText(LocalisationService.getInstance().getString("fileUploaded", language) +
LocalisationService.getInstance().getString("uploadedFileURL", language) + message.getDocument().getFileId()); LocalisationService.getInstance().getString("uploadedFileURL", language) + message.getDocument().getFileId());
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
} }
private void onListCommand(Message message, String language) { private void onListCommand(Message message, String language) throws InvalidObjectException {
HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId()); HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
if (files.size() > 0) { if (files.size() > 0) {
@ -117,14 +124,14 @@ public class FilesHandlers implements UpdatesCallback {
} else { } else {
sendMessageRequest.setText(LocalisationService.getInstance().getString("noFiles", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("noFiles", language));
} }
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide(); ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
replyKeyboardHide.setHideKeyboard(true); replyKeyboardHide.setHideKeyboard(true);
sendMessageRequest.setReplayMarkup(replyKeyboardHide); sendMessageRequest.setReplayMarkup(replyKeyboardHide);
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
private void onDeleteCommand(Message message, String language, String[] parts) { private void onDeleteCommand(Message message, String language, String[] parts) throws InvalidObjectException {
if (DatabaseManager.getInstance().getUserStatusForFile(message.getFrom().getId()) == DELETE_UPLOADED_STATUS && if (DatabaseManager.getInstance().getUserStatusForFile(message.getFrom().getId()) == DELETE_UPLOADED_STATUS &&
parts.length == 2) { parts.length == 2) {
onDeleteCommandWithParameters(message, language, parts[1]); onDeleteCommandWithParameters(message, language, parts[1]);
@ -133,11 +140,11 @@ public class FilesHandlers implements UpdatesCallback {
} }
} }
private void onDeleteCommandWithoutParameters(Message message, String language) { private void onDeleteCommandWithoutParameters(Message message, String language) throws InvalidObjectException {
DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), DELETE_UPLOADED_STATUS); DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), DELETE_UPLOADED_STATUS);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getInstance().getString("deleteUploadedFile", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("deleteUploadedFile", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId()); HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId());
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
if (files.size() > 0) { if (files.size() > 0) {
@ -156,7 +163,7 @@ public class FilesHandlers implements UpdatesCallback {
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
private void onDeleteCommandWithParameters(Message message, String language, String part) { private void onDeleteCommandWithParameters(Message message, String language, String part) throws InvalidObjectException {
String[] innerParts = part.split(Emoji.LEFT_RIGHT_ARROW.toString(), 2); String[] innerParts = part.split(Emoji.LEFT_RIGHT_ARROW.toString(), 2);
boolean removed = DatabaseManager.getInstance().deleteFile(innerParts[0].trim()); boolean removed = DatabaseManager.getInstance().deleteFile(innerParts[0].trim());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
@ -165,55 +172,55 @@ public class FilesHandlers implements UpdatesCallback {
} else { } else {
sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language));
} }
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
} }
private void onCancelCommand(Message message, String language) { private void onCancelCommand(Message message, String language) throws InvalidObjectException {
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getInstance().getString("processFinished", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("processFinished", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
private void onUploadCommand(Message message, String language) { private void onUploadCommand(Message message, String language) throws InvalidObjectException {
DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), INITIAL_UPLOAD_STATUS); DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), INITIAL_UPLOAD_STATUS);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getInstance().getString("sendFileToUpload", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("sendFileToUpload", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
private void sendHelpMessage(Message message, String language) { private void sendHelpMessage(Message message, String language) throws InvalidObjectException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
String formatedString = String.format( String formatedString = String.format(
LocalisationService.getInstance().getString("helpFiles", language), LocalisationService.getInstance().getString("helpFiles", language),
Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand, Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand,
Commands.listCommand); Commands.listCommand);
sendMessageRequest.setText(formatedString); sendMessageRequest.setText(formatedString);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
private void onStartWithParameters(Message message, String language, String part) { private void onStartWithParameters(Message message, String language, String part) throws InvalidObjectException {
if (DatabaseManager.getInstance().doesFileExists(part.trim())) { if (DatabaseManager.getInstance().doesFileExists(part.trim())) {
SendDocument sendDocumentRequest = new SendDocument(); SendDocument sendDocumentRequest = new SendDocument();
sendDocumentRequest.setDocument(part.trim()); sendDocumentRequest.setDocument(part.trim());
sendDocumentRequest.setChatId(message.getChatId()); sendDocumentRequest.setChatId(message.getChatId().toString());
SenderHelper.SendDocument(sendDocumentRequest, TOKEN); SenderHelper.SendDocument(sendDocumentRequest, TOKEN);
} else { } else {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
} }
private void onSetLanguageCommand(Message message, String language) { private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
HashMap<String, String> languages = LocalisationService.getInstance().getSupportedLanguages(); HashMap<String, String> languages = LocalisationService.getInstance().getSupportedLanguages();
List<List<String>> commands = new ArrayList<>(); List<List<String>> commands = new ArrayList<>();
@ -232,10 +239,10 @@ public class FilesHandlers implements UpdatesCallback {
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} }
private void onLanguageReceived(Message message) { private void onLanguageReceived(Message message) throws InvalidObjectException {
String[] parts = message.getText().split(Emoji.LEFT_RIGHT_ARROW.toString(), 2); String[] parts = message.getText().split(Emoji.LEFT_RIGHT_ARROW.toString(), 2);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) { if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) {
DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim()); DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim());
sendMessageRequest.setText(LocalisationService.getInstance().getString("languageModified", parts[0].trim())); sendMessageRequest.setText(LocalisationService.getInstance().getString("languageModified", parts[0].trim()));

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

31
src/main/java/org/telegram/updateshandlers/TransifexHandlers.java

@ -1,17 +1,23 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.*; import org.telegram.BotConfig;
import org.telegram.api.objects.Message; import org.telegram.BuildVars;
import org.telegram.api.objects.Update; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.SenderHelper;
import org.telegram.api.methods.BotApiMethod; import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendDocument; import org.telegram.api.methods.SendDocument;
import org.telegram.api.methods.SendMessage; import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.Update;
import org.telegram.database.DatabaseManager;
import org.telegram.services.BotLogger;
import org.telegram.services.LocalisationService; import org.telegram.services.LocalisationService;
import org.telegram.services.TransifexService; import org.telegram.services.TransifexService;
import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.UpdatesThread;
import org.telegram.updatesreceivers.Webhook; import org.telegram.updatesreceivers.Webhook;
import java.io.InvalidObjectException;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
@ -19,12 +25,13 @@ import org.telegram.updatesreceivers.Webhook;
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class TransifexHandlers implements UpdatesCallback { public class TransifexHandlers implements UpdatesCallback {
private static final String LOGTAG = "TRANSIFEXHANDLERS";
private static final String TOKEN = BotConfig.TOKENTRANSIFEX; private static final String TOKEN = BotConfig.TOKENTRANSIFEX;
private static final String BOTNAME = BotConfig.USERNAMETRANSIFEX; private static final String BOTNAME = BotConfig.USERNAMETRANSIFEX;
private static final boolean USEWEBHOOK = false; private static final boolean USEWEBHOOK = false;
public TransifexHandlers(Webhook webhook) { public TransifexHandlers(Webhook webhook) {
if (USEWEBHOOK) { if (USEWEBHOOK && BuildVars.useWebHook) {
webhook.registerWebhook(this, BOTNAME); webhook.registerWebhook(this, BOTNAME);
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else { } else {
@ -35,7 +42,11 @@ public class TransifexHandlers implements UpdatesCallback {
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
sendTransifexFile(update); try {
sendTransifexFile(update);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} }
@Override @Override
@ -44,7 +55,7 @@ public class TransifexHandlers implements UpdatesCallback {
return null; return null;
} }
public void sendTransifexFile(Update update) { public void sendTransifexFile(Update update) throws InvalidObjectException {
Message message = update.getMessage(); Message message = update.getMessage();
if (message != null && message.hasText()) { if (message != null && message.hasText()) {
String language = DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId()); String language = DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId());
@ -74,12 +85,12 @@ public class TransifexHandlers implements UpdatesCallback {
Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP, Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP,
Commands.transifexAndroidSupportCommand); Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated); sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
if (sendDocument != null) { if (sendDocument != null) {
sendDocument.setChatId(message.getChatId()); sendDocument.setChatId(message.getChatId().toString());
SenderHelper.SendDocument(sendDocument, TOKEN); SenderHelper.SendDocument(sendDocument, TOKEN);
} }
} else if (parts[0].startsWith(Commands.help) || } else if (parts[0].startsWith(Commands.help) ||
@ -91,7 +102,7 @@ public class TransifexHandlers implements UpdatesCallback {
Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP, Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP,
Commands.transifexAndroidSupportCommand); Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated); sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
} }
} }

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

@ -4,15 +4,16 @@ import org.telegram.BotConfig;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.SenderHelper; import org.telegram.SenderHelper;
import org.telegram.api.objects.*;
import org.telegram.database.DatabaseManager;
import org.telegram.api.methods.BotApiMethod; import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendMessage; import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.*;
import org.telegram.database.DatabaseManager;
import org.telegram.services.*; import org.telegram.services.*;
import org.telegram.structure.WeatherAlert; import org.telegram.structure.WeatherAlert;
import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.updatesreceivers.UpdatesThread;
import org.telegram.updatesreceivers.Webhook; import org.telegram.updatesreceivers.Webhook;
import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -24,6 +25,7 @@ import java.util.List;
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class WeatherHandlers implements UpdatesCallback { public class WeatherHandlers implements UpdatesCallback {
private static final String LOGTAG = "WEATHERHANDLERS";
private static final String TOKEN = BotConfig.TOKENWEATHER; private static final String TOKEN = BotConfig.TOKENWEATHER;
private static final String BOTNAME = BotConfig.USERNAMEWEATHER; private static final String BOTNAME = BotConfig.USERNAMEWEATHER;
private static final boolean USEWEBHOOK = true; private static final boolean USEWEBHOOK = true;
@ -46,7 +48,7 @@ public class WeatherHandlers implements UpdatesCallback {
private final Object webhookLock = new Object(); private final Object webhookLock = new Object();
public WeatherHandlers(Webhook webhook) { public WeatherHandlers(Webhook webhook) {
if (USEWEBHOOK) { if (USEWEBHOOK && BuildVars.useWebHook) {
webhook.registerWebhook(this, BOTNAME); webhook.registerWebhook(this, BOTNAME);
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else { } else {
@ -75,12 +77,19 @@ public class WeatherHandlers implements UpdatesCallback {
private static void sendAlerts() { private static void sendAlerts() {
List<WeatherAlert> allAlerts = DatabaseManager.getInstance().getAllAlerts(); List<WeatherAlert> allAlerts = DatabaseManager.getInstance().getAllAlerts();
for (WeatherAlert weatherAlert : allAlerts) { for (WeatherAlert weatherAlert : allAlerts) {
synchronized (Thread.currentThread()) {
try {
Thread.currentThread().wait(35);
} catch (InterruptedException e) {
BotLogger.severe(LOGTAG, e);
}
}
String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId()); String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId());
String weather = WeatherService.getInstance().fetchWeatherAlert(weatherAlert.getCityId(), String weather = WeatherService.getInstance().fetchWeatherAlert(weatherAlert.getCityId(),
weatherAlert.getUserId(), userOptions[0], userOptions[1]); weatherAlert.getUserId(), userOptions[0], userOptions[1]);
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(weatherAlert.getUserId()); sendMessage.setChatId(String.valueOf(weatherAlert.getUserId()));
sendMessage.setText(weather); sendMessage.setText(weather);
sendBuiltMessage(sendMessage); sendBuiltMessage(sendMessage);
} }
@ -88,17 +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 message = update.getMessage();
BotApiMethod botApiMethod = handleIncomingMessage(message); if (message.hasText() || message.hasLocation()) {
SenderHelper.SendApiMethod(botApiMethod, TOKEN); BotApiMethod botApiMethod = handleIncomingMessage(message);
try {
SenderHelper.SendApiMethod(botApiMethod, TOKEN);
} 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);
} }
@ -106,9 +121,9 @@ public class WeatherHandlers implements UpdatesCallback {
return null; return null;
} }
private static BotApiMethod onCancelCommand(Integer chatId, Integer userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) { private static BotApiMethod onCancelCommand(Long chatId, Integer userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayMarkup(getMainMenuKeyboard(language)); sendMessage.setReplayMarkup(getMainMenuKeyboard(language));
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
@ -124,7 +139,7 @@ public class WeatherHandlers implements UpdatesCallback {
private static BotApiMethod handleIncomingMessage(Message message) { private static BotApiMethod handleIncomingMessage(Message message) {
final int state = DatabaseManager.getInstance().getWeatherState(message.getFrom().getId(), message.getChatId()); final int state = DatabaseManager.getInstance().getWeatherState(message.getFrom().getId(), message.getChatId());
final String language = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[0]; final String language = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[0];
if (message.isGroupMessage() && message.hasText()) { if (!message.isUserMessage() && message.hasText()) {
if (isCommandForOther(message.getText())) { if (isCommandForOther(message.getText())) {
return null; return null;
} else if (message.getText().startsWith(Commands.STOPCOMMAND)){ } else if (message.getText().startsWith(Commands.STOPCOMMAND)){
@ -168,9 +183,9 @@ public class WeatherHandlers implements UpdatesCallback {
return botApiMethod; return botApiMethod;
} }
private static void sendHideKeyboard(Integer userId, Integer chatId, Integer messageId) { private static void sendHideKeyboard(Integer userId, Long chatId, Integer messageId) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
sendMessage.setText(Emoji.WAVING_HAND_SIGN.toString()); sendMessage.setText(Emoji.WAVING_HAND_SIGN.toString());
@ -180,8 +195,12 @@ public class WeatherHandlers implements UpdatesCallback {
replyKeyboardHide.setHideKeyboard(true); replyKeyboardHide.setHideKeyboard(true);
sendMessage.setReplayMarkup(replyKeyboardHide); sendMessage.setReplayMarkup(replyKeyboardHide);
SenderHelper.SendApiMethod(sendMessage, TOKEN); try {
DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE); SenderHelper.SendApiMethod(sendMessage, TOKEN);
DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} }
@ -231,7 +250,7 @@ public class WeatherHandlers implements UpdatesCallback {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setReplayMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getInstance().getString("alertDeleted", language)); sendMessage.setText(LocalisationService.getInstance().getString("alertDeleted", language));
@ -243,7 +262,7 @@ public class WeatherHandlers implements UpdatesCallback {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setReplayMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language));
@ -257,7 +276,7 @@ public class WeatherHandlers implements UpdatesCallback {
if (message.getText().equals(getCancelCommand(language))) { if (message.getText().equals(getCancelCommand(language))) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setReplayMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language));
@ -280,7 +299,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getAlertsKeyboard(language)); sendMessageRequest.setReplayMarkup(getAlertsKeyboard(language));
sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setReplayToMessageId(message.getMessageId());
sendMessageRequest.setText(getChooseNewAlertSetMessage(message.getText(), language)); sendMessageRequest.setText(getChooseNewAlertSetMessage(message.getText(), language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT);
return sendMessageRequest; return sendMessageRequest;
@ -316,7 +335,7 @@ public class WeatherHandlers implements UpdatesCallback {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayMarkup(replyKeyboardMarkup);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
@ -327,7 +346,7 @@ public class WeatherHandlers implements UpdatesCallback {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setReplayMarkup(getAlertsKeyboard(language));
sendMessage.setText(getAlertListMessage(message.getFrom().getId(), language)); sendMessage.setText(getAlertListMessage(message.getFrom().getId(), language));
@ -340,7 +359,7 @@ public class WeatherHandlers implements UpdatesCallback {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
ReplyKeyboardMarkup replyKeyboardMarkup = getAlertsListKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getAlertsListKeyboard(message.getFrom().getId(), language);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
@ -360,7 +379,7 @@ public class WeatherHandlers implements UpdatesCallback {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayMarkup(getRecentsKeyboard(message.getFrom().getId(), language, false)); sendMessage.setReplayMarkup(getRecentsKeyboard(message.getFrom().getId(), language, false));
sendMessage.setText(LocalisationService.getInstance().getString("chooseNewAlertCity", language)); sendMessage.setText(LocalisationService.getInstance().getString("chooseNewAlertCity", language));
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
@ -397,7 +416,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setReplayMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language));
@ -410,7 +429,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayMarkup(getUnitsKeyboard(language)); sendMessage.setReplayMarkup(getUnitsKeyboard(language));
sendMessage.setText(getUnitsMessage(message.getFrom().getId(), language)); sendMessage.setText(getUnitsMessage(message.getFrom().getId(), language));
@ -423,7 +442,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplayMarkup(getLanguagesKeyboard(language)); sendMessage.setReplayMarkup(getLanguagesKeyboard(language));
sendMessage.setText(getLanguageMessage(language)); sendMessage.setText(getLanguageMessage(language));
@ -460,17 +479,17 @@ public class WeatherHandlers implements UpdatesCallback {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayMarkup(replyKeyboardMarkup);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
return sendMessage; return sendMessage;
} }
private static BotApiMethod onUnitsError(Integer chatId, Integer messageId, String language) { private static BotApiMethod onUnitsError(Long chatId, Integer messageId, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setReplayMarkup(getUnitsKeyboard(language)); sendMessageRequest.setReplayMarkup(getUnitsKeyboard(language));
sendMessageRequest.setText(LocalisationService.getInstance().getString("errorUnitsNotFound", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("errorUnitsNotFound", language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
@ -478,12 +497,12 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onUnitsChosen(Integer userId, Integer chatId, Integer messageId, String units, String language) { private static BotApiMethod onUnitsChosen(Integer userId, Long chatId, Integer messageId, String units, String language) {
DatabaseManager.getInstance().putUserWeatherUnitsOption(userId, units); DatabaseManager.getInstance().putUserWeatherUnitsOption(userId, units);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setText(LocalisationService.getInstance().getString("unitsUpdated", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("unitsUpdated", language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
@ -518,17 +537,17 @@ public class WeatherHandlers implements UpdatesCallback {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayMarkup(replyKeyboardMarkup);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
return sendMessage; return sendMessage;
} }
private static BotApiMethod onLanguageError(Integer chatId, Integer messageId, String language) { private static BotApiMethod onLanguageError(Long chatId, Integer messageId, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setReplayMarkup(getLanguagesKeyboard(language)); sendMessageRequest.setReplayMarkup(getLanguagesKeyboard(language));
sendMessageRequest.setText(LocalisationService.getInstance().getString("errorLanguageNotFound", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("errorLanguageNotFound", language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
@ -536,13 +555,13 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onLanguageChosen(Integer userId, Integer chatId, Integer messageId, String language) { private static BotApiMethod onLanguageChosen(Integer userId, Long chatId, Integer messageId, String language) {
String languageCode = LocalisationService.getInstance().getLanguageCodeByName(language); String languageCode = LocalisationService.getInstance().getLanguageCodeByName(language);
DatabaseManager.getInstance().putUserWeatherLanguageOption(userId, languageCode); DatabaseManager.getInstance().putUserWeatherLanguageOption(userId, languageCode);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setText(LocalisationService.getInstance().getString("languageUpdated", languageCode)); sendMessageRequest.setText(LocalisationService.getInstance().getString("languageUpdated", languageCode));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(languageCode)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(languageCode));
@ -597,7 +616,7 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onForecastWeatherCityReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { private static BotApiMethod onForecastWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) {
Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text); Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text);
if (cityId != null) { if (cityId != null) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
@ -607,7 +626,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
@ -616,12 +635,12 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onLocationForecastWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { private static BotApiMethod onLocationForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setReplayMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getInstance().getString("onWeatherLocationCommand", language)); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherLocationCommand", language));
@ -630,12 +649,12 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onNewForecastWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { private static BotApiMethod onNewForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setReplayMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getInstance().getString("onWeatherNewCommand", language)); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherNewCommand", language));
@ -699,7 +718,7 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onCurrentWeatherCityReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { private static BotApiMethod onCurrentWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) {
Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text); Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text);
if (cityId != null) { if (cityId != null) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
@ -709,7 +728,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
} else { } else {
@ -717,12 +736,12 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onLocationCurrentWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { private static BotApiMethod onLocationCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setReplayMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getInstance().getString("onWeatherLocationCommand", language)); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherLocationCommand", language));
@ -731,12 +750,12 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onNewCurrentWeatherCommand(Integer chatId, Integer userId, Integer messageId, String language) { private static BotApiMethod onNewCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
sendMessage.setReplayMarkup(forceReplyKeyboard); sendMessage.setReplayMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getInstance().getString("onWeatherNewCommand", language)); sendMessage.setText(LocalisationService.getInstance().getString("onWeatherNewCommand", language));
@ -767,7 +786,7 @@ public class WeatherHandlers implements UpdatesCallback {
} else if (message.getText().equals(getSettingsCommand(language))) { } else if (message.getText().equals(getSettingsCommand(language))) {
botApiMethod = onSettingsChoosen(message, language); botApiMethod = onSettingsChoosen(message, language);
} else if (message.getText().equals(getRateCommand(language))) { } else if (message.getText().equals(getRateCommand(language))) {
botApiMethod = sendRateMessage(message.getChatId(), message.getMessageId(), null, language); botApiMethod = sendRateMessage(message.getChatId().toString(), message.getMessageId(), null, language);
} else { } else {
botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(),
getMainMenuKeyboard(language), language); getMainMenuKeyboard(language), language);
@ -787,7 +806,7 @@ public class WeatherHandlers implements UpdatesCallback {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayMarkup(replyKeyboardMarkup);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
@ -801,7 +820,7 @@ public class WeatherHandlers implements UpdatesCallback {
ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language);
sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayMarkup(replyKeyboardMarkup);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
if (replyKeyboardMarkup.getKeyboard().size() > 3) { if (replyKeyboardMarkup.getKeyboard().size() > 3) {
sendMessage.setText(LocalisationService.getInstance().getString("onForecastCommandFromHistory", language)); sendMessage.setText(LocalisationService.getInstance().getString("onForecastCommandFromHistory", language));
} else { } else {
@ -819,7 +838,7 @@ public class WeatherHandlers implements UpdatesCallback {
ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language);
sendMessage.setReplayMarkup(replyKeyboardMarkup); sendMessage.setReplayMarkup(replyKeyboardMarkup);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(message.getChatId().toString());
if (replyKeyboardMarkup.getKeyboard().size() > 3) { if (replyKeyboardMarkup.getKeyboard().size() > 3) {
sendMessage.setText(LocalisationService.getInstance().getString("onCurrentCommandFromHistory", language)); sendMessage.setText(LocalisationService.getInstance().getString("onCurrentCommandFromHistory", language));
} else { } else {
@ -1136,14 +1155,14 @@ public class WeatherHandlers implements UpdatesCallback {
private static BotApiMethod sendMessageDefault(Message message, String language) { private static BotApiMethod sendMessageDefault(Message message, String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = getMainMenuKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getMainMenuKeyboard(language);
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU);
return sendHelpMessage(message.getChatId(), message.getMessageId(), replyKeyboardMarkup, language); return sendHelpMessage(message.getChatId().toString(), message.getMessageId(), replyKeyboardMarkup, language);
} }
private static BotApiMethod sendChooseOptionMessage(Integer chatId, Integer messageId, private static BotApiMethod sendChooseOptionMessage(Long chatId, Integer messageId,
ReplyKeyboard replyKeyboard, String language) { ReplyKeyboard replyKeyboard, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId.toString());
sendMessage.setReplayToMessageId(messageId); sendMessage.setReplayToMessageId(messageId);
sendMessage.setReplayMarkup(replyKeyboard); sendMessage.setReplayMarkup(replyKeyboard);
sendMessage.setText(LocalisationService.getInstance().getString("chooseOption", language)); sendMessage.setText(LocalisationService.getInstance().getString("chooseOption", language));
@ -1151,7 +1170,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod sendHelpMessage(Integer chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { private static BotApiMethod sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId);
@ -1163,7 +1182,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod sendRateMessage(Integer chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { private static BotApiMethod sendRateMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId);
@ -1189,13 +1208,13 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setReplayToMessageId(message.getMessageId());
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU);
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onForecastWeatherReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { private static BotApiMethod onForecastWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
String weather = WeatherService.getInstance().fetchWeatherForecast(text, userId, language, unitsSystem); String weather = WeatherService.getInstance().fetchWeatherForecast(text, userId, language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
@ -1203,7 +1222,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
@ -1218,13 +1237,13 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setReplayToMessageId(message.getMessageId());
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(message.getChatId().toString());
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU);
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onCurrentWeatherReceived(Integer chatId, Integer userId, Integer messageId, String text, String language) { private static BotApiMethod onCurrentWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
String weather = WeatherService.getInstance().fetchWeatherCurrent(text, userId, language, unitsSystem); String weather = WeatherService.getInstance().fetchWeatherCurrent(text, userId, language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
@ -1232,7 +1251,7 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplayMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplayToMessageId(messageId); sendMessageRequest.setReplayToMessageId(messageId);
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId); sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
@ -1243,7 +1262,11 @@ public class WeatherHandlers implements UpdatesCallback {
// region Helper Methods // region Helper Methods
private static void sendBuiltMessage(SendMessage sendMessage) { private static void sendBuiltMessage(SendMessage sendMessage) {
SenderHelper.SendApiMethod(sendMessage, TOKEN); try {
SenderHelper.SendApiMethod(sendMessage, TOKEN);
} catch (InvalidObjectException e) {
BotLogger.severe(LOGTAG, e);
}
} }
// endregion Helper Methods // endregion Helper Methods

20
src/main/java/org/telegram/updatesreceivers/UpdatesThread.java

@ -13,10 +13,10 @@ import org.apache.http.util.EntityUtils;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.api.objects.Update;
import org.telegram.database.DatabaseManager;
import org.telegram.api.methods.Constants; import org.telegram.api.methods.Constants;
import org.telegram.api.methods.GetUpdates; import org.telegram.api.methods.GetUpdates;
import org.telegram.api.objects.Update;
import org.telegram.database.DatabaseManager;
import org.telegram.services.BotLogger; import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.UpdatesCallback; import org.telegram.updateshandlers.UpdatesCallback;
@ -32,7 +32,7 @@ import java.util.concurrent.TimeUnit;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class UpdatesThread { public class UpdatesThread {
private static volatile BotLogger log = BotLogger.getLogger(UpdatesThread.class.getName()); private static final String LOGTAG = "UPDATESTHREAD";
private final UpdatesCallback callback; private final UpdatesCallback callback;
private final ReaderThread readerThread; private final ReaderThread readerThread;
@ -67,7 +67,7 @@ public class UpdatesThread {
httpPost.addHeader("charset", "UTF-8"); httpPost.addHeader("charset", "UTF-8");
httpPost.setEntity(new StringEntity(request.toJson().toString(), ContentType.APPLICATION_JSON)); httpPost.setEntity(new StringEntity(request.toJson().toString(), ContentType.APPLICATION_JSON));
HttpResponse response; HttpResponse response;
log.debug(httpPost.toString()); BotLogger.debug(LOGTAG, httpPost.toString());
response = httpclient.execute(httpPost); response = httpclient.execute(httpPost);
HttpEntity ht = response.getEntity(); HttpEntity ht = response.getEntity();
@ -80,7 +80,7 @@ public class UpdatesThread {
throw new InvalidObjectException(jsonObject.toString()); throw new InvalidObjectException(jsonObject.toString());
} }
JSONArray jsonArray = jsonObject.getJSONArray("result"); JSONArray jsonArray = jsonObject.getJSONArray("result");
log.debug(jsonArray.toString()); BotLogger.debug(LOGTAG, jsonArray.toString());
if (jsonArray.length() != 0) { if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) { for (int i = 0; i < jsonArray.length(); i++) {
Update update = new Update(jsonArray.getJSONObject(i)); Update update = new Update(jsonArray.getJSONObject(i));
@ -98,15 +98,15 @@ public class UpdatesThread {
this.wait(500); this.wait(500);
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.error(e); BotLogger.error(LOGTAG, e);
continue; continue;
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
log.warning(e); BotLogger.warn(LOGTAG, e);
} }
} catch (IOException e) { } catch (IOException e) {
log.warning(e); BotLogger.warn(LOGTAG, e);
} }
} }
} }
@ -124,7 +124,7 @@ public class UpdatesThread {
try { try {
receivedUpdates.wait(); receivedUpdates.wait();
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.error(e); BotLogger.error(LOGTAG, e);
continue; continue;
} }
update = receivedUpdates.pollLast(); update = receivedUpdates.pollLast();
@ -136,7 +136,7 @@ public class UpdatesThread {
DatabaseManager.getInstance().putLastUpdate(token, update.getUpdateId()); DatabaseManager.getInstance().putLastUpdate(token, update.getUpdateId());
callback.onUpdateReceived(update); callback.onUpdateReceived(update);
} catch (Exception e) { } catch (Exception e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }
} }

6
src/main/java/org/telegram/updatesreceivers/Webhook.java

@ -21,7 +21,7 @@ import java.net.URI;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class Webhook { public class Webhook {
private static volatile BotLogger log = BotLogger.getLogger(Webhook.class.getName()); private static final String LOGTAG = "WEBHOOK";
private static final String KEYSTORE_SERVER_FILE = "./keystore_server"; private static final String KEYSTORE_SERVER_FILE = "./keystore_server";
private static final String KEYSTORE_SERVER_PWD = "asdfgh"; private static final String KEYSTORE_SERVER_PWD = "asdfgh";
@ -47,7 +47,7 @@ public class Webhook {
rc.register(restApi); rc.register(restApi);
rc.register(JacksonFeature.class); rc.register(JacksonFeature.class);
rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true); rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true);
log.error("Internal webhook: " + getBaseURI().toString()); BotLogger.info(LOGTAG, "Internal webhook: " + getBaseURI().toString());
final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer( final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(
getBaseURI(), getBaseURI(),
rc, rc,
@ -56,7 +56,7 @@ public class Webhook {
try { try {
grizzlyServer.start(); grizzlyServer.start();
} catch (IOException e) { } catch (IOException e) {
log.error(e); BotLogger.error(LOGTAG, e);
} }
} }

75
src/main/resources/localisation/strings_eo.properties

@ -0,0 +1,75 @@
helpTransifex= \u0108u vi estas suferanto de babela eraro? Provu min por Telegram-tradukaro.\n\nPor ricevi la plej lastatempan Telegram-tradukdosieron por lingvo\: \n|-- %s LINGVOKODO \: Ricevi la plej lastatempan iOS-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Android-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Webogram-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Tdesktop-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan OSX-App-tradukon.\n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Windows Phone-tradukon.\n\n2. Por ricevi \u011disdatigitan tradukdosieron por via Android-beta-aplika\u0135o\: \n|-- %s LINGVOKODO \: Ricevi la plej lastatempan Android-beta-tradukon.\n\n(La lingvokodo de Esperanto estas\: eo)
helpFiles= \u0108u vi volas konigi dosieron al piratoj? Bonvolu resti \u0109i tie kun viaj boatoj\!\n\nKonigi dosierojn per ligilo\: \n|-- %s DOSIERIDENTIGILO \: Ricevi dosieron per identigilo.\n|-- %s \: Komenci dosieral\u015duton.\n|-- %s \: Elekti unu de viaj dosieroj por forigi \u011din.\n|-- %s \: Montri liston de viaj al\u015dutitaj dosieroj.
helpDirections= Se mapon mi havus, mi bone voja\u011dus.\n\nPor ricevi veturinstrukcion inter du lokoj\: \n|-- %s \: Komenci ricevi veturinstrukcion
sendFileToUpload= Sendu al mi dosieron kiun vi volas konigi. Certu, ke vi aligos \u011din kiel dosieron, ne kiel bildon a\u016d videon.
fileUploaded= Bone, via dosiero estas al\u015dutita. Sendu tiun ligilon al \u0109iuj ajn, kiujn vi volas kaj ili povos el\u015duti la dosieron\:\n
deleteUploadedFile= Elektu la dosieron, kiun vi volas forigi\:
fileDeleted= La dosiero estis forigita
wrongFileId= Mi beda\u016dras, mi ne povas trovi dosieron per tiu identigilo. A\u016d vi tajperaris a\u016d \u011di estis forigita jam.
listOfFiles= Jen viaj nunaj al\u015dutitaj dosieroj\:
noFiles= Vi ne havas ajnajn al\u015dutitajn dosierojn ankora\u016d.
processFinished= La nuna procezo estas nuligita.
uploadedFileURL= https\://telegram.me/filesbot?start\=
initDirections= Respondu al tiu mesa\u011do per via deirpunkto.
sendDestination= Respondu al tiu mesa\u011do per via destino.
youNeedReplyDirections= Mi beda\u016dras, mi ne povas helpi vin, krom se vi respondas al mia mesa\u011do.
chooselanguage= Elektu lingvon de la listo por \u015dan\u011di \u0109i tiun agordon.
errorLanguage= Mi ne subtenas tiun lingvon a\u016d vi tajperaris. La procezo estas nuligita.
directionsInit= %s trovi\u011das je %s for de %s, kaj necesas %s por alveni tien, sekvante tiun veturinstrukcion\:\n
directionsNotFound= Veturinstrukcio inter %s kaj %s ne estas trovita.
errorFetchingDirections= Mi beda\u016dras, eraro okazis dum ricevado de la veturinstrukcio.
directionsStep= %s dum %s (%s)
languageModified= Via lingvo-agordo estas \u011disdatigita.
helpWeatherMessage= Suno a\u016d pluvo, hajlo a\u016d glacio? \u0108u vi volas scii?\nDemandu al mi kaj mi donos la scion al vi\!\n\t\t%s Ricevu la nunan veteron de loko a\u016d urbo\n\t\t%s Ricevu prognozon por 3 tagoj de loko a\u016d urbo\n\t\t%s \u015can\u011du nunajn avertojn\n\t\t%s Elektu lingvon por prognozoj\n\t\t%s Elektu viajn preferitajn unuojn
forecast=%sPrognozo
current=%sNuna
help=%sHelpo
settings=%sAgordoj
cancel=%sNuligi
location=%sLoko
new=%sNova
languages=%sLingvoj
alerts=%sAvertoj
units=%sUnuoj
back=%sReen
delete=%sForigi
showList=%sMontri liston
rateMe=%sKlasifiku min
metricSystem=Metra sistemo
imperialSystem= Imperia sistemo
selectLanguage=Via nuna lingvo estas %s. Elektu lingvon de la listo por \u015dan\u011di \u0109i tiun agordon.
languageUpdated=Via lingvo-agordo estas \u011disdatigita.
errorLanguageNotFound= Mi ne subtenas tiun lingvon a\u016d vi tajperaris. Elektu alian el la listo.
selectUnits=Viaj nunaj unuoj estas %s. Elektu unuojn de la listo por \u015dan\u011di \u0109i tiun agordon.
unitsUpdated=Via unuo-agordo estas \u011disdatigita.
errorUnitsNotFound= Mi ne subtenas tiujn unuojn a\u016d vi tajperaris. Elektu unu de la listo.
onWeatherNewCommand=Sendu al mi la urbon, kiu vin interesas. Uzu la jenan formaton\: URBO,LANDO
onWeatherLocationCommand=Sendu al mi la lokon, kiu vin interesas.
onCurrentCommandFromHistory=Elektu opcion de viaj lastaj petoj, "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi la nunan veteron.
onCurrentCommandWithoutHistory=Elektu "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi la nunan veteron.
onForecastCommandFromHistory=Elektu opcion de viaj lastaj petoj, "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi prognozon por 3 tagoj.
onForecastCommandWithoutHistory=Elektu "nova" por sendi novan urbon a\u016d "loko" por sendi al mi lokon por ricevi prognozon por 3 tagoj.
weatherCurrent= La vetero por %s estas\:\n\n %s
currentWeatherPartMetric=\t- Vetero\: %s\n\t- Nubeco\: %s\n\t- Temperaturo\: %s \u00baC\n
currentWeatherPartImperial=\t- Vetero\: %s\n\t- Nubeco\: %s\n\t- Temperaturo\: %s \u00baF\n
weatherForcast= La vetero por %s estos\:\n\n %s
forecastWeatherPartMetric= %s je %s \n\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baC\n\t- Malalta temperaturo\: %s \u00baC\n
forecastWeatherPartImperial= %s je %s \n\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baF\n\t- Malalta temperaturo\: %s \u00baF\n
weatherAlert= La vetero por %s estos\:\n\n %s
alertWeatherPartMetric=\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baC\n\t- Malalta temperaturo\: %s \u00baC\n
alertWeatherPartImperial=\t- Prognozo\: %s\n\t- Alta temperaturo\: %s \u00baF\n\t- Malalta temperaturo\: %s \u00baF\n
chooseOption=Elektu opcion de la menuo.
backToMainMenu=Procezo estas nuligita, reen al la \u0109efa menuo.
onSettingsCommand=Elektu opcion\:\n\t\t%s Lingvoj\: Elektu lingvon por prognozoj\n\t\t%s Unuoj\: Elektu viajn preferitajn unuojn\n\t\t%s Avertoj\: \u015can\u011du tagajn avertojn\n\t\t%s Reen\: Reen al la \u0109efa menuo
alertsMenuMessage=\u0108i tie vi povas administri viajn avertojn a\u016d aldoni novajn avertojn.
chooseNewAlertCity=Por kiu urbo vi volas agordi averton? Elektu opcion de viaj lastaj petoj.
newAlertSaved=%s Via averto por %s estas kreita \u011duste, vi ricevos la veteron dufoje tage.
initialAlertList=Vi havas %d avertojn\:\n\n%s
partialAlertList=%s%s\n
noAlertList=Mi ne povas trovi ajnan averton por vi.
alertDeleted=La elektita averto estas forigita.
cityNotFound= Urbo ne estas trovita
errorFetchingWeather= Mi beda\u016dras, eraro okazis dum ricevado de la vetero.
rateMeMessage=Se vi \u015datas \u0109i tiun roboton, bonvolu klasifikadi \u011din \u0109e https\://telegram.me/storebot?start\=weatherbot
Loading…
Cancel
Save