Browse Source

1. Migrate to external API

master
Rubenlagu 10 years ago
committed by Rubenlagus
parent
commit
4324d8f5c1
  1. 1
      .idea/dataSources.xml
  2. 13
      .idea/libraries/Maven__com_github_rubenlagus_TelegramBots_v0_1_5.xml
  3. 8
      .idea/libraries/Maven__mysql_mysql_connector_java_5_1_38.xml
  4. 8
      .idea/libraries/Maven__org_glassfish_grizzly_grizzly_framework_2_3_23.xml
  5. 8
      .idea/libraries/Maven__org_glassfish_grizzly_grizzly_http_2_3_23.xml
  6. 8
      .idea/libraries/Maven__org_glassfish_grizzly_grizzly_http_server_2_3_23.xml
  7. 8
      .idea/libraries/Maven__org_glassfish_jersey_bundles_repackaged_jersey_guava_2_22_1.xml
  8. 8
      .idea/libraries/Maven__org_glassfish_jersey_containers_jersey_container_grizzly2_http_2_22_1.xml
  9. 8
      .idea/libraries/Maven__org_glassfish_jersey_core_jersey_client_2_22_1.xml
  10. 8
      .idea/libraries/Maven__org_glassfish_jersey_core_jersey_common_2_22_1.xml
  11. 8
      .idea/libraries/Maven__org_glassfish_jersey_core_jersey_server_2_22_1.xml
  12. 8
      .idea/libraries/Maven__org_glassfish_jersey_ext_jersey_entity_filtering_2_22_1.xml
  13. 8
      .idea/libraries/Maven__org_glassfish_jersey_media_jersey_media_jaxb_2_22_1.xml
  14. 8
      .idea/libraries/Maven__org_glassfish_jersey_media_jersey_media_json_jackson_2_22_1.xml
  15. 13
      .idea/libraries/Maven__org_json_json_20141113.xml
  16. 13
      .idea/libraries/Maven__org_json_json_20151123.xml
  17. 980
      .idea/workspace.xml
  18. 27
      BotAPi.iml
  19. 25
      pom.xml
  20. 33
      src/main/java/org/telegram/Main.java
  21. 287
      src/main/java/org/telegram/SenderHelper.java
  22. 13
      src/main/java/org/telegram/api/interfaces/BotApiObject.java
  23. 18
      src/main/java/org/telegram/api/interfaces/IToJson.java
  24. 138
      src/main/java/org/telegram/api/methods/AnswerInlineQuery.java
  25. 28
      src/main/java/org/telegram/api/methods/BotApiMethod.java
  26. 11
      src/main/java/org/telegram/api/methods/Constants.java
  27. 92
      src/main/java/org/telegram/api/methods/ForwardMessage.java
  28. 74
      src/main/java/org/telegram/api/methods/GetFile.java
  29. 50
      src/main/java/org/telegram/api/methods/GetMe.java
  30. 77
      src/main/java/org/telegram/api/methods/GetUpdates.java
  31. 102
      src/main/java/org/telegram/api/methods/GetUserProfilePhotos.java
  32. 104
      src/main/java/org/telegram/api/methods/SendAudio.java
  33. 86
      src/main/java/org/telegram/api/methods/SendChatAction.java
  34. 76
      src/main/java/org/telegram/api/methods/SendDocument.java
  35. 123
      src/main/java/org/telegram/api/methods/SendLocation.java
  36. 148
      src/main/java/org/telegram/api/methods/SendMessage.java
  37. 87
      src/main/java/org/telegram/api/methods/SendPhoto.java
  38. 76
      src/main/java/org/telegram/api/methods/SendSticker.java
  39. 98
      src/main/java/org/telegram/api/methods/SendVideo.java
  40. 31
      src/main/java/org/telegram/api/methods/SendVoice.java
  41. 39
      src/main/java/org/telegram/api/methods/SetWebhook.java
  42. 134
      src/main/java/org/telegram/api/objects/Audio.java
  43. 129
      src/main/java/org/telegram/api/objects/Chat.java
  44. 66
      src/main/java/org/telegram/api/objects/ChosenInlineQuery.java
  45. 68
      src/main/java/org/telegram/api/objects/Contact.java
  46. 119
      src/main/java/org/telegram/api/objects/Document.java
  47. 86
      src/main/java/org/telegram/api/objects/File.java
  48. 94
      src/main/java/org/telegram/api/objects/ForceReplyKeyboard.java
  49. 76
      src/main/java/org/telegram/api/objects/InlineQuery.java
  50. 13
      src/main/java/org/telegram/api/objects/InlineQueryResult.java
  51. 233
      src/main/java/org/telegram/api/objects/InlineQueryResultArticle.java
  52. 213
      src/main/java/org/telegram/api/objects/InlineQueryResultGif.java
  53. 214
      src/main/java/org/telegram/api/objects/InlineQueryResultMpeg4Gif.java
  54. 249
      src/main/java/org/telegram/api/objects/InlineQueryResultPhoto.java
  55. 245
      src/main/java/org/telegram/api/objects/InlineQueryResultVideo.java
  56. 66
      src/main/java/org/telegram/api/objects/Location.java
  57. 528
      src/main/java/org/telegram/api/objects/Message.java
  58. 96
      src/main/java/org/telegram/api/objects/PhotoSize.java
  59. 13
      src/main/java/org/telegram/api/objects/ReplyKeyboard.java
  60. 88
      src/main/java/org/telegram/api/objects/ReplyKeyboardHide.java
  61. 156
      src/main/java/org/telegram/api/objects/ReplyKeyboardMarkup.java
  62. 73
      src/main/java/org/telegram/api/objects/Sticker.java
  63. 104
      src/main/java/org/telegram/api/objects/Update.java
  64. 84
      src/main/java/org/telegram/api/objects/User.java
  65. 90
      src/main/java/org/telegram/api/objects/UserProfilePhotos.java
  66. 142
      src/main/java/org/telegram/api/objects/Video.java
  67. 99
      src/main/java/org/telegram/api/objects/Voice.java
  68. 2
      src/main/java/org/telegram/services/RaeService.java
  69. 2
      src/main/java/org/telegram/services/TransifexService.java
  70. 95
      src/main/java/org/telegram/updateshandlers/ChannelHandlers.java
  71. 103
      src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java
  72. 105
      src/main/java/org/telegram/updateshandlers/FilesHandlers.java
  73. 83
      src/main/java/org/telegram/updateshandlers/RaeHandlers.java
  74. 26
      src/main/java/org/telegram/updateshandlers/SentCallback.java
  75. 56
      src/main/java/org/telegram/updateshandlers/TransifexHandlers.java
  76. 24
      src/main/java/org/telegram/updateshandlers/UpdatesCallback.java
  77. 363
      src/main/java/org/telegram/updateshandlers/WeatherHandlers.java
  78. 52
      src/main/java/org/telegram/updatesreceivers/RestApi.java
  79. 144
      src/main/java/org/telegram/updatesreceivers/UpdatesThread.java
  80. 78
      src/main/java/org/telegram/updatesreceivers/Webhook.java

1
.idea/dataSources.xml

@ -13,7 +13,6 @@
<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>

13
.idea/libraries/Maven__com_github_rubenlagus_TelegramBots_v0_1_5.xml

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: com.github.rubenlagus:TelegramBots:v0.1.5">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/github/rubenlagus/TelegramBots/v0.1.5/TelegramBots-v0.1.5.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/github/rubenlagus/TelegramBots/v0.1.5/TelegramBots-v0.1.5-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/github/rubenlagus/TelegramBots/v0.1.5/TelegramBots-v0.1.5-sources.jar!/" />
</SOURCES>
</library>
</component>

8
.idea/libraries/Maven__mysql_mysql_connector_java_5_1_36.xml → .idea/libraries/Maven__mysql_mysql_connector_java_5_1_38.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: mysql:mysql-connector-java:5.1.36"> <library name="Maven: mysql:mysql-connector-java:5.1.38">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.36/mysql-connector-java-5.1.36.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.36/mysql-connector-java-5.1.36-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.36/mysql-connector-java-5.1.36-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_grizzly_grizzly_framework_2_3_22.xml → .idea/libraries/Maven__org_glassfish_grizzly_grizzly_framework_2_3_23.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.grizzly:grizzly-framework:2.3.22"> <library name="Maven: org.glassfish.grizzly:grizzly-framework:2.3.23">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.22/grizzly-framework-2.3.22.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.23/grizzly-framework-2.3.23.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.22/grizzly-framework-2.3.22-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.23/grizzly-framework-2.3.23-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.22/grizzly-framework-2.3.22-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.23/grizzly-framework-2.3.23-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_grizzly_grizzly_http_2_3_22.xml → .idea/libraries/Maven__org_glassfish_grizzly_grizzly_http_2_3_23.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.grizzly:grizzly-http:2.3.22"> <library name="Maven: org.glassfish.grizzly:grizzly-http:2.3.23">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.22/grizzly-http-2.3.22.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.23/grizzly-http-2.3.23.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.22/grizzly-http-2.3.22-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.23/grizzly-http-2.3.23-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.22/grizzly-http-2.3.22-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.23/grizzly-http-2.3.23-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_grizzly_grizzly_http_server_2_3_22.xml → .idea/libraries/Maven__org_glassfish_grizzly_grizzly_http_server_2_3_23.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.grizzly:grizzly-http-server:2.3.22"> <library name="Maven: org.glassfish.grizzly:grizzly-http-server:2.3.23">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.22/grizzly-http-server-2.3.22.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.23/grizzly-http-server-2.3.23.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.22/grizzly-http-server-2.3.22-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.23/grizzly-http-server-2.3.23-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.22/grizzly-http-server-2.3.22-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.23/grizzly-http-server-2.3.23-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_bundles_repackaged_jersey_guava_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_bundles_repackaged_jersey_guava_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.bundles.repackaged:jersey-guava:2.21"> <library name="Maven: org.glassfish.jersey.bundles.repackaged:jersey-guava:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.21/jersey-guava-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.22.1/jersey-guava-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.21/jersey-guava-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.22.1/jersey-guava-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.21/jersey-guava-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.22.1/jersey-guava-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_containers_jersey_container_grizzly2_http_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_containers_jersey_container_grizzly2_http_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.21"> <library name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.21/jersey-container-grizzly2-http-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.22.1/jersey-container-grizzly2-http-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.21/jersey-container-grizzly2-http-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.22.1/jersey-container-grizzly2-http-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.21/jersey-container-grizzly2-http-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.22.1/jersey-container-grizzly2-http-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_core_jersey_client_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_core_jersey_client_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.core:jersey-client:2.21"> <library name="Maven: org.glassfish.jersey.core:jersey-client:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.21/jersey-client-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.22.1/jersey-client-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.21/jersey-client-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.22.1/jersey-client-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.21/jersey-client-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.22.1/jersey-client-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_core_jersey_common_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_core_jersey_common_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.core:jersey-common:2.21"> <library name="Maven: org.glassfish.jersey.core:jersey-common:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.21/jersey-common-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.22.1/jersey-common-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.21/jersey-common-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.22.1/jersey-common-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.21/jersey-common-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.22.1/jersey-common-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_core_jersey_server_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_core_jersey_server_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.core:jersey-server:2.21"> <library name="Maven: org.glassfish.jersey.core:jersey-server:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.21/jersey-server-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.22.1/jersey-server-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.21/jersey-server-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.22.1/jersey-server-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.21/jersey-server-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.22.1/jersey-server-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_ext_jersey_entity_filtering_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_ext_jersey_entity_filtering_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.21"> <library name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.21/jersey-entity-filtering-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.22.1/jersey-entity-filtering-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.21/jersey-entity-filtering-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.22.1/jersey-entity-filtering-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.21/jersey-entity-filtering-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.22.1/jersey-entity-filtering-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_media_jersey_media_jaxb_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_media_jersey_media_jaxb_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.21"> <library name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.21/jersey-media-jaxb-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.22.1/jersey-media-jaxb-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.21/jersey-media-jaxb-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.22.1/jersey-media-jaxb-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.21/jersey-media-jaxb-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.22.1/jersey-media-jaxb-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

8
.idea/libraries/Maven__org_glassfish_jersey_media_jersey_media_json_jackson_2_21.xml → .idea/libraries/Maven__org_glassfish_jersey_media_jersey_media_json_jackson_2_22_1.xml

@ -1,13 +1,13 @@
<component name="libraryTable"> <component name="libraryTable">
<library name="Maven: org.glassfish.jersey.media:jersey-media-json-jackson:2.21"> <library name="Maven: org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1">
<CLASSES> <CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.21/jersey-media-json-jackson-2.21.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.22.1/jersey-media-json-jackson-2.22.1.jar!/" />
</CLASSES> </CLASSES>
<JAVADOC> <JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.21/jersey-media-json-jackson-2.21-javadoc.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.22.1/jersey-media-json-jackson-2.22.1-javadoc.jar!/" />
</JAVADOC> </JAVADOC>
<SOURCES> <SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.21/jersey-media-json-jackson-2.21-sources.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.22.1/jersey-media-json-jackson-2.22.1-sources.jar!/" />
</SOURCES> </SOURCES>
</library> </library>
</component> </component>

13
.idea/libraries/Maven__org_json_json_20141113.xml

@ -1,13 +0,0 @@
<component name="libraryTable">
<library name="Maven: org.json:json:20141113">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20141113/json-20141113.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20141113/json-20141113-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20141113/json-20141113-sources.jar!/" />
</SOURCES>
</library>
</component>

13
.idea/libraries/Maven__org_json_json_20151123.xml

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.json:json:20151123">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20151123/json-20151123.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20151123/json-20151123-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20151123/json-20151123-sources.jar!/" />
</SOURCES>
</library>
</component>

980
.idea/workspace.xml

File diff suppressed because it is too large

27
BotAPi.iml

@ -11,27 +11,28 @@
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.21" level="project" /> <orderEntry type="library" name="Maven: com.github.rubenlagus:TelegramBots:v0.1.5" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.22.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2.external:javax.inject:2.4.0-b31" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.hk2.external:javax.inject:2.4.0-b31" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-http-server:2.3.22" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-http-server:2.3.23" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-http:2.3.22" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-http:2.3.23" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-framework:2.3.22" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-framework:2.3.23" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-common:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-common:2.22.1" level="project" />
<orderEntry type="library" name="Maven: javax.annotation:javax.annotation-api:1.2" level="project" /> <orderEntry type="library" name="Maven: javax.annotation:javax.annotation-api:1.2" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.bundles.repackaged:jersey-guava:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.bundles.repackaged:jersey-guava:2.22.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-api:2.4.0-b31" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-api:2.4.0-b31" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-utils:2.4.0-b31" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-utils:2.4.0-b31" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2.external:aopalliance-repackaged:2.4.0-b31" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.hk2.external:aopalliance-repackaged:2.4.0-b31" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-locator:2.4.0-b31" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-locator:2.4.0-b31" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.18.1-GA" level="project" /> <orderEntry type="library" name="Maven: org.javassist:javassist:3.18.1-GA" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:osgi-resource-locator:1.0.1" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.hk2:osgi-resource-locator:1.0.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-server:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-server:2.22.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-client:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-client:2.22.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.22.1" level="project" />
<orderEntry type="library" name="Maven: javax.validation:validation-api:1.1.0.Final" level="project" /> <orderEntry type="library" name="Maven: javax.validation:validation-api:1.1.0.Final" level="project" />
<orderEntry type="library" name="Maven: javax.ws.rs:javax.ws.rs-api:2.0.1" level="project" /> <orderEntry type="library" name="Maven: javax.ws.rs:javax.ws.rs-api:2.0.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-json-jackson:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.21" level="project" /> <orderEntry type="library" name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.22.1" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:2.5.4" level="project" /> <orderEntry type="library" name="Maven: com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:2.5.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.5.4" level="project" /> <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.5.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.5.4" level="project" /> <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.5.4" level="project" />
@ -47,14 +48,14 @@
<orderEntry type="library" name="Maven: com.sun.jersey:jersey-core:1.19" level="project" /> <orderEntry type="library" name="Maven: com.sun.jersey:jersey-core:1.19" level="project" />
<orderEntry type="library" name="Maven: javax.servlet:javax.servlet-api:3.0.1" level="project" /> <orderEntry type="library" name="Maven: javax.servlet:javax.servlet-api:3.0.1" level="project" />
<orderEntry type="library" name="Maven: com.sun.jersey:jersey-servlet:1.19" level="project" /> <orderEntry type="library" name="Maven: com.sun.jersey:jersey-servlet:1.19" level="project" />
<orderEntry type="library" name="Maven: org.json:json:20141113" level="project" /> <orderEntry type="library" name="Maven: org.json:json:20151123" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.4" level="project" /> <orderEntry type="library" name="Maven: commons-io:commons-io:2.4" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.3" level="project" /> <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.3" level="project" />
<orderEntry type="library" name="Maven: commons-logging:commons-logging:1.2" level="project" /> <orderEntry type="library" name="Maven: commons-logging:commons-logging:1.2" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.9" level="project" /> <orderEntry type="library" name="Maven: commons-codec:commons-codec:1.9" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpmime:4.5.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpmime:4.5.1" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.36" level="project" /> <orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.38" level="project" />
<orderEntry type="library" name="Maven: org.jsoup:jsoup:1.8.3" level="project" /> <orderEntry type="library" name="Maven: org.jsoup:jsoup:1.8.3" level="project" />
</component> </component>
</module> </module>

25
pom.xml

@ -8,11 +8,25 @@
<artifactId>org.telegram.botapi</artifactId> <artifactId>org.telegram.botapi</artifactId>
<version>1.0</version> <version>1.0</version>
<repositories>
<repository>
<id>central</id>
<name>Maven Repository Switchboard</name>
<layout>default</layout>
<url>http://repo1.maven.org/maven2</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<jersey.version>2.21</jersey.version> <jersey.version>2.22.1</jersey.version>
<httpcompontents.version>4.5.1</httpcompontents.version> <httpcompontents.version>4.5.1</httpcompontents.version>
<telegrambots.version>v0.1.5</telegrambots.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
@ -28,6 +42,11 @@
</dependencyManagement> </dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>com.github.rubenlagus</groupId>
<artifactId>TelegramBots</artifactId>
<version>${telegrambots.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.containers</groupId> <groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId> <artifactId>jersey-container-grizzly2-http</artifactId>
@ -50,7 +69,7 @@
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
<version>20141113</version> <version>20151123</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
@ -70,7 +89,7 @@
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version> <version>5.1.38</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jsoup</groupId> <groupId>org.jsoup</groupId>

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

@ -1,7 +1,9 @@
package org.telegram; package org.telegram;
import org.telegram.services.BotLogger;
import org.telegram.telegrambots.TelegramApiException;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.updateshandlers.*; import org.telegram.updateshandlers.*;
import org.telegram.updatesreceivers.Webhook;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
@ -10,27 +12,20 @@ import org.telegram.updatesreceivers.Webhook;
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
public class Main { public class Main {
private static Webhook webhook; private static final String LOGTAG = "MAIN";
public static void main(String[] args) { public static void main(String[] args) {
if (BuildVars.useWebHook) { TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
webhook = new Webhook(); try {
telegramBotsApi.registerBot(new ChannelHandlers());
telegramBotsApi.registerBot(new DirectionsHandlers());
telegramBotsApi.registerBot(new RaeHandlers());
telegramBotsApi.registerBot(new WeatherHandlers());
telegramBotsApi.registerBot(new TransifexHandlers());
telegramBotsApi.registerBot(new FilesHandlers());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
} }
initBots();
if (BuildVars.useWebHook) {
webhook.startServer();
}
}
private static void initBots() {
UpdatesCallback weatherBot = new WeatherHandlers(webhook);
UpdatesCallback channelBot = new ChannelHandlers(webhook);
UpdatesCallback transifexBot = new TransifexHandlers(webhook);
UpdatesCallback filesBot = new FilesHandlers(webhook);
UpdatesCallback directionsBot = new DirectionsHandlers(webhook);
UpdatesCallback raeBot = new RaeHandlers(webhook);
} }
} }

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

@ -1,287 +0,0 @@
package org.telegram;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.telegram.api.methods.*;
import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.SentCallback;
import java.io.File;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Send Helper
* @date 20 of June of 2015
*/
public class SenderHelper {
private static final String LOGTAG = "SENDERHELPER";
private static final ExecutorService exe = Executors.newSingleThreadExecutor();
public static void SendDocument(SendDocument sendDocument, String botToken) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendDocument.PATH;
HttpPost httppost = new HttpPost(url);
if (sendDocument.isNewDocument()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId());
builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName());
if (sendDocument.getReplayMarkup() != null) {
builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString());
}
if (sendDocument.getReplayToMessageId() != null) {
builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString());
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
} else {
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendDocument.DOCUMENT_FIELD, sendDocument.getDocument()));
if (sendDocument.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toString()));
}
if (sendDocument.getReplayToMessageId() != null) {
nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
} finally {
if (sendDocument.isNewDocument()) {
File fileToDelete = new File(sendDocument.getDocument());
fileToDelete.delete();
}
}
}
public static void SendPhoto(SendPhoto sendPhoto, String botToken) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendPhoto.PATH;
HttpPost httppost = new HttpPost(url);
if (sendPhoto.isNewPhoto()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId());
builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName());
if (sendPhoto.getReplayMarkup() != null) {
builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString());
}
if (sendPhoto.getReplayToMessageId() != null) {
builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString());
}
if (sendPhoto.getCaption() != null) {
builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption());
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
} else {
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendPhoto.PHOTO_FIELD, sendPhoto.getPhoto()));
if (sendPhoto.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toString()));
}
if (sendPhoto.getReplayToMessageId() != null) {
nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString()));
}
if (sendPhoto.getCaption() != null) {
nameValuePairs.add(new BasicNameValuePair(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
}
public static void SendVideo(SendVideo sendVideo, String botToken) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendVideo.PATH;
HttpPost httppost = new HttpPost(url);
if (sendVideo.isNewVideo()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId());
builder.addBinaryBody(SendVideo.VIDEO_FIELD, new File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName());
if (sendVideo.getReplayMarkup() != null) {
builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString());
}
if (sendVideo.getReplayToMessageId() != null) {
builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString());
}
if (sendVideo.getCaption() != null) {
builder.addTextBody(SendVideo.CAPTION_FIELD, sendVideo.getCaption());
}
if (sendVideo.getDuration() != null) {
builder.addTextBody(SendVideo.DURATION_FIELD, sendVideo.getDuration().toString());
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
} else {
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendVideo.VIDEO_FIELD, sendVideo.getVideo()));
if (sendVideo.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toString()));
}
if (sendVideo.getReplayToMessageId() != null) {
nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString()));
}
if (sendVideo.getCaption() != null) {
nameValuePairs.add(new BasicNameValuePair(SendVideo.CAPTION_FIELD, sendVideo.getCaption()));
}
if (sendVideo.getDuration() != null) {
nameValuePairs.add(new BasicNameValuePair(SendVideo.DURATION_FIELD, sendVideo.getDuration().toString()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
}
public static void sendSticker(SendSticker sendSticker, String botToken) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendSticker.PATH;
HttpPost httppost = new HttpPost(url);
if (sendSticker.isNewSticker()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId());
builder.addBinaryBody(SendSticker.STICKER_FIELD, new File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName());
if (sendSticker.getReplayMarkup() != null) {
builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString());
}
if (sendSticker.getReplayToMessageId() != null) {
builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString());
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
} else {
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId()));
nameValuePairs.add(new BasicNameValuePair(SendSticker.STICKER_FIELD, sendSticker.getSticker()));
if (sendSticker.getReplayMarkup() != null) {
nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toString()));
}
if (sendSticker.getReplayToMessageId() != null) {
nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
} finally {
if (sendSticker.isNewSticker()) {
File fileToDelete = new File(sendSticker.getSticker());
fileToDelete.delete();
}
}
}
public static void SendWebhook(String webHookURL, String botToken) {
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + SetWebhook.PATH;
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, webHookURL);
if (BuildVars.pathToCertificatePublicKey != null) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, new File(BuildVars.pathToCertificatePublicKey), ContentType.APPLICATION_OCTET_STREAM, BuildVars.certificatePublicKeyFileName);
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
BotLogger.debug(LOGTAG, responseContent);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
}
public static void SendApiMethod(BotApiMethod method, String botToken) throws InvalidObjectException {
String responseContent = "{}";
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + method.getPath();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("charset", "UTF-8");
httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, "UTF-8");
} catch (IOException 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) {
exe.submit(() -> {
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + method.getPath();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("charset", "UTF-8");
httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
callback.onError(method, jsonObject);
}
callback.onResult(method, jsonObject);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
});
}
}

13
src/main/java/org/telegram/api/interfaces/BotApiObject.java

@ -1,13 +0,0 @@
package org.telegram.api.interfaces;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief An object of Telegram Bots Api
* @date 07 of September of 2015
*/
public interface BotApiObject extends JsonSerializable {
}

18
src/main/java/org/telegram/api/interfaces/IToJson.java

@ -1,18 +0,0 @@
package org.telegram.api.interfaces;
import org.json.JSONObject;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Add conversion to JSON object
* @date 08 of September of 2015
*/
public interface IToJson {
/**
* Convert to json object
* @return JSONObject created in the conversion
*/
JSONObject toJson();
}

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

@ -1,138 +0,0 @@
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);
}
}

28
src/main/java/org/telegram/api/methods/BotApiMethod.java

@ -1,28 +0,0 @@
package org.telegram.api.methods;
import com.fasterxml.jackson.databind.JsonSerializable;
import org.json.JSONObject;
import org.telegram.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief A method of Telegram Bots Api that is fully supported in json format
* @date 07 of September of 2015
*/
public abstract class BotApiMethod<T> implements JsonSerializable, IToJson {
protected static final String METHOD_FIELD = "method";
/**
* Getter for method path (that is the same as method name)
* @return Method path
*/
public abstract String getPath();
/**
* Deserialize a json answer to the response type to a method
* @param answer Json answer received
* @return Answer for the method
*/
public abstract T deserializeResponse(JSONObject answer);
}

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

@ -1,11 +0,0 @@
package org.telegram.api.methods;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief TODO
* @date 20 of June of 2015
*/
public class Constants {
public static final String BASEURL = "https://api.telegram.org/bot";
}

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

@ -1,92 +0,0 @@
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.JSONObject;
import org.telegram.api.objects.Message;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send text messages. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class ForwardMessage extends BotApiMethod<Message> {
public static final String PATH = "forwardmessage";
public static final String CHATID_FIELD = "chat_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";
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";
private Integer messageId; ///< Unique message identifier
public ForwardMessage() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public Integer getFromChatId() {
return fromChatId;
}
public void setFromChatId(Integer fromChatId) {
this.fromChatId = fromChatId;
}
public Integer getMessageId() {
return messageId;
}
public void setMessageId(Integer messageId) {
this.messageId = messageId;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(FROMCHATID_FIELD, fromChatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(FROMCHATID_FIELD, fromChatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
return jsonObject;
}
@Override
public String getPath() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return new Message(answer.getJSONObject("result"));
}
return null;
}
}

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

@ -1,74 +0,0 @@
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.JSONObject;
import org.telegram.api.objects.File;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to get basic info about a file and prepare it for downloading.
* For the moment, bots can download files of up to 20MB in size.
* On success, a File object is returned.
* The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
* where <file_path> is taken from the response.
* It is guaranteed that the link will be valid for at least 1 hour.
* When the link expires, a new one can be requested by calling getFile again.
* @date 20 of June of 2015
*/
public class GetFile extends BotApiMethod<File> {
public static final String PATH = "getfield";
public static final String FILEID_FIELD = "file_id";
private String fileId; ///< File identifier to get info about
public GetFile() {
super();
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FILEID_FIELD, fileId);
return jsonObject;
}
@Override
public String getPath() {
return PATH;
}
@Override
public File deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return new File(answer.getJSONObject("result"));
}
return null;
}
}

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

@ -1,50 +0,0 @@
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.JSONObject;
import org.telegram.api.objects.User;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief A simple method for testing your bot's auth token. Requires no parameters.
* Returns basic information about the bot in form of a User object
* @date 20 of June of 2015
*/
public class GetMe extends BotApiMethod<User> {
public static final String PATH = "getme";
@Override
public JSONObject toJson() {
return new JSONObject();
}
@Override
public String getPath() {
return PATH;
}
@Override
public User deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return new User(answer.getJSONObject("result"));
}
return null;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

77
src/main/java/org/telegram/api/methods/GetUpdates.java

@ -1,77 +0,0 @@
package org.telegram.api.methods;
import org.json.JSONObject;
import org.telegram.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to receive incoming updates using long polling (wiki).
* An Array of Update objects is returned.
* @date 20 of June of 2015
*/
public class GetUpdates implements IToJson {
public static final String PATH = "getupdates";
public static final String OFFSET_FIELD = "offset";
/**
* Optional Identifier of the first update to be returned.
* Must be greater by one than the highest among the identifiers of previously received updates.
* By default, updates starting with the earliest unconfirmed update are returned.
*/
private Integer offset;
public static final String LIMIT_FIELD = "limit";
/**
* Optional Limits the number of updates to be retrieved.
* Values between 1100 are accepted. Defaults to 100
*/
private Integer limit;
public static final String TIMEOUT_FIELD = "timeout";
/**
* Optional Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling
*/
private Integer timeout;
public GetUpdates() {
super();
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (offset != null) {
jsonObject.put(OFFSET_FIELD, offset);
}
if (limit != null) {
jsonObject.put(LIMIT_FIELD, limit);
}
if (timeout != null) {
jsonObject.put(TIMEOUT_FIELD, timeout);
}
return jsonObject;
}
}

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

@ -1,102 +0,0 @@
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.JSONObject;
import org.telegram.api.objects.UserProfilePhotos;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
* @date 20 of June of 2015
*/
public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
public static final String PATH = "getuserprofilephotos";
public static final String USERID_FIELD = "user_id";
private Integer userId; ///< Unique identifier of the target user
public static final String OFFSET_FIELD = "offset";
/**
* Sequential number of the first photo to be returned. By default, all photos are returned.
*/
private Integer offset;
public static final String LIMIT_FIELD = "limit";
/**
* Optional. Limits the number of photos to be retrieved. Values between 1100 are accepted. Defaults to 100.
*/
private Integer limit;
public GetUserProfilePhotos() {
super();
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(USERID_FIELD, userId);
jsonObject.put(OFFSET_FIELD, offset);
if (limit != null) {
jsonObject.put(LIMIT_FIELD, limit);
}
return jsonObject;
}
@Override
public String getPath() {
return PATH;
}
@Override
public UserProfilePhotos deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return new UserProfilePhotos(answer.getJSONObject("result"));
}
return null;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,104 +0,0 @@
package org.telegram.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send audio files,
* Use this method to send audio files, if you want Telegram clients to display them in the music player.
* Your audio must be in an .mp3 format. On success, the sent Message is returned.
* Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
*
* @note For backward compatibility, when both fields title and description are empty and mime-type of the sent
* file is not audio/mpeg, file is sent as playable voice message.
* In this case, your audio must be in an .ogg file encoded with OPUS.
* This will be removed in the future. You need to use sendVoice method instead.
*
* @date 16 of July of 2015
*/
public class SendAudio {
public static final String PATH = "sendaudio";
public static final String CHATID_FIELD = "chat_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";
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";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public static final String PERFOMER_FIELD = "performer";
private String performer; ///< Optional. Performer of sent audio
public static final String TITLE_FIELD = "title";
private String title; ///< Optional. Title of sent audio
private boolean isNewAudio;
private String audioName;
public SendAudio() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
this.isNewAudio = false;
}
public void setNewAudio(String audio, String audioName) {
this.audio = audio;
this.isNewAudio = true;
this.audioName = audioName;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isNewAudio() {
return isNewAudio;
}
public String getAudioName() {
return audioName;
}
}

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

@ -1,86 +0,0 @@
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.JSONObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot,
* Telegram clients clear its typing status).
* @date 20 of June of 2015
*/
public class SendChatAction extends BotApiMethod<Boolean>{
public static final String PATH = "sendChatAction";
public static final String CHATID_FIELD = "chat_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";
/**
* Type of action to broadcast.
* Choose one, depending on what the user is about to receive:
* 'typing' for text messages
* 'upload_photo' for photos
* 'record_video' or 'upload_video' for videos
* 'record_audio' or 'upload_audio' for audio files
* 'upload_document' for general files,
* 'find_location' for location data.
*/
private String action;
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
@Override
public String getPath() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return answer.getBoolean("result");
}
return null;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(ACTION_FIELD, action);
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(ACTION_FIELD, action);
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,76 +0,0 @@
package org.telegram.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send general files. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendDocument {
public static final String PATH = "senddocument";
public static final String CHATID_FIELD = "chat_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";
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";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
private boolean isNewDocument;
private String documentName;
public SendDocument() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
this.isNewDocument = false;
}
public void setNewDocument(String document, String documentName) {
this.document = document;
this.isNewDocument = true;
this.documentName = documentName;
}
public boolean isNewDocument() {
return isNewDocument;
}
public String getDocumentName() {
return documentName;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
}

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

@ -1,123 +0,0 @@
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.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.ReplyKeyboard;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send point on the map. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendLocation extends BotApiMethod<Message> {
public static final String PATH = "sendlocation";
public static final String CHATID_FIELD = "chat_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";
private Float latitude; ///< Latitude of location
public static final String LONGITUDE_FIELD = "longitude";
private Float longitude; ///< Longitude of location
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public Float getLatitude() {
return latitude;
}
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLongitude() {
return longitude;
}
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
@Override
public String getPath() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return new Message(answer.getJSONObject("result"));
}
return null;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(LATITUDE_FIELD, latitude);
jsonObject.put(LONGITUDE_FIELD, longitude);
if (replayToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId);
}
if (replayMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson());
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,148 +0,0 @@
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.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.ReplyKeyboard;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send text messages. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendMessage extends BotApiMethod<Message> {
public static final String PATH = "sendmessage";
public static final String CHATID_FIELD = "chat_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";
private String text; ///< Text of the message to be sent
public static final String PARSEMODE_FIELD = "parse_mode";
private String parseMode; ///< Optional. Send Markdown, if you want Telegram apps to show bold, italic and URL text in your bot's message.
public static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview";
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public SendMessage() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
public Boolean getDisableWebPagePreview() {
return disableWebPagePreview;
}
public void setDisableWebPagePreview(Boolean disableWebPagePreview) {
this.disableWebPagePreview = disableWebPagePreview;
}
public void enableMarkdown(boolean enable) {
if (enable) {
this.parseMode = "Markdown";
} else {
this.parseMode = null;
}
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(TEXT_FIELD, text);
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview);
}
if (replayToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId);
}
if (replayMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson());
}
return jsonObject;
}
@Override
public String getPath() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean("ok")) {
return new Message(answer.getJSONObject("result"));
}
return null;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,87 +0,0 @@
package org.telegram.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send photos. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendPhoto {
public static final String PATH = "sendphoto";
public static final String CHATID_FIELD = "chat_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";
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";
private String caption; ///< Optional Photo caption (may also be used when resending photos by file_id).
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
private boolean isNewPhoto; ///< True if the photo must be uploaded from a file, file if it is a fileId
private String photoName; ///< Name of the photo
public SendPhoto() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getPhoto() {
return photo;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
public boolean isNewPhoto() {
return isNewPhoto;
}
public String getPhotoName() {
return photoName;
}
public void setPhoto(String photo) {
this.photo = photo;
this.isNewPhoto = false;
}
public void setNewPhoto(String photo, String photoName) {
this.photo = photo;
this.isNewPhoto = true;
this.photoName = photoName;
}
}

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

@ -1,76 +0,0 @@
package org.telegram.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief TODO
* @date 20 of June of 2015
*/
public class SendSticker {
public static final String PATH = "sendsticker";
public static final String CHATID_FIELD = "chat_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";
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";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
private boolean isNewSticker;
private String stickerName;
public SendSticker() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getSticker() {
return sticker;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
public void setSticker(String sticker) {
this.sticker = sticker;
this.isNewSticker = false;
}
public void setSticker(String sticker, String stickerName) {
this.sticker = sticker;
this.isNewSticker = true;
this.stickerName = stickerName;
}
public boolean isNewSticker() {
return isNewSticker;
}
public String getStickerName() {
return stickerName;
}
}

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

@ -1,98 +0,0 @@
package org.telegram.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send video files,
* Telegram clients support mp4 videos (other formats may be sent as Document).
* On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendVideo {
public static final String PATH = "sendvideo";
public static final String CHATID_FIELD = "chat_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";
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";
private Integer duration; ///< Optional. Duration of sent video in seconds
public static final String CAPTION_FIELD = "caption";
private String caption; ///< OptionaL. Video caption (may also be used when resending videos by file_id).
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
private boolean isNewVideo; ///< True to upload a new video, false to use a fileId
private String videoName; ///< Name of the video
public SendVideo() {
super();
}
public String getChatId() {
return chatId;
}
public void setChatId(String chatId) {
this.chatId = chatId;
}
public String getVideo() {
return video;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public Integer getReplayToMessageId() {
return replayToMessageId;
}
public void setReplayToMessageId(Integer replayToMessageId) {
this.replayToMessageId = replayToMessageId;
}
public ReplyKeyboard getReplayMarkup() {
return replayMarkup;
}
public void setReplayMarkup(ReplyKeyboard replayMarkup) {
this.replayMarkup = replayMarkup;
}
public boolean isNewVideo() {
return isNewVideo;
}
public String getVideoName() {
return videoName;
}
public void setVideo(String video) {
this.video = video;
this.isNewVideo = false;
}
public void setNewVideo(String video, String videoName) {
this.video = video;
this.isNewVideo = true;
this.videoName = videoName;
}
}

31
src/main/java/org/telegram/api/methods/SendVoice.java

@ -1,31 +0,0 @@
package org.telegram.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send voice notes, if you want Telegram clients to display
* the file as a playable voice message.
* For this to work, your audio must be in an .ogg file encoded with OPUS
* (other formats may be sent as Audio or Document).
* @date 16 of July of 2015
*/
public class SendVoice {
public static final String PATH = "sendvoice";
public static final String CHATID_FIELD = "chat_id";
private String chatId; ///< Unique identifier for the chat sent message to (Or username for channels)
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
public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message
public static final String REPLYMARKUP_FIELD = "reply_markup";
private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public static final String DURATION_FIELD = "duration";
private Integer duration; ///< Optional. Duration of sent audio in seconds
public SendVoice() {
super();
}
}

39
src/main/java/org/telegram/api/methods/SetWebhook.java

@ -1,39 +0,0 @@
package org.telegram.api.methods;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to specify a url and receive incoming updates via an outgoing webhook.
* Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url,
* containing a JSON-serialized Update. In case of an unsuccessful request,
* we will give up after a reasonable amount of attempts.
* @date 20 of June of 2015
*/
public class SetWebhook {
public static final String PATH = "setwebhook";
public static final String URL_FIELD = "url";
private String url; ///< Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration
public static final String CERTIFICATE_FIELD = "certificate";
private String certificateFile; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked
public SetWebhook() {
this.url = "";
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCertificateFile() {
return certificateFile;
}
public void setCertificateFile(String certificateFile) {
this.certificateFile = certificateFile;
}
}

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

@ -1,134 +0,0 @@
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 audio file
* @date 16 of July of 2015
*/
public class Audio implements BotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
public static final String DURATION_FIELD = "duration";
@JsonProperty(DURATION_FIELD)
private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender
public static final String MIMETYPE_FIELD = "mime_type";
@JsonProperty(MIMETYPE_FIELD)
private String mimeType; ///< Optional. MIME type of the file as defined by sender
public static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public static final String TITLE_FIELD = "title";
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Title of the audio as defined by sender or by audio tags
public static final String PERFORMER_FIELD = "performer";
@JsonProperty(PERFORMER_FIELD)
private String performer; ///< Optional. Performer of the audio as defined by sender or by audio tags
public Audio() {
super();
}
public Audio(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.duration = jsonObject.getInt(DURATION_FIELD);
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILEID_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
if (jsonObject.has(TITLE_FIELD)) {
this.title = jsonObject.getString(TITLE_FIELD);
}
if (jsonObject.has(PERFORMER_FIELD)) {
this.performer = jsonObject.getString(PERFORMER_FIELD);
}
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,129 +0,0 @@
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 Telegram chat with an user or a group
* @date 24 of June of 2015
*/
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";
@JsonProperty(ID_FIELD)
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";
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Title of the chat, only for channels and group chat
public static final String FIRSTNAME_FIELD = "first_name";
@JsonProperty(FIRSTNAME_FIELD)
private String firstName; ///< Optional. Username of the chat, only for private chats and channels if available
public static final String LASTNAME_FIELD = "last_name";
@JsonProperty(LASTNAME_FIELD)
private String lastName; ///< Optional. Interlocutor's first name for private chats
public static final String USERNAME_FIELD = "username";
@JsonProperty(USERNAME_FIELD)
private String userName; ///< Optional. Interlocutor's last name for private chats
public Chat() {
super();
}
public Chat(JSONObject jsonObject) {
super();
this.id = jsonObject.getLong(ID_FIELD);
this.type = jsonObject.getString(TYPE_FIELD);
if (jsonObject.has(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 Long getId() {
return id;
}
public Boolean isGroupChat() {
return GROUPCHATTYPE.equals(type);
}
public Boolean isChannelChat() {
return CHANNELCHATTYPE.equals(type);
}
public Boolean isUserChat() {
return USERCHATTYPE.equals(type);
}
public Boolean isSuperGroupChat() {
return SUPERGROUPCHATTYPE.equals(type);
}
public String getTitle() {
return title;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getUserName() {
return userName;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(ID_FIELD, id);
gen.writeStringField(TYPE_FIELD, type);
if (isUserChat()) {
if (firstName != null) {
gen.writeStringField(FIRSTNAME_FIELD, firstName);
}
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
} else {
if (title != null) {
gen.writeStringField(TITLE_FIELD, title);
}
}
if (!isGroupChat() && userName != null) {
gen.writeStringField(USERNAME_FIELD, userName);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,66 +0,0 @@
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 = "result_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);
}
}

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

@ -1,68 +0,0 @@
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 phone contact.
* @date 20 of June of 2015
*/
public class Contact implements BotApiObject {
public static final String PHONENUMBER_FIELD = "phone_number";
@JsonProperty(PHONENUMBER_FIELD)
private String phoneNumber; ///< Contact's phone number
public static final String FIRSTNAME_FIELD = "first_name";
@JsonProperty(FIRSTNAME_FIELD)
private String firstName; ///< Contact's first name
public static final String LASTNAME_FIELD = "last_name";
@JsonProperty(LASTNAME_FIELD)
private String lastName; ///< Optional. Contact's last name
public static final String USERID_FIELD = "user_id";
@JsonProperty(USERID_FIELD)
private Integer userID; ///< Optional. Contact's user identifier in Telegram
public Contact() {
super();
}
public Contact(JSONObject jsonObject) {
super();
this.phoneNumber = jsonObject.getString(PHONENUMBER_FIELD);
this.firstName = jsonObject.getString(FIRSTNAME_FIELD);
if (jsonObject.has(LASTNAME_FIELD)) {
this.lastName = jsonObject.getString(LASTNAME_FIELD);
}
if (jsonObject.has(USERID_FIELD)) {
this.userID = jsonObject.getInt(USERID_FIELD);
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,119 +0,0 @@
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 general file (as opposed to photos and audio files).
* Telegram users can send files of any type of up to 1.5 GB in size.
* @date 20 of June of 2015
*/
public class Document implements BotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
public static final String THUMB_FIELD = "thumb";
@JsonProperty(THUMB_FIELD)
private PhotoSize thumb; ///< Document thumbnail as defined by sender
public static final String FILENAME_FIELD = "file_name";
@JsonProperty(FILENAME_FIELD)
private String fileName; ///< Optional. Original filename as defined by sender
public static final String MIMETYPE_FIELD = "mime_type";
@JsonProperty(MIMETYPE_FIELD)
private String mimeType; ///< Optional. Mime type of a file as defined by sender
public static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public Document() {
super();
}
public Document(JSONObject jsonObject) {
this.fileId = jsonObject.getString(FILEID_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(FILENAME_FIELD)) {
this.fileName = jsonObject.getString(FILENAME_FIELD);
}
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public PhotoSize getThumb() {
return thumb;
}
public void setThumb(PhotoSize thumb) {
this.thumb = thumb;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,86 +0,0 @@
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 file ready to be downloaded
* @date 24 of June of 2015
*/
public class File implements BotApiObject {
public static final String FILE_ID = "file_id";
@JsonProperty(FILE_ID)
private String fileId; ///< Unique identifier for this file
public static final String FILE_SIZE_FIELD = "file_size";
@JsonProperty(FILE_SIZE_FIELD)
private Integer fileSize; ///< Optional. File size, if known
public static final String FILE_PATH_FIELD = "first_name";
@JsonProperty(FILE_PATH_FIELD)
private String filePath; ///< Optional. File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file.
public File() {
super();
}
public File(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILE_ID);
if (jsonObject.has(FILE_SIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILE_SIZE_FIELD);
}
if (jsonObject.has(FILE_PATH_FIELD)) {
this.filePath = jsonObject.getString(FILE_PATH_FIELD);
}
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,94 +0,0 @@
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 Upon receiving a message with this object, Telegram clients will display a reply interface to the user
* (act as if the user has selected the bots message and tapped Reply').
* This can be extremely useful if you want to create user-friendly step-by-step
* interfaces without having to sacrifice privacy mode.
* @date 22 of June of 2015
*/
public class ForceReplyKeyboard implements ReplyKeyboard {
public static final String FORCEREPLY_FIELD = "force_reply";
/**
* Shows reply interface to the user, as if they manually selected the bots message and tapped Reply'
*/
@JsonProperty(FORCEREPLY_FIELD)
private Boolean forceReply;
public static final String SELECTIVE_FIELD = "selective";
/**
* Use this parameter if you want to force reply from specific users only.
* Targets:
* 1) users that are @mentioned in the text of the Message object;
* 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
*/
@JsonProperty(SELECTIVE_FIELD)
private Boolean selective;
public ForceReplyKeyboard() {
super();
this.forceReply = true;
}
public ForceReplyKeyboard(JSONObject jsonObject) {
super();
if (jsonObject.has(FORCEREPLY_FIELD)) {
this.forceReply = jsonObject.getBoolean(FORCEREPLY_FIELD);
}
if (jsonObject.has(SELECTIVE_FIELD)) {
this.selective = jsonObject.getBoolean(SELECTIVE_FIELD);
}
}
public Boolean getForceReply() {
return forceReply;
}
public void setForceReply(Boolean forceReply) {
this.forceReply = forceReply;
}
public Boolean getSelective() {
return selective;
}
public void setSelective(Boolean selective) {
this.selective = selective;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FORCEREPLY_FIELD, this.forceReply);
if (this.selective != null) {
jsonObject.put(SELECTIVE_FIELD, this.selective);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeBooleanField(FORCEREPLY_FIELD, forceReply);
gen.writeBooleanField(SELECTIVE_FIELD, selective);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,76 +0,0 @@
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

@ -1,13 +0,0 @@
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

@ -1,233 +0,0 @@
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

@ -1,213 +0,0 @@
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

@ -1,214 +0,0 @@
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

@ -1,249 +0,0 @@
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

@ -1,245 +0,0 @@
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);
}
}

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

@ -1,66 +0,0 @@
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 point on the map.
* @date 20 of June of 2015
*/
public class Location implements BotApiObject {
public static final String LONGITUDE_FIELD = "longitude";
@JsonProperty(LONGITUDE_FIELD)
private Double longitude; ///< Longitude as defined by sender
public static final String LATITUDE_FIELD = "latitude";
@JsonProperty(LATITUDE_FIELD)
private Double latitude; ///< Latitude as defined by sender
public Location() {
super();
}
public Location(JSONObject jsonObject) {
super();
this.longitude = jsonObject.getDouble(LONGITUDE_FIELD);
this.latitude = jsonObject.getDouble(LATITUDE_FIELD);
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(LONGITUDE_FIELD, longitude);
gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,528 +0,0 @@
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.JSONArray;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a message.
* @date 20 of June of 2015
*/
public class Message implements BotApiObject {
public static final String MESSAGEID_FIELD = "message_id";
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId; ///< Integer Unique message identifier
public static final String FROM_FIELD = "from";
@JsonProperty(FROM_FIELD)
private User from; ///< Optional. Sender, can be empty for messages sent to channels
public static final String DATE_FIELD = "date";
@JsonProperty(DATE_FIELD)
private Integer date; ///< Date the message was sent in Unix time
public static final String CHAT_FIELD = "chat";
@JsonProperty(CHAT_FIELD)
private Chat chat; ///< Conversation the message belongs to
public static final String FORWARDFROM_FIELD = "forward_from";
@JsonProperty(FORWARDFROM_FIELD)
private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message
public static final String FORWARDDATE_FIELD = "forward_date";
@JsonProperty(FORWARDDATE_FIELD)
private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent
public static final String TEXT_FIELD = "text";
@JsonProperty(TEXT_FIELD)
private String text; ///< Optional. For text messages, the actual UTF-8 text of the message
public static final String AUDIO_FIELD = "audio";
@JsonProperty(AUDIO_FIELD)
private Audio audio; ///< Optional. Message is an audio file, information about the file
public static final String DOCUMENT_FIELD = "document";
@JsonProperty(DOCUMENT_FIELD)
private Document document; ///< Optional. Message is a general file, information about the file
public static final String PHOTO_FIELD = "photo";
@JsonProperty(PHOTO_FIELD)
private List<PhotoSize> photo; ///< Optional. Message is a photo, available sizes of the photo
public static final String STICKER_FIELD = "sticker";
@JsonProperty(STICKER_FIELD)
private Sticker sticker; ///< Optional. Message is a sticker, information about the sticker
public static final String VIDEO_FIELD = "video";
@JsonProperty(VIDEO_FIELD)
private Video video; ///< Optional. Message is a video, information about the video
public static final String CONTACT_FIELD = "contact";
@JsonProperty(CONTACT_FIELD)
private Contact contact; ///< Optional. Message is a shared contact, information about the contact
public static final String LOCATION_FIELD = "location";
@JsonProperty(LOCATION_FIELD)
private Location location; ///< Optional. Message is a shared location, information about the location
public static final String NEWCHATPARTICIPANT_FIELD = "new_chat_participant";
@JsonProperty(NEWCHATPARTICIPANT_FIELD)
private User newChatParticipant; ///< Optional. A new member was added to the group, information about them (this member may be bot itself)
public static final String LEFTCHATPARTICIPANT_FIELD = "left_chat_participant";
@JsonProperty(LEFTCHATPARTICIPANT_FIELD)
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";
@JsonProperty(NEWCHATTITLE_FIELD)
private String newChatTitle; ///< Optional. A chat title was changed to this value
public static final String NEWCHATPHOTO_FIELD = "new_chat_photo";
@JsonProperty(NEWCHATPHOTO_FIELD)
private List<PhotoSize> newChatPhoto; ///< Optional. A chat photo was change to this value
public static final String DELETECHATPHOTO_FIELD = "delete_chat_photo";
@JsonProperty(DELETECHATPHOTO_FIELD)
private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted
public static final String GROUPCHATCREATED_FIELD = "group_chat_created";
@JsonProperty(GROUPCHATCREATED_FIELD)
private Boolean groupchatCreated; ///< Optional. Informs that the group has been created
public static final String REPLYTOMESSAGE_FIELD = "reply_to_message";
@JsonProperty(REPLYTOMESSAGE_FIELD)
private Message replyToMessage;
public static final String VOICE_FIELD = "voice";
@JsonProperty(VOICE_FIELD)
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() {
super();
}
public Message(JSONObject jsonObject) {
super();
this.messageId = jsonObject.getInt(MESSAGEID_FIELD);
if (jsonObject.has(FROM_FIELD)) {
this.from = new User(jsonObject.getJSONObject(FROM_FIELD));
}
this.date = jsonObject.getInt(DATE_FIELD);
this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD));
if (jsonObject.has(FORWARDFROM_FIELD)) {
this.forwardFrom = new User(jsonObject.getJSONObject(FORWARDFROM_FIELD));
}
if (jsonObject.has(FORWARDDATE_FIELD)) {
this.forwardDate = jsonObject.getInt(FORWARDDATE_FIELD);
}
if (jsonObject.has(TEXT_FIELD)) {
this.text = jsonObject.getString(TEXT_FIELD);
}
if (jsonObject.has(AUDIO_FIELD)) {
this.audio = new Audio(jsonObject.getJSONObject(AUDIO_FIELD));
}
if (jsonObject.has(DOCUMENT_FIELD)) {
this.document = new Document(jsonObject.getJSONObject(DOCUMENT_FIELD));
}
if (jsonObject.has(PHOTO_FIELD)) {
this.photo = new ArrayList<>();
JSONArray photos = jsonObject.getJSONArray(PHOTO_FIELD);
for (int i = 0; i < photos.length(); i++) {
this.photo.add(new PhotoSize(photos.getJSONObject(i)));
}
}
if (jsonObject.has(STICKER_FIELD)) {
this.sticker = new Sticker(jsonObject.getJSONObject(STICKER_FIELD));
}
if (jsonObject.has(VIDEO_FIELD)) {
this.video = new Video(jsonObject.getJSONObject(VIDEO_FIELD));
}
if (jsonObject.has(CONTACT_FIELD)) {
this.contact = new Contact(jsonObject.getJSONObject(CONTACT_FIELD));
}
if (jsonObject.has(LOCATION_FIELD)) {
this.location = new Location(jsonObject.getJSONObject(LOCATION_FIELD));
}
if (jsonObject.has(VOICE_FIELD)) {
this.voice = new Voice(jsonObject.getJSONObject(VOICE_FIELD));
}
if (jsonObject.has(NEWCHATPARTICIPANT_FIELD)) {
this.newChatParticipant = new User(jsonObject.getJSONObject(NEWCHATPARTICIPANT_FIELD));
}
if (jsonObject.has(LEFTCHATPARTICIPANT_FIELD)) {
this.leftChatParticipant = new User(jsonObject.getJSONObject(LEFTCHATPARTICIPANT_FIELD));
}
if (jsonObject.has(REPLYTOMESSAGE_FIELD)) {
this.replyToMessage = new Message(jsonObject.getJSONObject(REPLYTOMESSAGE_FIELD));
}
if (jsonObject.has(NEWCHATTITLE_FIELD)) {
this.newChatTitle = jsonObject.getString(NEWCHATTITLE_FIELD);
}
if (jsonObject.has(NEWCHATPHOTO_FIELD)) {
JSONArray photoArray = jsonObject.getJSONArray(NEWCHATPHOTO_FIELD);
this.newChatPhoto = new ArrayList<>();
for (int i = 0; i < photoArray.length(); i++) {
this.newChatPhoto.add(new PhotoSize(photoArray.getJSONObject(i)));
}
}
if (jsonObject.has(DELETECHATPHOTO_FIELD)) {
this.deleteChatPhoto = true;
}
if (jsonObject.has(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);
}
}
public Integer getMessageId() {
return messageId;
}
public void setMessageId(Integer messageId) {
this.messageId = messageId;
}
public User getFrom() {
return from;
}
public void setFrom(User from) {
this.from = from;
}
public Integer getDate() {
return date;
}
public void setDate(Integer date) {
this.date = date;
}
public boolean isGroupMessage() {
return chat.isGroupChat();
}
public boolean isUserMessage() {
return chat.isUserChat();
}
public boolean isChannelMessage() {
return chat.isChannelChat();
}
public boolean isSuperGroupMessage() {
return chat.isSuperGroupChat();
}
public Long getChatId() {
return chat.getId();
}
public Chat getChat() {
return chat;
}
public void setChat(Chat chat) {
this.chat = chat;
}
public User getForwardFrom() {
return forwardFrom;
}
public void setForwardFrom(User forwardFrom) {
this.forwardFrom = forwardFrom;
}
public Integer getForwardDate() {
return forwardDate;
}
public void setForwardDate(Integer forwardDate) {
this.forwardDate = forwardDate;
}
public boolean hasText() {
return text != null && !text.isEmpty();
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Audio getAudio() {
return audio;
}
public void setAudio(Audio audio) {
this.audio = audio;
}
public boolean hasDocument() {
return this.document != null;
}
public Document getDocument() {
return document;
}
public void setDocument(Document document) {
this.document = document;
}
public List<PhotoSize> getPhoto() {
return photo;
}
public void setPhoto(List<PhotoSize> photo) {
this.photo = photo;
}
public Sticker getSticker() {
return sticker;
}
public void setSticker(Sticker sticker) {
this.sticker = sticker;
}
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public User getNewChatParticipant() {
return newChatParticipant;
}
public void setNewChatParticipant(User newChatParticipant) {
this.newChatParticipant = newChatParticipant;
}
public User getLeftChatParticipant() {
return leftChatParticipant;
}
public void setLeftChatParticipant(User leftChatParticipant) {
this.leftChatParticipant = leftChatParticipant;
}
public String getNewChatTitle() {
return newChatTitle;
}
public void setNewChatTitle(String newChatTitle) {
this.newChatTitle = newChatTitle;
}
public List<PhotoSize> getNewChatPhoto() {
return newChatPhoto;
}
public void setNewChatPhoto(List<PhotoSize> newChatPhoto) {
this.newChatPhoto = newChatPhoto;
}
public Boolean getDeleteChatPhoto() {
return deleteChatPhoto;
}
public void setDeleteChatPhoto(Boolean deleteChatPhoto) {
this.deleteChatPhoto = deleteChatPhoto;
}
public Boolean getGroupchatCreated() {
return groupchatCreated;
}
public void setGroupchatCreated(Boolean groupchatCreated) {
this.groupchatCreated = groupchatCreated;
}
public boolean hasReplayMessage() {
return replyToMessage != null;
}
public Message getReplyToMessage() {
return replyToMessage;
}
public void setReplyToMessage(Message replyToMessage) {
this.replyToMessage = replyToMessage;
}
public boolean isReply() {
return this.replyToMessage != null;
}
public boolean hasLocation() {
return location != null;
}
public Voice getVoice() {
return voice;
}
public void setVoice(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
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(MESSAGEID_FIELD, messageId);
gen.writeObjectField(FROM_FIELD, from);
gen.writeNumberField(DATE_FIELD, date);
gen.writeObjectField(CHAT_FIELD, chat);
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) {
gen.writeObjectField(LOCATION_FIELD, location);
}
if (voice != null) {
gen.writeObjectField(VOICE_FIELD, voice);
}
if (newChatParticipant != null) {
gen.writeObjectField(NEWCHATPARTICIPANT_FIELD, newChatParticipant);
}
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);
}
if (superGroupCreated != null) {
gen.writeBooleanField(SUPERGROUPCREATED_FIELD, superGroupCreated);
}
if (channelChatCreated != null) {
gen.writeBooleanField(CHANNELCHATCREATED_FIELD, channelChatCreated);
}
if (migrateToChatId != null) {
gen.writeNumberField(MIGRATETOCHAT_FIELD, migrateToChatId);
}
if (migrateFromChatId != null) {
gen.writeNumberField(MIGRATEFROMCHAT_FIELD, migrateFromChatId);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,96 +0,0 @@
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 one size of a photo or a file / sticker thumbnail.
* @date 20 of June of 2015
*/
public class PhotoSize implements BotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
public static final String WIDTH_FIELD = "width";
@JsonProperty(WIDTH_FIELD)
private Integer width; ///< Photo width
public static final String HEIGHT_FIELD = "height";
@JsonProperty(HEIGHT_FIELD)
private Integer height; ///< Photo height
public static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public PhotoSize() {
super();
}
public PhotoSize(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,13 +0,0 @@
package org.telegram.api.objects;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Reply keyboard abstract type
* @date 20 of June of 2015
*/
public interface ReplyKeyboard extends BotApiObject, IToJson {
}

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

@ -1,88 +0,0 @@
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 Upon receiving a message with this object,
* Telegram clients will hide the current custom keyboard and display the default letter-keyboard.
* By default, custom keyboards are displayed until a new keyboard is sent by a bot.
* An exception is made for one-time keyboards that are hidden immediately after the user presses a button
* (@see ReplyKeyboardMarkup).
* @date 20 of June of 2015
*/
public class ReplyKeyboardHide implements ReplyKeyboard {
public static final String HIDEKEYBOARD_FIELD = "hide_keyboard";
@JsonProperty(HIDEKEYBOARD_FIELD)
private Boolean hideKeyboard; ///< Requests clients to hide the custom keyboard
public static final String SELECTIVE_FIELD = "selective";
/**
* Optional. Use this parameter if you want to show the keyboard to specific users only.
* Targets:
* 1) users that are @mentioned in the text of the Message object;
* 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
*/
@JsonProperty(SELECTIVE_FIELD)
private Boolean selective;
public ReplyKeyboardHide() {
super();
this.selective = true;
}
public ReplyKeyboardHide(JSONObject jsonObject) {
super();
if (jsonObject.has(HIDEKEYBOARD_FIELD)) {
this.hideKeyboard = jsonObject.getBoolean(HIDEKEYBOARD_FIELD);
}
if (jsonObject.has(SELECTIVE_FIELD)) {
this.selective = jsonObject.getBoolean(SELECTIVE_FIELD);
}
}
public Boolean getHideKeyboard() {
return hideKeyboard;
}
public void setHideKeyboard(Boolean hideKeyboard) {
this.hideKeyboard = hideKeyboard;
}
public Boolean getSelective() {
return selective;
}
public void setSelective(Boolean selective) {
this.selective = selective;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(HIDEKEYBOARD_FIELD, this.hideKeyboard);
jsonObject.put(SELECTIVE_FIELD, this.selective);
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeBooleanField(HIDEKEYBOARD_FIELD, hideKeyboard);
gen.writeBooleanField(SELECTIVE_FIELD, selective);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,156 +0,0 @@
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.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a custom keyboard with reply options.
* @date 20 of June of 2015
*/
public class ReplyKeyboardMarkup implements ReplyKeyboard {
public static final String KEYBOARD_FIELD = "keyboard";
@JsonProperty(KEYBOARD_FIELD)
private List<List<String>> keyboard; ///< Array of button rows, each represented by an Array of Strings
public static final String RESIZEKEYBOARD_FIELD = "resize_keyboard";
@JsonProperty(RESIZEKEYBOARD_FIELD)
private Boolean resizeKeyboard; ///< Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false.
public static final String ONETIMEKEYBOARD_FIELD = "one_time_keyboard";
@JsonProperty(ONETIMEKEYBOARD_FIELD)
private Boolean oneTimeKeyboad; ///< Optional. Requests clients to hide the keyboard as soon as it's been used. Defaults to false.
public static final String SELECTIVE_FIELD = "selective";
/**
* Optional. Use this parameter if you want to show the keyboard to specific users only.
* Targets:
* 1) users that are @mentioned in the text of the Message object;
* 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
*/
private Boolean selective;
public ReplyKeyboardMarkup() {
super();
keyboard = new ArrayList<List<String>>();
}
public ReplyKeyboardMarkup(JSONObject jsonObject) {
super();
this.keyboard = new ArrayList<List<String>>();
JSONArray keyboard = jsonObject.getJSONArray(KEYBOARD_FIELD);
for (int i=0; i< keyboard.length(); i++) {
JSONArray keyboardRow = keyboard.getJSONArray(i);
List<String> row = new ArrayList<String>();
for (int j=0; j < keyboardRow.length(); j++) {
row.add(keyboardRow.getString(j));
}
this.keyboard.add(row);
}
if (jsonObject.has(RESIZEKEYBOARD_FIELD)) {
this.resizeKeyboard = jsonObject.getBoolean(RESIZEKEYBOARD_FIELD);
}
if (jsonObject.has(ONETIMEKEYBOARD_FIELD)) {
this.oneTimeKeyboad = jsonObject.getBoolean(ONETIMEKEYBOARD_FIELD);
}
if (jsonObject.has(SELECTIVE_FIELD)) {
this.selective = jsonObject.getBoolean(SELECTIVE_FIELD);
}
}
public List<List<String>> getKeyboard() {
return keyboard;
}
public void setKeyboard(List<List<String>> keyboard) {
this.keyboard = keyboard;
}
public Boolean getResizeKeyboard() {
return resizeKeyboard;
}
public void setResizeKeyboard(Boolean resizeKeyboard) {
this.resizeKeyboard = resizeKeyboard;
}
public Boolean getOneTimeKeyboad() {
return oneTimeKeyboad;
}
public void setOneTimeKeyboad(Boolean oneTimeKeyboad) {
this.oneTimeKeyboad = oneTimeKeyboad;
}
public Boolean getSelective() {
return selective;
}
public void setSelective(Boolean selective) {
this.selective = selective;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
JSONArray jsonkeyboard = new JSONArray();
for (List<String> innerRow : this.keyboard) {
JSONArray innerJSONKeyboard = new JSONArray();
for (String element: innerRow) {
innerJSONKeyboard.put(element);
}
jsonkeyboard.put(innerJSONKeyboard);
}
jsonObject.put(ReplyKeyboardMarkup.KEYBOARD_FIELD, jsonkeyboard);
if (this.oneTimeKeyboad != null) {
jsonObject.put(ReplyKeyboardMarkup.ONETIMEKEYBOARD_FIELD, this.oneTimeKeyboad);
}
if (this.resizeKeyboard != null) {
jsonObject.put(ReplyKeyboardMarkup.RESIZEKEYBOARD_FIELD, this.resizeKeyboard);
}
if (this.selective != null) {
jsonObject.put(ReplyKeyboardMarkup.SELECTIVE_FIELD, this.selective);
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,73 +0,0 @@
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 sticker.
* @date 20 of June of 2015
*/
public class Sticker implements BotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
public static final String WIDTH_FIELD = "width";
@JsonProperty(WIDTH_FIELD)
private Integer width; ///< Sticker width
public static final String HEIGHT_FIELD = "height";
@JsonProperty(HEIGHT_FIELD)
private Integer height; ///< Sticker height
public static final String THUMB_FIELD = "thumb";
@JsonProperty(THUMB_FIELD)
private PhotoSize thumb; ///< Optional. Sticker thumbnail in .webp or .jpg format
public static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public Sticker() {
super();
}
public Sticker(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,104 +0,0 @@
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 update.
* Only one of the optional parameters can be present in any given update.
* @date 20 of June of 2015
*/
public class Update implements BotApiObject {
public static final String UPDATEID_FIELD = "update_id";
@JsonProperty(UPDATEID_FIELD)
private Integer updateId;
public static final String MESSAGE_FIELD = "message";
@JsonProperty(MESSAGE_FIELD)
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() {
super();
}
public Update(JSONObject jsonObject) {
super();
this.updateId = jsonObject.getInt(UPDATEID_FIELD);
if (jsonObject.has(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() {
return updateId;
}
public Message getMessage() {
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
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(UPDATEID_FIELD, updateId);
if (message != null) {
gen.writeObjectField(MESSAGE_FIELD, message);
}
if (inlineQuery != null) {
gen.writeObjectField(INLINEQUERY_FIELD, inlineQuery);
}
if (chosenInlineQuery != null) {
gen.writeObjectField(CHOSENINLINEQUERY_FIELD, chosenInlineQuery);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,84 +0,0 @@
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 Telegram user or bot.
* @date 20 of June of 2015
*/
public class User implements BotApiObject {
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private Integer id; ///< Unique identifier for this user or bot
public static final String FIRSTNAME_FIELD = "first_name";
@JsonProperty(FIRSTNAME_FIELD)
private String firstName; ///< User‘s or bot’s first name
public static final String LASTNAME_FIELD = "last_name";
@JsonProperty(LASTNAME_FIELD)
private String lastName; ///< Optional. User‘s or bot’s last name
public static final String USERNAME_FIELD = "username";
@JsonProperty(USERNAME_FIELD)
private String userName; ///< Optional. User‘s or bot’s username
public User() {
super();
}
public User(JSONObject jsonObject) {
super();
this.id = jsonObject.getInt(ID_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() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getUserName() {
return userName;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,90 +0,0 @@
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.JSONArray;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represent a user's profile pictures.
* @date 22 of June of 2015
*/
public class UserProfilePhotos implements BotApiObject {
public static final String TOTALCOUNT_FIELD = "total_count";
@JsonProperty(TOTALCOUNT_FIELD)
private Integer totalCount; ///< Total number of profile pictures the target user has
public static final String PHOTOS_FIELD = "photos";
@JsonProperty(PHOTOS_FIELD)
private List<List<PhotoSize>> photos; ///< Requested profile pictures (in up to 4 sizes each)
public UserProfilePhotos() {
super();
}
public UserProfilePhotos(JSONObject jsonObject) {
super();
this.totalCount = jsonObject.getInt(TOTALCOUNT_FIELD);
if (totalCount > 0) {
this.photos = new ArrayList<>();
JSONArray photos = jsonObject.getJSONArray(PHOTOS_FIELD);
for (int i = 0; i < photos.length(); i++) {
JSONArray innerArray = photos.getJSONArray(i);
List<PhotoSize> innerPhotos = new ArrayList<>();
for (int j = 0; j < innerArray.length(); j++) {
innerPhotos.add(new PhotoSize(innerArray.getJSONObject(j)));
}
this.photos.add(innerPhotos);
}
}
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public List<List<PhotoSize>> getPhotos() {
return photos;
}
public void setPhotos(List<List<PhotoSize>> photos) {
this.photos = photos;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,142 +0,0 @@
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 video file.
* @date 20 of June of 2015
*/
public class Video implements BotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
public static final String WIDTH_FIELD = "width";
@JsonProperty(WIDTH_FIELD)
private Integer width; ///< Video width as defined by sender
public static final String HEIGHT_FIELD = "height";
@JsonProperty(HEIGHT_FIELD)
private Integer height; ///< Video height as defined by sender
public static final String DURATION_FIELD = "duration";
@JsonProperty(DURATION_FIELD)
private Integer duration; ///< Duration of the video in seconds as defined by sender
public static final String THUMB_FIELD = "thumb";
@JsonProperty(THUMB_FIELD)
private PhotoSize thumb; ///< Video thumbnail
public static final String MIMETYPE_FIELD = "mime_type";
@JsonProperty(MIMETYPE_FIELD)
private String mimeType; ///< Optional. Mime type of a file as defined by sender
public static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public Video() {
super();
}
public Video(JSONObject jsonObject) {
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
this.duration = jsonObject.getInt(DURATION_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public PhotoSize getThumb() {
return thumb;
}
public void setThumb(PhotoSize thumb) {
this.thumb = thumb;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -1,99 +0,0 @@
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 voice note
* @date 16 of July of 2015
*/
public class Voice implements BotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
public static final String DURATION_FIELD = "duration";
@JsonProperty(DURATION_FIELD)
private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender
public static final String MIMETYPE_FIELD = "mime_type";
@JsonProperty(MIMETYPE_FIELD)
private String mimeType; ///< Optional. MIME type of the file as defined by sender
public static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public Voice() {
super();
}
public Voice(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.duration = jsonObject.getInt(DURATION_FIELD);
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
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();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

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

@ -94,7 +94,7 @@ public class RaeService {
Elements links = list.getElementsByTag("a"); Elements links = list.getElementsByTag("a");
if (!links.isEmpty()) { if (!links.isEmpty()) {
for (Element link : links) { for (Element link : links) {
List<RaeResult> partialResults = fetchWord(link.attributes().get("href"), link.text()); List<RaeResult> partialResults = fetchWord(URLEncoder.encode(link.attributes().get("href"), "UTF-8"), link.text());
if (!partialResults.isEmpty()) { if (!partialResults.isEmpty()) {
results.addAll(partialResults); results.addAll(partialResults);
} }

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

@ -8,7 +8,7 @@ import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.api.methods.SendDocument; import org.telegram.telegrambots.api.methods.SendDocument;
import java.io.*; import java.io.*;

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

@ -1,18 +1,16 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.BotConfig; 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.*;
import org.telegram.services.BotLogger; import org.telegram.services.BotLogger;
import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.telegrambots.TelegramApiException;
import org.telegram.updatesreceivers.Webhook; import org.telegram.telegrambots.api.methods.SendMessage;
import org.telegram.telegrambots.api.objects.ForceReplyKeyboard;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.ReplyKeyboardMarkup;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
@ -22,11 +20,8 @@ import java.util.concurrent.ConcurrentHashMap;
* This is a use case that will send a message to a channel if it is added as an admin to it. * 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 * @date 24 of June of 2015
*/ */
public class ChannelHandlers implements UpdatesCallback { public class ChannelHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "CHANNELHANDLERS"; 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 int WAITINGCHANNEL = 1;
@ -39,27 +34,12 @@ public class ChannelHandlers implements UpdatesCallback {
private final ConcurrentHashMap<Integer, Integer> userState = new ConcurrentHashMap<>(); 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 @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
Message message = update.getMessage(); Message message = update.getMessage();
if (message != null && message.hasText()) { if (message != null && message.hasText()) {
try { try {
BotApiMethod botApiMethod = handleIncomingMessage(message); handleIncomingMessage(message);
if (botApiMethod != null) {
SenderHelper.SendApiMethod(botApiMethod, TOKEN);
}
} catch (InvalidObjectException e) { } catch (InvalidObjectException e) {
BotLogger.severe(LOGTAG, e); BotLogger.severe(LOGTAG, e);
} }
@ -67,47 +47,52 @@ public class ChannelHandlers implements UpdatesCallback {
} }
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public String getBotToken() {
throw new NoSuchMethodError(); return BotConfig.TOKENCHANNEL;
}
@Override
public String getBotUsername() {
return BotConfig.USERNAMECHANNEL;
} }
// region Incoming messages handlers // region Incoming messages handlers
private BotApiMethod handleIncomingMessage(Message message) throws InvalidObjectException { private void handleIncomingMessage(Message message) throws InvalidObjectException {
int state = userState.getOrDefault(message.getFrom().getId(), 0); int state = userState.getOrDefault(message.getFrom().getId(), 0);
BotApiMethod botApiMethod;
switch(state) { switch(state) {
case WAITINGCHANNEL: case WAITINGCHANNEL:
botApiMethod = onWaitingChannelMessage(message); onWaitingChannelMessage(message);
break; break;
default: default:
botApiMethod = sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null); sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null);
userState.put(message.getFrom().getId(), WAITINGCHANNEL); userState.put(message.getFrom().getId(), WAITINGCHANNEL);
break; break;
} }
return botApiMethod;
} }
private BotApiMethod onWaitingChannelMessage(Message message) throws InvalidObjectException { private void onWaitingChannelMessage(Message message) throws InvalidObjectException {
BotApiMethod sendMessage = null; try {
if (message.getText().equals(CANCEL_COMMAND)) { if (message.getText().equals(CANCEL_COMMAND)) {
userState.remove(message.getFrom().getId()); userState.remove(message.getFrom().getId());
sendMessage = sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null); sendHelpMessage(message.getChatId().toString(), message.getMessageId(), null);
} else { } else {
if (message.getText().startsWith("@") && !message.getText().trim().contains(" ")) { if (message.getText().startsWith("@") && !message.getText().trim().contains(" ")) {
sendBuiltMessage(getMessageToChannelSent(message)); sendMessage(getMessageToChannelSent(message));
sendMessageToChannel(message.getText(), message); sendMessageToChannel(message.getText(), message);
userState.remove(message.getFrom().getId()); userState.remove(message.getFrom().getId());
} else { } else {
sendMessage = getWrongUsernameMessage(message); sendMessage(getWrongUsernameMessage(message));
} }
} }
} catch (TelegramApiException e) {
return sendMessage; BotLogger.error(LOGTAG, e);
}
} }
private static void sendMessageToChannel(String username, Message message) { private void sendMessageToChannel(String username, Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(username.trim()); sendMessage.setChatId(username.trim());
@ -116,13 +101,13 @@ public class ChannelHandlers implements UpdatesCallback {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
try { try {
sendBuiltMessage(sendMessage); sendMessage(sendMessage);
} catch (InvalidObjectException e) { } catch (TelegramApiException e) {
sendErrorMessage(message, e.getMessage()); sendErrorMessage(message, e.getMessage());
} }
} }
private static void sendErrorMessage(Message message, String errorText) { private void sendErrorMessage(Message message, String errorText) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString()); sendMessage.setChatId(message.getChatId().toString());
@ -132,13 +117,13 @@ public class ChannelHandlers implements UpdatesCallback {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
try { try {
sendBuiltMessage(sendMessage); sendMessage(sendMessage);
} catch (InvalidObjectException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); BotLogger.error(LOGTAG, e);
} }
} }
private static BotApiMethod getWrongUsernameMessage(Message message) { private static SendMessage getWrongUsernameMessage(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString()); sendMessage.setChatId(message.getChatId().toString());
@ -164,7 +149,7 @@ public class ChannelHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup) { private void sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(chatId);
@ -174,10 +159,10 @@ public class ChannelHandlers implements UpdatesCallback {
} }
sendMessage.setText(HELP_TEXT); sendMessage.setText(HELP_TEXT);
return sendMessage; try {
sendMessage(sendMessage);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
} }
private static void sendBuiltMessage(SendMessage sendMessage) throws InvalidObjectException {
SenderHelper.SendApiMethod(sendMessage, TOKEN);
} }
} }

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

@ -1,16 +1,18 @@
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.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendMessage;
import org.telegram.services.BotLogger; 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.telegrambots.TelegramApiException;
import org.telegram.updatesreceivers.Webhook; import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.SendMessage;
import org.telegram.telegrambots.api.objects.*;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.updateshandlers.SentCallback;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
@ -25,24 +27,17 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* @brief Handler for updates to Directions Bot * @brief Handler for updates to Directions Bot
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class DirectionsHandlers implements UpdatesCallback { public class DirectionsHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "DIRECTIONSHANDLERS"; private static final String LOGTAG = "DIRECTIONSHANDLERS";
private static final String TOKEN = BotConfig.TOKENDIRECTIONS;
private static final String BOTNAME = BotConfig.USERNAMEDIRECTIONS;
private static final boolean USEWEBHOOK = false;
private static final int WATING_ORIGIN_STATUS = 0; private static final int WATING_ORIGIN_STATUS = 0;
private static final int WATING_DESTINY_STATUS = 1; private static final int WATING_DESTINY_STATUS = 1;
private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>();
public DirectionsHandlers(Webhook webhook) {
if (USEWEBHOOK && BuildVars.useWebHook) { @Override
webhook.registerWebhook(this, BOTNAME); public String getBotToken() {
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN); return BotConfig.TOKENDIRECTIONS;
} else {
SenderHelper.SendWebhook("", TOKEN);
new UpdatesThread(TOKEN, this);
}
} }
@Override @Override
@ -55,12 +50,11 @@ public class DirectionsHandlers implements UpdatesCallback {
} }
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public String getBotUsername() {
// Webhook not supported in this example return BotConfig.USERNAMEDIRECTIONS;
return null;
} }
public void handleDirections(Update update) throws InvalidObjectException { private 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())) {
@ -92,7 +86,11 @@ public class DirectionsHandlers implements UpdatesCallback {
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().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }
} }
@ -110,22 +108,29 @@ public class DirectionsHandlers implements UpdatesCallback {
replyKeyboardHide.setSelective(true); replyKeyboardHide.setSelective(true);
sendMessageRequest.setReplayMarkup(replyKeyboardHide); sendMessageRequest.setReplayMarkup(replyKeyboardHide);
sendMessageRequest.setReplayToMessageId(message.getMessageId()); sendMessageRequest.setReplayToMessageId(message.getMessageId());
Message sentMessage = null;
for (String direction : directions) { for (String direction : directions) {
sendMessageRequest.setText(direction); sendMessageRequest.setText(direction);
SenderHelper.SendApiMethodAsync(sendMessageRequest, TOKEN, new SentCallback<Message>() { try {
sendMessageAsync(sendMessageRequest, new SentCallback<Message>() {
@Override @Override
public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) { public void onResult(BotApiMethod<Message> botApiMethod, JSONObject jsonObject) {
Message sentMessage = method.deserializeResponse(jsonObject); Message sentMessage = botApiMethod.deserializeResponse(jsonObject);
if (sentMessage != null) { if (sentMessage != null) {
DatabaseManager.getInstance().deleteUserForDirections(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForDirections(message.getFrom().getId());
} }
} }
@Override @Override
public void onError(BotApiMethod<Message> method, JSONObject jsonObject) { public void onError(BotApiMethod<Message> botApiMethod, JSONObject jsonObject) {
}
@Override
public void onException(BotApiMethod<Message> botApiMethod, Exception e) {
} }
}); });
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }
@ -139,7 +144,8 @@ public class DirectionsHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(forceReplyKeyboard); sendMessageRequest.setReplayMarkup(forceReplyKeyboard);
sendMessageRequest.setText(LocalisationService.getInstance().getString("sendDestination", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("sendDestination", language));
SenderHelper.SendApiMethodAsync(sendMessageRequest, TOKEN, new SentCallback<Message>() { try {
sendMessageAsync(sendMessageRequest, new SentCallback<Message>() {
@Override @Override
public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) { public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) {
Message sentMessage = method.deserializeResponse(jsonObject); Message sentMessage = method.deserializeResponse(jsonObject);
@ -150,9 +156,16 @@ public class DirectionsHandlers implements UpdatesCallback {
} }
@Override @Override
public void onError(BotApiMethod<Message> method, JSONObject jsonObject) { public void onError(BotApiMethod<Message> botApiMethod, JSONObject jsonObject) {
}
@Override
public void onException(BotApiMethod<Message> botApiMethod, Exception e) {
} }
}); });
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
@ -163,7 +176,11 @@ public class DirectionsHandlers implements UpdatesCallback {
Commands.startDirectionCommand); Commands.startDirectionCommand);
sendMessageRequest.setText(helpDirectionsFormated); sendMessageRequest.setText(helpDirectionsFormated);
sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onStartdirectionsCommand(Message message, String language) { private void onStartdirectionsCommand(Message message, String language) {
@ -175,7 +192,8 @@ public class DirectionsHandlers implements UpdatesCallback {
sendMessageRequest.setReplayMarkup(forceReplyKeyboard); sendMessageRequest.setReplayMarkup(forceReplyKeyboard);
sendMessageRequest.setText(LocalisationService.getInstance().getString("initDirections", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("initDirections", language));
SenderHelper.SendApiMethodAsync(sendMessageRequest, TOKEN, new SentCallback<Message>() { try {
sendMessageAsync(sendMessageRequest, new SentCallback<Message>() {
@Override @Override
public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) { public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) {
Message sentMessage = method.deserializeResponse(jsonObject); Message sentMessage = method.deserializeResponse(jsonObject);
@ -186,9 +204,16 @@ public class DirectionsHandlers implements UpdatesCallback {
} }
@Override @Override
public void onError(BotApiMethod<Message> method, JSONObject jsonObject) { public void onError(BotApiMethod<Message> botApiMethod, JSONObject jsonObject) {
}
@Override
public void onException(BotApiMethod<Message> botApiMethod, Exception e) {
} }
}); });
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
@ -209,8 +234,12 @@ public class DirectionsHandlers implements UpdatesCallback {
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkup.setSelective(true);
sendMessageRequest.setReplayMarkup(replyKeyboardMarkup); sendMessageRequest.setReplayMarkup(replyKeyboardMarkup);
sendMessageRequest.setText(LocalisationService.getInstance().getString("chooselanguage", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("chooselanguage", language));
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onLanguageSelected(Message message) throws InvalidObjectException { private void onLanguageSelected(Message message) throws InvalidObjectException {
@ -228,7 +257,11 @@ public class DirectionsHandlers implements UpdatesCallback {
replyKeyboardHide.setHideKeyboard(true); replyKeyboardHide.setHideKeyboard(true);
replyKeyboardHide.setSelective(true); replyKeyboardHide.setSelective(true);
sendMessageRequest.setReplayMarkup(replyKeyboardHide); sendMessageRequest.setReplayMarkup(replyKeyboardHide);
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
languageMessages.remove(message.getFrom().getId()); languageMessages.remove(message.getFrom().getId());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }

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

@ -1,22 +1,19 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.BuildVars;
import org.telegram.Commands; import org.telegram.Commands;
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.ReplyKeyboardHide;
import org.telegram.api.objects.ReplyKeyboardMarkup;
import org.telegram.api.objects.Update;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.services.BotLogger; import org.telegram.services.BotLogger;
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.telegrambots.TelegramApiException;
import org.telegram.updatesreceivers.Webhook; import org.telegram.telegrambots.api.methods.SendDocument;
import org.telegram.telegrambots.api.methods.SendMessage;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.ReplyKeyboardHide;
import org.telegram.telegrambots.api.objects.ReplyKeyboardMarkup;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,24 +29,16 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* This bot is an example for the use of sendMessage asynchronously * This bot is an example for the use of sendMessage asynchronously
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class FilesHandlers implements UpdatesCallback { public class FilesHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "FILESHANDLERS"; private static final String LOGTAG = "FILESHANDLERS";
private static final String TOKEN = BotConfig.TOKENFILES;
private static final String BOTNAME = BotConfig.USERNAMEFILES;
private static final boolean USEWEBHOOK = false;
private static final int INITIAL_UPLOAD_STATUS = 0; private static final int INITIAL_UPLOAD_STATUS = 0;
private static final int DELETE_UPLOADED_STATUS = 1; private static final int DELETE_UPLOADED_STATUS = 1;
private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>();
public FilesHandlers(Webhook webhook) { @Override
if (USEWEBHOOK && BuildVars.useWebHook) { public String getBotToken() {
webhook.registerWebhook(this, BOTNAME); return BotConfig.TOKENFILES;
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else {
SenderHelper.SendWebhook("", TOKEN);
new UpdatesThread(TOKEN, this);
}
} }
@Override @Override
@ -62,12 +51,11 @@ public class FilesHandlers implements UpdatesCallback {
} }
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public String getBotUsername() {
// Webhook not supported in this example return BotConfig.USERNAMEFILES;
return null;
} }
public void handleFileUpdate(Update update) throws InvalidObjectException { private 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())) {
@ -107,7 +95,11 @@ public class FilesHandlers implements UpdatesCallback {
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().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }
@ -128,7 +120,11 @@ public class FilesHandlers implements UpdatesCallback {
ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide(); ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
replyKeyboardHide.setHideKeyboard(true); replyKeyboardHide.setHideKeyboard(true);
sendMessageRequest.setReplayMarkup(replyKeyboardHide); sendMessageRequest.setReplayMarkup(replyKeyboardHide);
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onDeleteCommand(Message message, String language, String[] parts) throws InvalidObjectException { private void onDeleteCommand(Message message, String language, String[] parts) throws InvalidObjectException {
@ -160,7 +156,11 @@ public class FilesHandlers implements UpdatesCallback {
replyKeyboardMarkup.setKeyboard(commands); replyKeyboardMarkup.setKeyboard(commands);
} }
sendMessageRequest.setReplayMarkup(replyKeyboardMarkup); sendMessageRequest.setReplayMarkup(replyKeyboardMarkup);
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onDeleteCommandWithParameters(Message message, String language, String part) throws InvalidObjectException { private void onDeleteCommandWithParameters(Message message, String language, String part) throws InvalidObjectException {
@ -173,8 +173,13 @@ public class FilesHandlers implements UpdatesCallback {
sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("wrongFileId", language));
} }
sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onCancelCommand(Message message, String language) throws InvalidObjectException { private void onCancelCommand(Message message, String language) throws InvalidObjectException {
@ -182,7 +187,11 @@ public class FilesHandlers implements UpdatesCallback {
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().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onUploadCommand(Message message, String language) throws InvalidObjectException { private void onUploadCommand(Message message, String language) throws InvalidObjectException {
@ -190,7 +199,11 @@ public class FilesHandlers implements UpdatesCallback {
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().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void sendHelpMessage(Message message, String language) throws InvalidObjectException { private void sendHelpMessage(Message message, String language) throws InvalidObjectException {
@ -201,20 +214,28 @@ public class FilesHandlers implements UpdatesCallback {
Commands.listCommand); Commands.listCommand);
sendMessageRequest.setText(formatedString); sendMessageRequest.setText(formatedString);
sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onStartWithParameters(Message message, String language, String part) throws InvalidObjectException { private void onStartWithParameters(Message message, String language, String part) throws InvalidObjectException {
try {
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().toString()); sendDocumentRequest.setChatId(message.getChatId().toString());
SenderHelper.SendDocument(sendDocumentRequest, TOKEN); sendDocument(sendDocumentRequest);
} 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().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); sendMessage(sendMessageRequest);
}
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
} }
} }
@ -235,8 +256,12 @@ public class FilesHandlers implements UpdatesCallback {
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkup.setSelective(true);
sendMessageRequest.setReplayMarkup(replyKeyboardMarkup); sendMessageRequest.setReplayMarkup(replyKeyboardMarkup);
sendMessageRequest.setText(LocalisationService.getInstance().getString("chooselanguage", language)); sendMessageRequest.setText(LocalisationService.getInstance().getString("chooselanguage", language));
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private void onLanguageReceived(Message message) throws InvalidObjectException { private void onLanguageReceived(Message message) throws InvalidObjectException {
@ -254,7 +279,11 @@ public class FilesHandlers implements UpdatesCallback {
replyKeyboardHide.setHideKeyboard(true); replyKeyboardHide.setHideKeyboard(true);
replyKeyboardHide.setSelective(true); replyKeyboardHide.setSelective(true);
sendMessageRequest.setReplayMarkup(replyKeyboardHide); sendMessageRequest.setReplayMarkup(replyKeyboardHide);
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
languageMessages.remove(message.getFrom().getId()); languageMessages.remove(message.getFrom().getId());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }

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

@ -1,18 +1,14 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.BotConfig; 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.BotLogger;
import org.telegram.services.RaeService; import org.telegram.services.RaeService;
import org.telegram.updatesreceivers.UpdatesThread; import org.telegram.telegrambots.TelegramApiException;
import org.telegram.updatesreceivers.Webhook; import org.telegram.telegrambots.api.methods.AnswerInlineQuery;
import org.telegram.telegrambots.api.methods.SendMessage;
import org.telegram.telegrambots.api.objects.*;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -20,18 +16,14 @@ import java.util.List;
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for inline queries in Raebot * @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 * @date 24 of June of 2015
*/ */
public class RaeHandlers implements UpdatesCallback { public class RaeHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "RAEHANDLERS"; 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 Integer CACHETIME = 86400;
private static final boolean USEWEBHOOK = true; private final RaeService raeService = new RaeService();
private final RaeService raeService; private static final String THUMBNAILBLUE = "https://lh5.ggpht.com/-kSFHGvQkFivERzyCNgKPIECtIOELfPNWAQdXqQ7uqv2xztxqll4bVibI0oHJYAuAas=w300";
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" + 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" + "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" + "Simplemente abre cualquiera de tus chats y escribe `@raebot loquesea` en la zona de escribir mensajes.\n" +
@ -39,62 +31,45 @@ public class RaeHandlers implements UpdatesCallback {
"\n\n" + "\n\n" +
"Por ejemplo, intenta escribir `@raebot Punto` aquí."; "Por ejemplo, intenta escribir `@raebot Punto` aquí.";
public RaeHandlers(Webhook webhook) { @Override
raeService = new RaeService(); public String getBotToken() {
if (USEWEBHOOK && BuildVars.useWebHook) { return BotConfig.TOKENRAE;
webhook.registerWebhook(this, BOTNAME);
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else {
SenderHelper.SendWebhook("", TOKEN);
new UpdatesThread(TOKEN, this);
}
} }
@Override @Override
public void onUpdateReceived(Update update) { public void onUpdateReceived(Update update) {
if (update.hasInlineQuery()) { if (update.hasInlineQuery()) {
BotApiMethod botApiMethod = handleIncomingInlineQuery(update.getInlineQuery()); handleIncomingInlineQuery(update.getInlineQuery());
try {
SenderHelper.SendApiMethod(botApiMethod, TOKEN);
} catch (InvalidObjectException e) {
BotLogger.error(LOGTAG, e);
}
} else if (update.hasMessage() && update.getMessage().isUserMessage()) { } else if (update.hasMessage() && update.getMessage().isUserMessage()) {
try { try {
SenderHelper.SendApiMethod(getHelpMessage(update.getMessage()), TOKEN); sendMessage(getHelpMessage(update.getMessage()));
} catch (InvalidObjectException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); e.printStackTrace();
} }
} }
} }
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public String getBotUsername() {
if (update.hasInlineQuery()) { return BotConfig.USERNAMERAE;
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 * For an InlineQuery, results from RAE dictionariy are fetch and returned
* @param inlineQuery InlineQuery recieved * @param inlineQuery InlineQuery recieved
* @return BotApiMethod as response to the inline query
*/ */
private BotApiMethod handleIncomingInlineQuery(InlineQuery inlineQuery) { private void handleIncomingInlineQuery(InlineQuery inlineQuery) {
String query = inlineQuery.getQuery(); String query = inlineQuery.getQuery();
BotLogger.debug(LOGTAG, "Searching: " + query); BotLogger.debug(LOGTAG, "Searching: " + query);
try {
if (!query.isEmpty()) { if (!query.isEmpty()) {
List<RaeService.RaeResult> results = raeService.getResults(query); List<RaeService.RaeResult> results = raeService.getResults(query);
return converteResultsToResponse(inlineQuery, results); sendAnswerInlineQuery(converteResultsToResponse(inlineQuery, results));
} else { } else {
return converteResultsToResponse(inlineQuery, new ArrayList<>()); sendAnswerInlineQuery(converteResultsToResponse(inlineQuery, new ArrayList<>()));
}
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
} }
} }
@ -104,7 +79,7 @@ public class RaeHandlers implements UpdatesCallback {
* @param results Results from RAE service * @param results Results from RAE service
* @return AnswerInlineQuery method to answer the query * @return AnswerInlineQuery method to answer the query
*/ */
private BotApiMethod converteResultsToResponse(InlineQuery inlineQuery, List<RaeService.RaeResult> results) { private static AnswerInlineQuery converteResultsToResponse(InlineQuery inlineQuery, List<RaeService.RaeResult> results) {
AnswerInlineQuery answerInlineQuery = new AnswerInlineQuery(); AnswerInlineQuery answerInlineQuery = new AnswerInlineQuery();
answerInlineQuery.setInlineQueryId(inlineQuery.getId()); answerInlineQuery.setInlineQueryId(inlineQuery.getId());
answerInlineQuery.setCacheTime(CACHETIME); answerInlineQuery.setCacheTime(CACHETIME);
@ -117,14 +92,14 @@ public class RaeHandlers implements UpdatesCallback {
* @param raeResults Results from rae service * @param raeResults Results from rae service
* @return List of InlineQueryResult * @return List of InlineQueryResult
*/ */
private List<InlineQueryResult> convertRaeResults(List<RaeService.RaeResult> raeResults) { private static List<InlineQueryResult> convertRaeResults(List<RaeService.RaeResult> raeResults) {
List<InlineQueryResult> results = new ArrayList<>(); List<InlineQueryResult> results = new ArrayList<>();
for (int i = 0; i < raeResults.size(); i++) { for (int i = 0; i < raeResults.size(); i++) {
RaeService.RaeResult raeResult = raeResults.get(i); RaeService.RaeResult raeResult = raeResults.get(i);
InlineQueryResultArticle article = new InlineQueryResultArticle(); InlineQueryResultArticle article = new InlineQueryResultArticle();
article.setDisableWebPagePreview(true); article.setDisableWebPagePreview(true);
article.setMarkdown(true); article.enableMarkdown(true);
article.setId(Integer.toString(i)); article.setId(Integer.toString(i));
article.setMessageText(raeResult.getDefinition()); article.setMessageText(raeResult.getDefinition());
article.setTitle(raeResult.getTitle()); article.setTitle(raeResult.getTitle());
@ -141,7 +116,7 @@ public class RaeHandlers implements UpdatesCallback {
* @param message Received message * @param message Received message
* @return SendMessage method * @return SendMessage method
*/ */
public BotApiMethod getHelpMessage(Message message) { private static SendMessage getHelpMessage(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId().toString()); sendMessage.setChatId(message.getChatId().toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);

26
src/main/java/org/telegram/updateshandlers/SentCallback.java

@ -1,26 +0,0 @@
package org.telegram.updateshandlers;
import org.json.JSONObject;
import org.telegram.api.methods.BotApiMethod;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Callback to execute api method asynchronously
* @date 10 of September of 2015
*/
public interface SentCallback<T> {
/**
* Called when the request is successful
* @param method Method executed
* @param jsonObject Answer from Telegram server
*/
void onResult(BotApiMethod<T> method, JSONObject jsonObject);
/**
* Called when the request fails
* @param method Method executed
* @param jsonObject Answer from Telegram server (contains error information)
*/
void onError(BotApiMethod<T> method, JSONObject jsonObject);
}

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

@ -1,20 +1,17 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.BuildVars;
import org.telegram.Commands; import org.telegram.Commands;
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.Update;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.services.BotLogger; 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.telegrambots.TelegramApiException;
import org.telegram.updatesreceivers.Webhook; import org.telegram.telegrambots.api.methods.SendDocument;
import org.telegram.telegrambots.api.methods.SendMessage;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
@ -24,20 +21,12 @@ import java.io.InvalidObjectException;
* @brief Handler for updates to Transifex Bot * @brief Handler for updates to Transifex Bot
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class TransifexHandlers implements UpdatesCallback { public class TransifexHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "TRANSIFEXHANDLERS"; private static final String LOGTAG = "TRANSIFEXHANDLERS";
private static final String TOKEN = BotConfig.TOKENTRANSIFEX;
private static final String BOTNAME = BotConfig.USERNAMETRANSIFEX;
private static final boolean USEWEBHOOK = false;
public TransifexHandlers(Webhook webhook) { @Override
if (USEWEBHOOK && BuildVars.useWebHook) { public String getBotToken() {
webhook.registerWebhook(this, BOTNAME); return BotConfig.TOKENTRANSIFEX;
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else {
SenderHelper.SendWebhook("", TOKEN);
new UpdatesThread(TOKEN, this);
}
} }
@Override @Override
@ -50,12 +39,11 @@ public class TransifexHandlers implements UpdatesCallback {
} }
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public String getBotUsername() {
// Webhook not supported in this example return BotConfig.USERNAMETRANSIFEX;
return null;
} }
public void sendTransifexFile(Update update) throws InvalidObjectException { private 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());
@ -86,12 +74,20 @@ public class TransifexHandlers implements UpdatesCallback {
Commands.transifexAndroidSupportCommand); Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated); sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
if (sendDocument != null) { if (sendDocument != null) {
sendDocument.setChatId(message.getChatId().toString()); sendDocument.setChatId(message.getChatId().toString());
SenderHelper.SendDocument(sendDocument, TOKEN); try {
sendDocument(sendDocument);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} else if (parts[0].startsWith(Commands.help) || } else if (parts[0].startsWith(Commands.help) ||
(message.getText().startsWith(Commands.startCommand) || !message.isGroupMessage())) { (message.getText().startsWith(Commands.startCommand) || !message.isGroupMessage())) {
@ -103,7 +99,11 @@ public class TransifexHandlers implements UpdatesCallback {
Commands.transifexAndroidSupportCommand); Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated); sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setChatId(message.getChatId().toString());
SenderHelper.SendApiMethod(sendMessageRequest, TOKEN); try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
} }
} }

24
src/main/java/org/telegram/updateshandlers/UpdatesCallback.java

@ -1,24 +0,0 @@
package org.telegram.updateshandlers;
import org.telegram.api.objects.Update;
import org.telegram.api.methods.BotApiMethod;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Callback to handle updates. Must support both, single update and List of updates
* @date 20 of June of 2015
*/
public interface UpdatesCallback {
/**
* This method is called when receiving updates via org.telegram.api.methods.GetUpdates method
* @param update Update received
*/
void onUpdateReceived(Update update);
/**
* This method is called when receiving updates via webhook
* @param update Update received
*/
BotApiMethod onWebhookUpdateReceived(Update update);
}

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

@ -1,19 +1,15 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.BuildVars;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.SenderHelper;
import org.telegram.api.methods.BotApiMethod;
import org.telegram.api.methods.SendMessage;
import org.telegram.api.objects.*;
import org.telegram.database.DatabaseManager; 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.telegrambots.TelegramApiException;
import org.telegram.updatesreceivers.Webhook; import org.telegram.telegrambots.api.methods.SendMessage;
import org.telegram.telegrambots.api.objects.*;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -21,14 +17,10 @@ import java.util.List;
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for updates to Weather Bot * @brief Handler for updates to Weather Bot
* This is a use case that works with both Webhooks and GetUpdates methods
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
public class WeatherHandlers implements UpdatesCallback { public class WeatherHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "WEATHERHANDLERS"; private static final String LOGTAG = "WEATHERHANDLERS";
private static final String TOKEN = BotConfig.TOKENWEATHER;
private static final String BOTNAME = BotConfig.USERNAMEWEATHER;
private static final boolean USEWEBHOOK = true;
private static final int STARTSTATE = 0; private static final int STARTSTATE = 0;
private static final int MAINMENU = 1; private static final int MAINMENU = 1;
@ -45,20 +37,32 @@ public class WeatherHandlers implements UpdatesCallback {
private static final int LANGUAGE = 12; private static final int LANGUAGE = 12;
private static final int UNITS = 13; private static final int UNITS = 13;
private final Object webhookLock = new Object(); public WeatherHandlers() {
super();
startAlertTimers();
}
public WeatherHandlers(Webhook webhook) { @Override
if (USEWEBHOOK && BuildVars.useWebHook) { public String getBotToken() {
webhook.registerWebhook(this, BOTNAME); return BotConfig.TOKENWEATHER;
SenderHelper.SendWebhook(Webhook.getExternalURL(BOTNAME), TOKEN);
} else {
SenderHelper.SendWebhook("", TOKEN);
new UpdatesThread(TOKEN, this);
} }
startAlertTimers();
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage()) {
Message message = update.getMessage();
if (message.hasText() || message.hasLocation()) {
handleIncomingMessage(message);
}
}
}
@Override
public String getBotUsername() {
return BotConfig.USERNAMEWEATHER;
} }
private static void startAlertTimers() { private void startAlertTimers() {
TimerExecutor.getInstance().startExecutionEveryDayAt(new CustomTimerTask("First day alert", -1) { TimerExecutor.getInstance().startExecutionEveryDayAt(new CustomTimerTask("First day alert", -1) {
@Override @Override
public void execute() { public void execute() {
@ -74,7 +78,7 @@ public class WeatherHandlers implements UpdatesCallback {
}, 12, 0, 0); }, 12, 0, 0);
} }
private static void sendAlerts() { private 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()) { synchronized (Thread.currentThread()) {
@ -91,37 +95,15 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(String.valueOf(weatherAlert.getUserId())); sendMessage.setChatId(String.valueOf(weatherAlert.getUserId()));
sendMessage.setText(weather); sendMessage.setText(weather);
sendBuiltMessage(sendMessage);
}
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage()) {
Message message = update.getMessage();
if (message.hasText() || message.hasLocation()) {
BotApiMethod botApiMethod = handleIncomingMessage(message);
try { try {
SenderHelper.SendApiMethod(botApiMethod, TOKEN); sendMessage(sendMessage);
} catch (InvalidObjectException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); BotLogger.error(LOGTAG, e);
} }
} }
} }
}
@Override private static SendMessage onCancelCommand(Long chatId, Integer userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) {
public BotApiMethod onWebhookUpdateReceived(Update update) {
if (update.hasMessage()) {
Message message = update.getMessage();
synchronized (webhookLock) {
return handleIncomingMessage(message);
}
}
return null;
}
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.toString()); sendMessage.setChatId(chatId.toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -136,54 +118,59 @@ public class WeatherHandlers implements UpdatesCallback {
// region Incoming messages handlers // region Incoming messages handlers
private static BotApiMethod handleIncomingMessage(Message message) { private void 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.isUserMessage() && message.hasText()) { if (!message.isUserMessage() && message.hasText()) {
if (isCommandForOther(message.getText())) { if (isCommandForOther(message.getText())) {
return null; return;
} else if (message.getText().startsWith(Commands.STOPCOMMAND)){ } else if (message.getText().startsWith(Commands.STOPCOMMAND)){
sendHideKeyboard(message.getFrom().getId(), message.getChatId(), message.getMessageId()); sendHideKeyboard(message.getFrom().getId(), message.getChatId(), message.getMessageId());
return null; return;
} }
} }
BotApiMethod botApiMethod; SendMessage sendMessageRequest;
switch(state) { switch(state) {
case MAINMENU: case MAINMENU:
botApiMethod = messageOnMainMenu(message, language); sendMessageRequest = messageOnMainMenu(message, language);
break; break;
case CURRENTWEATHER: case CURRENTWEATHER:
case CURRENTNEWWEATHER: case CURRENTNEWWEATHER:
case CURRENTLOCATIONWEATHER: case CURRENTLOCATIONWEATHER:
botApiMethod = messageOnCurrentWeather(message, language, state); sendMessageRequest = messageOnCurrentWeather(message, language, state);
break; break;
case FORECASTWEATHER: case FORECASTWEATHER:
case FORECASTNEWWEATHER: case FORECASTNEWWEATHER:
case FORECASTLOCATIONWEATHER: case FORECASTLOCATIONWEATHER:
botApiMethod = messageOnForecastWeather(message, language, state); sendMessageRequest = messageOnForecastWeather(message, language, state);
break; break;
case ALERT: case ALERT:
case ALERTNEW: case ALERTNEW:
case ALERTDELETE: case ALERTDELETE:
botApiMethod = messageOnAlert(message, language, state); sendMessageRequest = messageOnAlert(message, language, state);
break; break;
case SETTINGS: case SETTINGS:
botApiMethod = messageOnSetting(message, language); sendMessageRequest = messageOnSetting(message, language);
break; break;
case LANGUAGE: case LANGUAGE:
botApiMethod = messageOnLanguage(message, language); sendMessageRequest = messageOnLanguage(message, language);
break; break;
case UNITS: case UNITS:
botApiMethod = messageOnUnits(message, language); sendMessageRequest = messageOnUnits(message, language);
break; break;
default: default:
botApiMethod = sendMessageDefault(message, language); sendMessageRequest = sendMessageDefault(message, language);
break; break;
} }
return botApiMethod;
try {
sendMessage(sendMessageRequest);
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
} }
private static void sendHideKeyboard(Integer userId, Long chatId, Integer messageId) { private void sendHideKeyboard(Integer userId, Long chatId, Integer messageId) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId.toString()); sendMessage.setChatId(chatId.toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -196,9 +183,9 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessage.setReplayMarkup(replyKeyboardHide); sendMessage.setReplayMarkup(replyKeyboardHide);
try { try {
SenderHelper.SendApiMethod(sendMessage, TOKEN); sendMessage(sendMessage);
DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE); DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE);
} catch (InvalidObjectException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); BotLogger.error(LOGTAG, e);
} }
@ -214,38 +201,38 @@ public class WeatherHandlers implements UpdatesCallback {
// region Alerts Menu Option selected // region Alerts Menu Option selected
private static BotApiMethod messageOnAlert(Message message, String language, int state) { private static SendMessage messageOnAlert(Message message, String language, int state) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
switch(state) { switch(state) {
case ALERT: case ALERT:
botApiMethod = onAlertOptionSelected(message, language); sendMessageRequest = onAlertOptionSelected(message, language);
break; break;
case ALERTNEW: case ALERTNEW:
botApiMethod = onAlertNewOptionSelected(message, language); sendMessageRequest = onAlertNewOptionSelected(message, language);
break; break;
case ALERTDELETE: case ALERTDELETE:
botApiMethod = onAlertDeleteOptionSelected(message, language); sendMessageRequest = onAlertDeleteOptionSelected(message, language);
break; break;
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onAlertDeleteOptionSelected(Message message, String language) { private static SendMessage onAlertDeleteOptionSelected(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().equals(getCancelCommand(language))) { if (message.getText().equals(getCancelCommand(language))) {
botApiMethod = onAlertDeleteBackOptionSelected(message, language); sendMessageRequest = onAlertDeleteBackOptionSelected(message, language);
} else if (DatabaseManager.getInstance().getAlertCitiesNameByUser(message.getFrom().getId()).contains(message.getText())) { } else if (DatabaseManager.getInstance().getAlertCitiesNameByUser(message.getFrom().getId()).contains(message.getText())) {
botApiMethod = onAlertDeleteCityOptionSelected(message, language); sendMessageRequest = onAlertDeleteCityOptionSelected(message, language);
} else { } else {
botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), getAlertsListKeyboard(message.getFrom().getId(), language), language); sendMessageRequest = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), getAlertsListKeyboard(message.getFrom().getId(), language), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onAlertDeleteCityOptionSelected(Message message, String language) { private static SendMessage onAlertDeleteCityOptionSelected(Message message, String language) {
DatabaseManager.getInstance().deleteAlertCity(message.getFrom().getId(), message.getText()); DatabaseManager.getInstance().deleteAlertCity(message.getFrom().getId(), message.getText());
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -258,7 +245,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onAlertDeleteBackOptionSelected(Message message, String language) { private static SendMessage onAlertDeleteBackOptionSelected(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplayToMessageId(message.getMessageId()); sendMessage.setReplayToMessageId(message.getMessageId());
@ -270,8 +257,8 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onAlertNewOptionSelected(Message message, String language) { private static SendMessage onAlertNewOptionSelected(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().equals(getCancelCommand(language))) { if (message.getText().equals(getCancelCommand(language))) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
@ -281,15 +268,15 @@ public class WeatherHandlers implements UpdatesCallback {
sendMessage.setReplayMarkup(getAlertsKeyboard(language)); sendMessage.setReplayMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language)); sendMessage.setText(LocalisationService.getInstance().getString("alertsMenuMessage", language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT);
botApiMethod = sendMessage; sendMessageRequest = sendMessage;
} else { } else {
botApiMethod = onNewAlertCityReceived(message, language); sendMessageRequest = onNewAlertCityReceived(message, language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onNewAlertCityReceived(Message message, String language) { private static SendMessage onNewAlertCityReceived(Message message, String language) {
int userId = message.getFrom().getId(); int userId = message.getFrom().getId();
Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, message.getText()); Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, message.getText());
if (cityId != null) { if (cityId != null) {
@ -309,26 +296,26 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onAlertOptionSelected(Message message, String language) { private static SendMessage onAlertOptionSelected(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().equals(getNewCommand(language))) { if (message.getText().equals(getNewCommand(language))) {
botApiMethod = onNewAlertCommand(message, language); sendMessageRequest = onNewAlertCommand(message, language);
} else if (message.getText().equals(getDeleteCommand(language))) { } else if (message.getText().equals(getDeleteCommand(language))) {
botApiMethod = onDeleteAlertCommand(message, language); sendMessageRequest = onDeleteAlertCommand(message, language);
} else if (message.getText().equals(getListCommand(language))) { } else if (message.getText().equals(getListCommand(language))) {
botApiMethod = onListAlertCommand(message, language); sendMessageRequest = onListAlertCommand(message, language);
} else if (message.getText().equals(getBackCommand(language))) { } else if (message.getText().equals(getBackCommand(language))) {
botApiMethod = onBackAlertCommand(message, language); sendMessageRequest = onBackAlertCommand(message, language);
} else { } else {
botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), sendMessageRequest = sendChooseOptionMessage(message.getChatId(), message.getMessageId(),
getAlertsKeyboard(language), language); getAlertsKeyboard(language), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onBackAlertCommand(Message message, String language) { private static SendMessage onBackAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -342,7 +329,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onListAlertCommand(Message message, String language) { private static SendMessage onListAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -355,7 +342,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onDeleteAlertCommand(Message message, String language) { private static SendMessage onDeleteAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -392,26 +379,26 @@ public class WeatherHandlers implements UpdatesCallback {
// region Settings Menu Option selected // region Settings Menu Option selected
private static BotApiMethod messageOnSetting(Message message, String language) { private static SendMessage messageOnSetting(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().startsWith(getLanguagesCommand(language))) { if (message.getText().startsWith(getLanguagesCommand(language))) {
botApiMethod = onLanguageCommand(message, language); sendMessageRequest = onLanguageCommand(message, language);
} else if (message.getText().startsWith(getUnitsCommand(language))) { } else if (message.getText().startsWith(getUnitsCommand(language))) {
botApiMethod = onUnitsCommand(message, language); sendMessageRequest = onUnitsCommand(message, language);
} else if (message.getText().startsWith(getAlertsCommand(language))) { } else if (message.getText().startsWith(getAlertsCommand(language))) {
botApiMethod = onAlertsCommand(message, language); sendMessageRequest = onAlertsCommand(message, language);
} else if (message.getText().startsWith(getBackCommand(language))) { } else if (message.getText().startsWith(getBackCommand(language))) {
botApiMethod = sendMessageDefault(message, language); sendMessageRequest = sendMessageDefault(message, language);
} else { } else {
botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), sendMessageRequest = sendChooseOptionMessage(message.getChatId(), message.getMessageId(),
getSettingsKeyboard(language), language); getSettingsKeyboard(language), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onAlertsCommand(Message message, String language) { private static SendMessage onAlertsCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -424,7 +411,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onUnitsCommand(Message message, String language) { private static SendMessage onUnitsCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -437,7 +424,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onLanguageCommand(Message message, String language) { private static SendMessage onLanguageCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -454,25 +441,25 @@ public class WeatherHandlers implements UpdatesCallback {
// region Units Menu Option selected // region Units Menu Option selected
private static BotApiMethod messageOnUnits(Message message, String language) { private static SendMessage messageOnUnits(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().trim().equals(getCancelCommand(language))) { if (message.getText().trim().equals(getCancelCommand(language))) {
botApiMethod = onBackUnitsCommand(message, language); sendMessageRequest = onBackUnitsCommand(message, language);
} else if (message.getText().trim().equals(LocalisationService.getInstance().getString("metricSystem", language))) { } else if (message.getText().trim().equals(LocalisationService.getInstance().getString("metricSystem", language))) {
botApiMethod = onUnitsChosen(message.getFrom().getId(), message.getChatId(), sendMessageRequest = onUnitsChosen(message.getFrom().getId(), message.getChatId(),
message.getMessageId(), WeatherService.METRICSYSTEM, language); message.getMessageId(), WeatherService.METRICSYSTEM, language);
} else if (message.getText().trim().equals(LocalisationService.getInstance().getString("imperialSystem", language))) { } else if (message.getText().trim().equals(LocalisationService.getInstance().getString("imperialSystem", language))) {
botApiMethod = onUnitsChosen(message.getFrom().getId(), message.getChatId(), sendMessageRequest = onUnitsChosen(message.getFrom().getId(), message.getChatId(),
message.getMessageId(), WeatherService.IMPERIALSYSTEM, language); message.getMessageId(), WeatherService.IMPERIALSYSTEM, language);
} else { } else {
botApiMethod = onUnitsError(message.getChatId(), message.getMessageId(), language); sendMessageRequest = onUnitsError(message.getChatId(), message.getMessageId(), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onBackUnitsCommand(Message message, String language) { private static SendMessage onBackUnitsCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -486,7 +473,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onUnitsError(Long chatId, Integer messageId, String language) { private static SendMessage onUnitsError(Long chatId, Integer messageId, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId.toString()); sendMessageRequest.setChatId(chatId.toString());
@ -497,7 +484,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onUnitsChosen(Integer userId, Long chatId, Integer messageId, String units, String language) { private static SendMessage 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();
@ -515,22 +502,22 @@ public class WeatherHandlers implements UpdatesCallback {
// region Language Menu Option selected // region Language Menu Option selected
private static BotApiMethod messageOnLanguage(Message message, String language) { private static SendMessage messageOnLanguage(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().trim().equals(getCancelCommand(language))) { if (message.getText().trim().equals(getCancelCommand(language))) {
botApiMethod = onBackLanguageCommand(message, language); sendMessageRequest = onBackLanguageCommand(message, language);
} else if (LocalisationService.getInstance().getSupportedLanguages().values().contains(message.getText().trim())) { } else if (LocalisationService.getInstance().getSupportedLanguages().values().contains(message.getText().trim())) {
botApiMethod = onLanguageChosen(message.getFrom().getId(), message.getChatId(), sendMessageRequest = onLanguageChosen(message.getFrom().getId(), message.getChatId(),
message.getMessageId(), message.getText().trim()); message.getMessageId(), message.getText().trim());
} else { } else {
botApiMethod = onLanguageError(message.getChatId(), message.getMessageId(), language); sendMessageRequest = onLanguageError(message.getChatId(), message.getMessageId(), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onBackLanguageCommand(Message message, String language) { private static SendMessage onBackLanguageCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -544,7 +531,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onLanguageError(Long chatId, Integer messageId, String language) { private static SendMessage onLanguageError(Long chatId, Integer messageId, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId.toString()); sendMessageRequest.setChatId(chatId.toString());
@ -555,7 +542,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onLanguageChosen(Integer userId, Long chatId, Integer messageId, String language) { private static SendMessage 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);
@ -574,41 +561,41 @@ public class WeatherHandlers implements UpdatesCallback {
// region Forecast Weather Menu Option selected // region Forecast Weather Menu Option selected
private static BotApiMethod messageOnForecastWeather(Message message, String language, int state) { private static SendMessage messageOnForecastWeather(Message message, String language, int state) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
switch(state) { switch(state) {
case FORECASTWEATHER: case FORECASTWEATHER:
botApiMethod = onForecastWeather(message, language); sendMessageRequest = onForecastWeather(message, language);
break; break;
case FORECASTNEWWEATHER: case FORECASTNEWWEATHER:
botApiMethod = onForecastNewWeather(message, language); sendMessageRequest = onForecastNewWeather(message, language);
break; break;
case FORECASTLOCATIONWEATHER: case FORECASTLOCATIONWEATHER:
botApiMethod = onForecastWeatherLocation(message, language); sendMessageRequest = onForecastWeatherLocation(message, language);
break; break;
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onForecastWeather(Message message, String language) { private static SendMessage onForecastWeather(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().startsWith(getNewCommand(language))) { if (message.getText().startsWith(getNewCommand(language))) {
botApiMethod = onNewForecastWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language); sendMessageRequest = onNewForecastWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language);
} else if (message.getText().startsWith(getLocationCommand(language))) { } else if (message.getText().startsWith(getLocationCommand(language))) {
botApiMethod = onLocationForecastWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language); sendMessageRequest = onLocationForecastWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language);
} else if (message.getText().startsWith(getCancelCommand(language))) { } else if (message.getText().startsWith(getCancelCommand(language))) {
botApiMethod = onCancelCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), sendMessageRequest = onCancelCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(),
getMainMenuKeyboard(language), language); getMainMenuKeyboard(language), language);
} else { } else {
botApiMethod = onForecastWeatherCityReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(), sendMessageRequest = onForecastWeatherCityReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(),
message.getText(), language); message.getText(), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onForecastNewWeather(Message message, String language) { private static SendMessage onForecastNewWeather(Message message, String language) {
if (message.isReply()) { if (message.isReply()) {
return onForecastWeatherReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(), message.getText(), language); return onForecastWeatherReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(), message.getText(), language);
} else { } else {
@ -616,7 +603,7 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onForecastWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage 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];
@ -635,7 +622,7 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onLocationForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onLocationForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
@ -649,7 +636,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onNewForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onNewForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
@ -663,7 +650,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onForecastWeatherLocation(Message message, String language) { private static SendMessage onForecastWeatherLocation(Message message, String language) {
if (message.isReply() && message.hasLocation()) { if (message.isReply() && message.hasLocation()) {
return onForecastWeatherLocationReceived(message, language); return onForecastWeatherLocationReceived(message, language);
} else { } else {
@ -675,42 +662,42 @@ public class WeatherHandlers implements UpdatesCallback {
// region Current Weather Menu Option selected // region Current Weather Menu Option selected
private static BotApiMethod messageOnCurrentWeather(Message message, String language, int state) { private static SendMessage messageOnCurrentWeather(Message message, String language, int state) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
switch(state) { switch(state) {
case CURRENTWEATHER: case CURRENTWEATHER:
botApiMethod = onCurrentWeather(message, language); sendMessageRequest = onCurrentWeather(message, language);
break; break;
case CURRENTNEWWEATHER: case CURRENTNEWWEATHER:
botApiMethod = onCurrentNewWeather(message, language); sendMessageRequest = onCurrentNewWeather(message, language);
break; break;
case CURRENTLOCATIONWEATHER: case CURRENTLOCATIONWEATHER:
botApiMethod = onCurrentWeatherLocation(message, language); sendMessageRequest = onCurrentWeatherLocation(message, language);
break; break;
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onCurrentWeather(Message message, String language) { private static SendMessage onCurrentWeather(Message message, String language) {
BotApiMethod botApiMethod = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().startsWith(getNewCommand(language))) { if (message.getText().startsWith(getNewCommand(language))) {
botApiMethod = onNewCurrentWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language); sendMessageRequest = onNewCurrentWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language);
} else if (message.getText().startsWith(getLocationCommand(language))) { } else if (message.getText().startsWith(getLocationCommand(language))) {
botApiMethod = onLocationCurrentWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language); sendMessageRequest = onLocationCurrentWeatherCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), language);
} else if (message.getText().startsWith(getCancelCommand(language))) { } else if (message.getText().startsWith(getCancelCommand(language))) {
botApiMethod = onCancelCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(), sendMessageRequest = onCancelCommand(message.getChatId(), message.getFrom().getId(), message.getMessageId(),
getMainMenuKeyboard(language), language); getMainMenuKeyboard(language), language);
} else { } else {
botApiMethod = onCurrentWeatherCityReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(), sendMessageRequest = onCurrentWeatherCityReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(),
message.getText(), language); message.getText(), language);
} }
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onCurrentNewWeather(Message message, String language) { private static SendMessage onCurrentNewWeather(Message message, String language) {
if (message.isReply()) { if (message.isReply()) {
return onCurrentWeatherReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(), message.getText(), language); return onCurrentWeatherReceived(message.getChatId(), message.getFrom().getId(), message.getMessageId(), message.getText(), language);
} else { } else {
@ -718,7 +705,7 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onCurrentWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage 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];
@ -736,7 +723,7 @@ public class WeatherHandlers implements UpdatesCallback {
} }
} }
private static BotApiMethod onLocationCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onLocationCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
@ -750,7 +737,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onNewCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onNewCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
@ -764,7 +751,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onCurrentWeatherLocation(Message message, String language) { private static SendMessage onCurrentWeatherLocation(Message message, String language) {
if (message.isReply() && message.hasLocation()) { if (message.isReply() && message.hasLocation()) {
return onCurrentWeatherLocationReceived(message, language); return onCurrentWeatherLocationReceived(message, language);
} else { } else {
@ -776,30 +763,30 @@ public class WeatherHandlers implements UpdatesCallback {
// region Main menu options selected // region Main menu options selected
private static BotApiMethod messageOnMainMenu(Message message, String language) { private static SendMessage messageOnMainMenu(Message message, String language) {
BotApiMethod botApiMethod; SendMessage sendMessageRequest;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().equals(getCurrentCommand(language))) { if (message.getText().equals(getCurrentCommand(language))) {
botApiMethod = onCurrentChoosen(message, language); sendMessageRequest = onCurrentChoosen(message, language);
} else if (message.getText().equals(getForecastCommand(language))) { } else if (message.getText().equals(getForecastCommand(language))) {
botApiMethod = onForecastChoosen(message, language); sendMessageRequest = onForecastChoosen(message, language);
} else if (message.getText().equals(getSettingsCommand(language))) { } else if (message.getText().equals(getSettingsCommand(language))) {
botApiMethod = onSettingsChoosen(message, language); sendMessageRequest = onSettingsChoosen(message, language);
} else if (message.getText().equals(getRateCommand(language))) { } else if (message.getText().equals(getRateCommand(language))) {
botApiMethod = sendRateMessage(message.getChatId().toString(), message.getMessageId(), null, language); sendMessageRequest = sendRateMessage(message.getChatId().toString(), message.getMessageId(), null, language);
} else { } else {
botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), sendMessageRequest = sendChooseOptionMessage(message.getChatId(), message.getMessageId(),
getMainMenuKeyboard(language), language); getMainMenuKeyboard(language), language);
} }
} else { } else {
botApiMethod = sendChooseOptionMessage(message.getChatId(), message.getMessageId(), sendMessageRequest = sendChooseOptionMessage(message.getChatId(), message.getMessageId(),
getMainMenuKeyboard(language), language); getMainMenuKeyboard(language), language);
} }
return botApiMethod; return sendMessageRequest;
} }
private static BotApiMethod onSettingsChoosen(Message message, String language) { private static SendMessage onSettingsChoosen(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -813,7 +800,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onForecastChoosen(Message message, String language) { private static SendMessage onForecastChoosen(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -831,7 +818,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod onCurrentChoosen(Message message, String language) { private static SendMessage onCurrentChoosen(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
@ -1152,13 +1139,13 @@ public class WeatherHandlers implements UpdatesCallback {
// region Send common messages // region Send common messages
private static BotApiMethod sendMessageDefault(Message message, String language) { private static SendMessage 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().toString(), message.getMessageId(), replyKeyboardMarkup, language); return sendHelpMessage(message.getChatId().toString(), message.getMessageId(), replyKeyboardMarkup, language);
} }
private static BotApiMethod sendChooseOptionMessage(Long chatId, Integer messageId, private static SendMessage 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);
@ -1170,7 +1157,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod sendHelpMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { private static SendMessage 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);
@ -1182,7 +1169,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessage; return sendMessage;
} }
private static BotApiMethod sendRateMessage(String chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { private static SendMessage 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);
@ -1199,7 +1186,7 @@ public class WeatherHandlers implements UpdatesCallback {
// region Send weather // region Send weather
private static BotApiMethod onForecastWeatherLocationReceived(Message message, String language) { private static SendMessage onForecastWeatherLocationReceived(Message message, String language) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1];
String weather = WeatherService.getInstance().fetchWeatherForecastByLocation(message.getLocation().getLongitude(), String weather = WeatherService.getInstance().fetchWeatherForecastByLocation(message.getLocation().getLongitude(),
message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem); message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem);
@ -1214,7 +1201,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onForecastWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage 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();
@ -1228,7 +1215,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onCurrentWeatherLocationReceived(Message message, String language) { private static SendMessage onCurrentWeatherLocationReceived(Message message, String language) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1];
String weather = WeatherService.getInstance().fetchWeatherCurrentByLocation(message.getLocation().getLongitude(), String weather = WeatherService.getInstance().fetchWeatherCurrentByLocation(message.getLocation().getLongitude(),
message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem); message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem);
@ -1243,7 +1230,7 @@ public class WeatherHandlers implements UpdatesCallback {
return sendMessageRequest; return sendMessageRequest;
} }
private static BotApiMethod onCurrentWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage 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();
@ -1258,16 +1245,4 @@ public class WeatherHandlers implements UpdatesCallback {
} }
// endregion Send weather // endregion Send weather
// region Helper Methods
private static void sendBuiltMessage(SendMessage sendMessage) {
try {
SenderHelper.SendApiMethod(sendMessage, TOKEN);
} catch (InvalidObjectException e) {
BotLogger.severe(LOGTAG, e);
}
}
// endregion Helper Methods
} }

52
src/main/java/org/telegram/updatesreceivers/RestApi.java

@ -1,52 +0,0 @@
package org.telegram.updatesreceivers;
import org.telegram.api.objects.Update;
import org.telegram.updateshandlers.UpdatesCallback;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Rest api to for webhook callback function
* @date 20 of June of 2015
*/
@Path("callback")
public class RestApi {
private final ConcurrentHashMap<String, UpdatesCallback> callbacks = new ConcurrentHashMap<>();
public RestApi() {
}
public void registerCallback(UpdatesCallback callback, String botName) {
if (!callbacks.containsKey(botName)) {
callbacks.put(botName, callback);
}
}
@POST
@Path("/{botname}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateReceived(@PathParam("botname") String botname, Update update) {
if (callbacks.containsKey(botname)) {
return Response.ok(this.callbacks.get(botname).onWebhookUpdateReceived(update)).build();
}
return Response.ok().build();
}
@GET
@Path("/{botname}")
@Produces(MediaType.APPLICATION_JSON)
public String testReceived(@PathParam("botname") String botname) {
if (callbacks.containsKey(botname)) {
return "Hi there " + botname + "!";
} else {
return "Callback not found for " + botname;
}
}
}

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

@ -1,144 +0,0 @@
package org.telegram.updatesreceivers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
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.GetUpdates;
import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.UpdatesCallback;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.TimeUnit;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Thread to request updates with active wait
* @date 20 of June of 2015
*/
public class UpdatesThread {
private static final String LOGTAG = "UPDATESTHREAD";
private final UpdatesCallback callback;
private final ReaderThread readerThread;
private final HandlerThread handlerThread;
private int lastReceivedUpdate;
private String token;
private final ConcurrentLinkedDeque<Update> receivedUpdates = new ConcurrentLinkedDeque<>();
public UpdatesThread(String token, UpdatesCallback callback) {
this.token = token;
this.callback = callback;
this.lastReceivedUpdate = DatabaseManager.getInstance().getLastUpdate(this.token);
this.readerThread = new ReaderThread();
this.readerThread.start();
this.handlerThread = new HandlerThread();
this.handlerThread.start();
}
private class ReaderThread extends Thread {
@Override
public void run() {
setPriority(Thread.MIN_PRIORITY);
while(true) {
GetUpdates request = new GetUpdates();
request.setLimit(100);
request.setTimeout(20);
request.setOffset(lastReceivedUpdate + 1);
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).setConnectionTimeToLive(20, TimeUnit.SECONDS).build();
String url = Constants.BASEURL + token + "/" + GetUpdates.PATH;
HttpPost httpPost = new HttpPost(url);
try {
httpPost.addHeader("charset", "UTF-8");
httpPost.setEntity(new StringEntity(request.toJson().toString(), ContentType.APPLICATION_JSON));
HttpResponse response;
BotLogger.debug(LOGTAG, httpPost.toString());
response = httpclient.execute(httpPost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
try {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new InvalidObjectException(jsonObject.toString());
}
JSONArray jsonArray = jsonObject.getJSONArray("result");
BotLogger.debug(LOGTAG, jsonArray.toString());
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
Update update = new Update(jsonArray.getJSONObject(i));
if (update.getUpdateId() > lastReceivedUpdate) {
lastReceivedUpdate = update.getUpdateId();
receivedUpdates.addFirst(update);
}
}
synchronized (receivedUpdates) {
receivedUpdates.notifyAll();
}
} else {
try {
synchronized (this) {
this.wait(500);
}
} catch (InterruptedException e) {
BotLogger.error(LOGTAG, e);
continue;
}
}
} catch (JSONException e) {
BotLogger.warn(LOGTAG, e);
}
} catch (IOException e) {
BotLogger.warn(LOGTAG, e);
}
}
}
}
private class HandlerThread extends Thread {
@Override
public void run() {
setPriority(Thread.MIN_PRIORITY);
while(true) {
try {
Update update = receivedUpdates.pollLast();
if (update == null) {
synchronized (receivedUpdates) {
try {
receivedUpdates.wait();
} catch (InterruptedException e) {
BotLogger.error(LOGTAG, e);
continue;
}
update = receivedUpdates.pollLast();
if (update == null) {
continue;
}
}
}
DatabaseManager.getInstance().putLastUpdate(token, update.getUpdateId());
callback.onUpdateReceived(update);
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
}
}
}
}
}

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

@ -1,78 +0,0 @@
package org.telegram.updatesreceivers;
import com.sun.jersey.api.json.JSONConfiguration;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.ssl.SSLContextConfigurator;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.telegram.BuildVars;
import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.UpdatesCallback;
import java.io.IOException;
import java.net.URI;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Webhook to receive updates
* @date 20 of June of 2015
*/
public class Webhook {
private static final String LOGTAG = "WEBHOOK";
private static final String KEYSTORE_SERVER_FILE = "./keystore_server";
private static final String KEYSTORE_SERVER_PWD = "asdfgh";
private final RestApi restApi;
public Webhook() {
this.restApi = new RestApi();
}
public void registerWebhook(UpdatesCallback callback, String botName) {
restApi.registerCallback(callback, botName);
}
public void startServer() {
SSLContextConfigurator sslContext = new SSLContextConfigurator();
// set up security context
sslContext.setKeyStoreFile(KEYSTORE_SERVER_FILE); // contains server keypair
sslContext.setKeyStorePass(KEYSTORE_SERVER_PWD);
ResourceConfig rc = new ResourceConfig();
rc.register(restApi);
rc.register(JacksonFeature.class);
rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true);
BotLogger.info(LOGTAG, "Internal webhook: " + getBaseURI().toString());
final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(
getBaseURI(),
rc,
true,
new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false));
try {
grizzlyServer.start();
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
}
public void startDebugServer() {
ResourceConfig rc = new ResourceConfig();
rc.register(restApi);
rc.register(JacksonFeature.class);
rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true);
GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
}
public static String getExternalURL(String botName) {
return String.format("%s/callback/%s", BuildVars.EXTERNALWEBHOOKURL, botName);
}
private static URI getBaseURI() {
return URI.create(BuildVars.INTERNALWEBHOOKURL);
}
}
Loading…
Cancel
Save