diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 23b437c2..00000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitignore b/.gitignore index e3308905..737c7ac7 100644 --- a/.gitignore +++ b/.gitignore @@ -8,28 +8,36 @@ release.properties dependency-reduced-pom.xml buildNumber.properties .mvn/timing.properties + ### Java template *.class -# Mobile Tools for Java (J2ME) +### Mobile Tools for Java (J2ME) .mtj.tmp/ -# Package Files # +### Package Files # *.jar *.war *.ear -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +### virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* -# logs files +### logs files *.log -# Certs +### Certs *.jks *.cer *.pem -# IDE files +### IDE files .idea/ +copyright/ *.iml +.classpath +.project +.settings/ + +#File System specific files +.DS_STORE diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..5992b3c4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,8 @@ +language: java +jdk: + - oraclejdk8 +script: mvn clean compile package +notifications: + webhooks: + secure: "jC7dK/x67ONWQoeLZg4HfW0mHhcjDerJjsLLkrbcpltiqAbw2p7XfY8Pk4zHoD72a+5o6WKu5WvYvZ4OdldnjP8Y6ZUbliQ5RG3olg3gFDoe0+sc3geeb4HRYVcdI20O0z4Bup/qO0ZihxPBc0D5IpHmFxlaqlZG0WeST4CicU8PNnBh6aX9/VMrwXhkMb2vfzmjmIhMbx/uK5+93bnk/vR5Uwu00/Yd2cTAAWMaqK1MRdtR0WLbxlUNsprEfCjYiH3n9XZnlKXs6cLC8EOU436Wx7aepiAszW0wWFMe/7nVqOqztrQiKNvL0qXYwlQf0BLechJdt458EopL9QCu687TNDFYvg1yERAmCRiaayYZcX3PbUSMr6H5Q+Odntjs3XKyzfgSqqlkgf/SAND5jny1/1uteVoplZmFXuZFIiK4H8Rl2ezy1/8pnbp+JD3YEfiA2NuRjlou1BZXyMhiqqVXbrJqk/tXF6yZSkDlYJfNsWzRCGfra4B6JjEvUP927chIFm1ii3dgNstXDo1evV46+OQQO4HKvMPdtU2FPvWpPlkTxnmpZRZjB+bjmybluJdWT3E+e1C3wm7YbRe3vporhpfNPlnod6M0G10y9CKzl9Fbcku6X1FtM+IoPO/aqZ8S4/CBZoYEuR/Nk6bcvsYouxtyIl6PSuF9E8YjpJE=" + email: false diff --git a/HOWTO.md b/HOWTO.md new file mode 100644 index 00000000..c4a31f9d --- /dev/null +++ b/HOWTO.md @@ -0,0 +1,193 @@ +So, you just wanna program your own Telegram bot with @rubenlagus library TelegramBots? Then I'm going to show you how to start ;) + +##### Table of Contents +[Preperations](#preperations) +[Let's code!](#lets_code) +[FAQ](#faq) +       1. [How to get picture?](#question_how_to_get_picture) +       2. [How to send photos?](#question_how_to_send_photos) +       3. [How to use custom keyboards?](#question_how_to_use_custom_keyboards) +       4. [How can I compile my project?](#question_how_to_compile) + + + + +## Preperations +First you need to download the latest .jar from the Release site [here](https://github.com/rubenlagus/TelegramBots/releases). You can choose between Jar with or without dependencies. If you don't know which one to choose, we recommend to download the full jar with all dependencies ;) + +Next, you need to integrate it into your project. + +Create a new project for your bot, in the example below we are showing you how to do it in eclipse. But of course, you are free to code in whatever IDE you want ;) + +If you don't know how to include a external .jar into your Eclipse project, maybe [this](https://www.youtube.com/watch?v=VWnfHkBgO1I) video is helpful for you + +More information on how to use it with Gradle or Maven, can be found here [here](https://jitpack.io/#rubenlagus/TelegramBots) + + + +## Let's code! +Create a new class that extends one of the following + +```TelegramLongPollingBot``` -> bot is asking Telegram servers continuously if new updates are available + +```TelegramWebhookBot``` -> our bot is "called" from Telegram servers when updates are available + +```TelegramLongPollingCommandBot``` -> simply like TelegramLongPollingBot, but based around the idea of Commands + +Due to the fact that the TelegramLongPollingBot is a little bit less complicated than the others, we are going to work with him in this example. + +Extend ```TelegramLongPollingBot``` with one of your own classes. If we want that the bot can work normally, we must implement the following methods: ```getBotUsername():String```, ```getBotToken():String``` and ```onUpdateReceived(update: Update)``` + +The first two methods are really easy to implement. Just create a new class that contains all the information for the bot (username, token and maybe in the future some database information) + +At the end it could look like this: + +```java +public class BotConfig { + public static final String BOT_USERNAME = "echoBot"; + public static final String BOT_TOKEN = "{you secret bot token that you got from BotFather}"; +} +``` + +After it, return these static variables like this one: +```java +@Override +public String getBotToken() { + return BotConfig.BOT_TOKEN; +} +``` + +The last method could look like this: + +```java +@Override +public void onUpdateReceived(Update update) { + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + + //check if the message has text. it could also contain for example a location ( message.hasLocation() ) + if(message.hasText()){ + //create an object that contains the information to send back the message + SendMessage sendMessageRequest = new SendMessage(); + sendMessageRequest.setChatId(message.getChatId().toString()); //who should get from the message the sender that sent it. + sendMessageRequest.setText("you said: " + message.getText()); + try { + sendMessage(sendMessageRequest); //at the end, so some magic and send the message ;) + } catch (TelegramApiException e) { + //do some error handling + } + } + } +} +``` +The principle is rather easy, we have an ```update```, we see that it contains a text -> we create a Send*** object, fill it up with all necessary infos (user/chatId, text) and fire it up + +If you want to send also other types of media (such as photos or audio), then check out our FAQ at the end if this HOWTO. Also please check out the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It contains useful information on how to use the lib from @rubenlagus. + +If you have questions that are not handled here or in the example repo, than feel free to open a new Issue :P +In any case, you can reach us at [our Telegram group chat](https://telegram.me/JavaBotsApi) ;) + +But to be in context: our bot is not ready, yet. It lacks a way to tell the library that we have a super cool new UpdateHandler written, you remember? 😏 + + +```java +public static void main(String[] args) { + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + try { + telegramBotsApi.registerBot(new MyProjectHandler()); + } catch (TelegramApiException e) { + BotLogger.error(LOGTAG, e); + } +} +``` + + +## FAQ + + Question: + How to get a picture? + Answer: A ```onUpdateReceived()``` Method that just downloads every Photo that users send to the bot could look like this: + +```java +@Override +public void onUpdateReceived(Update update) { + //check if the update has a message + if (update.hasMessage()) { + Message message = update.getMessage(); + //check if we got some photos + if (message.getPhoto() != null) { + /* + * Just save our received photos in a list. At this point, we do not really have the photos. We have just their id. + * And with their id's we can download them from Telegram servers + */ + for (int i = 0; i < photos.size(); i++) { + GetFile getFileRequest = new GetFile(); + getFileRequest.setFileId(photos.get(i).getFileId()); + try { + + //we send a request with our fileId to get our filePath. + File file = getFile(getFileRequest); + + /* + * After that, we can now start to save them on our local machine. + * Please have a look on the API specification, on how to download the files with their filepaths you just got in the code above + * https://core.telegram.org/bots/api#file + * + * Just replace with File.getFilePath(); + */ + + // In this example, we just print here the filePaths + System.out.println(file.getFilePath()); + } catch (TelegramApiException e) { + //TODO: so some error handling + } + } + } + } +} +``` + Question: + How to send photos? + Answer: + + +```java +@Override +public void onUpdateReceived(Update update) { + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + //check if the message has text. it could also contain for example a location ( message.hasLocation() ) + if(message.hasText()){ + if(message.getText().equals("/wiki")){ + SendPhoto sendPhotoRequest = new SendPhoto(); + sendPhotoRequest.setChatId(message.getChatId().toString()); + //path: String, photoName: String + sendPhotoRequest.setNewPhoto("/home/marcel/Downloads/potd_wikipedia.jpg", "Good Friday.jpg"); // + try { + sendPhoto(sendPhotoRequest); + } catch (TelegramApiException e) { + /* + * Do some error handling + * e.printStackTrace(); + */ + } + } + } + } +} +``` + + This method uploads the photo every time the user send the bot /wiki. Telegram stores the files we upload on their server. And if next time someone wants to retrieve THE SAME photo we uploaded some time ago, you should use instead of SendPhoto.setNewPhoto() the SendPhoto.setPhoto() method. This method has just one parameter, file_id. + + Question: + How to use custom keyboards? + Answer: You can look at the [source code](https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java) for [@Weatherbot](https://telegram.me/weatherbot) in the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It should contain all necessary information about using custom keyboards. + + + Question: How can I compile my project? + Answer: This is just one way, how you can compile it (here with maven). The example below below is compiling the TelegramBotsExample repo. + [![asciicast](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj.png)](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj) + + diff --git a/README.md b/README.md index 1047c346..e6456a41 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # Telegram Bot Java Library +[![Build Status](https://travis-ci.org/rubenlagus/TelegramBots.svg?branch=master)](https://travis-ci.org/rubenlagus/TelegramBots) +[![Jitpack](https://jitpack.io/v/rubenlagus/TelegramBots.svg)](https://jitpack.io/#rubenlagus/TelegramBots) [![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi) A simple to use library to create Telegram Bots in Java @@ -9,20 +11,18 @@ Feel free to fork this project, work on it and then make a pull request against Please, **DO NOT PUSH ANY TOKEN OR API KEY**, I will never accept a pull request with that content. ## Webhooks vs GetUpdates -Both ways are supported (but I still didn't tested webhooks). - -I recommend using getUpdates methods. +Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.1) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.1) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.5) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.5) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. If you like to use Webhook, extend `org.telegram.telegrambots.bots.TelegramWebhookBot` -Once done, you just need to creat a `org.telegram.telegrambots.TelegramBotsApi`and register your bots: +Once done, you just need to create a `org.telegram.telegrambots.TelegramBotsApi`and register your bots: ```java @@ -46,19 +46,23 @@ Once done, you just need to creat a `org.telegram.telegrambots.TelegramBotsApi`a ``` +For detailed explanation, visite our [How To](HOWTO.md) (thanks Clevero) + ## Example bots Open them and send them */help* command to get some information about their capabilities: -https://telegram.me/weatherbot +https://telegram.me/weatherbot (**Use custom keyboards**) -https://telegram.me/directionsbot +https://telegram.me/directionsbot (**Basic messages**) -https://telegram.me/filesbot +https://telegram.me/filesbot (**Send files by file_id**) -https://telegram.me/TGlanguagesbot +https://telegram.me/TGlanguagesbot (**Send files uploding them**) -https://telegram.me/RaeBot +https://telegram.me/RaeBot (**Inline support**) + +https://telegram.me/SnowcrashBot (**Webhook support**) You can see code for those bots at [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) project. diff --git a/eclipse configuration.md b/eclipse configuration.md index 8637ab1a..66375ab3 100644 --- a/eclipse configuration.md +++ b/eclipse configuration.md @@ -1,5 +1,8 @@ # How to use TelegramBots with Eclipse +If you **don't** need to modify the sources, you can just download the jar file from [here](https://github.com/rubenlagus/TelegramBots/releases) and import it as an external library. + +If you need to modify the sources, follow these steps: ### Step 1: Install Maven To get started, you need to install the Maven-Plugin for Eclipse. Click on Help > Eclipse Marketplace. After it finished loading, search for “Maven”. @@ -16,11 +19,9 @@ Now let’s setup the project-folder. Go to your Eclipse-Workspace and create a To import your project into the workspace you have to go to File > Import > (Folder) Maven > Existing Maven Projects > Next. Choose the folder, you have created in Step 3. In my case: **“TelegramBotApi”**. Click on finish and let Maven import the dependencies. ### Step 5: Setting the compliance level -In this last step you need to change the Compiler compliance level. To do this right-click on your Project (in my case **“TelegramBotApi”**) > Properties > Java Compiler. Uncheck the “Use compliance from…” if necessary and set it to 1.7 +In this last step you need to change the Compiler compliance level. To do this right-click on your Project (in my case **“TelegramBotApi”**) > Properties > Java Compiler. Uncheck the “Use compliance from…” if necessary and set it to 1.8 -*Now you are done. Everything should work fine. You need to set your Bot-Token in the BotConfig.java, afterwards you can run Main.java to check.* - -**For a better intstruction sheet, visit [Google Drive]** +*Now you are done. Everything should work fine.* [Google Drive]:https://goo.gl/5jd40w [here]:https://github.com/rubenlagus/TelegramBots/archive/master.zip diff --git a/pom.xml b/pom.xml index 5a65bc3a..a78d0f91 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.1 + 2.3.5 Telegram Bots https://telegram.me/JavaBotsApi @@ -26,6 +26,7 @@ 1.19.1 4.5.2 20160212 + 2.7.4 @@ -44,6 +45,7 @@ org.glassfish.jersey.containers jersey-container-grizzly2-http + ${jersey.version} org.glassfish.jersey.media @@ -83,91 +85,99 @@ ${project.artifactId}-${project.version} ${project.build.directory}/test-classes ${project.basedir}/src/main/java + + + maven-clean-plugin + 3.0.0 + + + clean-project + clean + + clean + + + + + + maven-assembly-plugin + 2.6 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.0 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + site + + javadoc-no-fork + + + + + + - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - true - lib/ - org.telegram.Main - - - - - - maven-assembly-plugin - - - - org.telegram.Main - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.9 - - - copy-dependencies - package - - copy-dependencies - - - ${project.build.directory}/lib - false - false - true - - - - - - maven-clean-plugin - org.apache.maven.plugins maven-compiler-plugin diff --git a/src/.DS_Store b/src/.DS_Store deleted file mode 100644 index 21ed6df6..00000000 Binary files a/src/.DS_Store and /dev/null differ diff --git a/src/main/.DS_Store b/src/main/.DS_Store deleted file mode 100644 index 9d2a42b3..00000000 Binary files a/src/main/.DS_Store and /dev/null differ diff --git a/src/main/java/.DS_Store b/src/main/java/.DS_Store deleted file mode 100644 index d6fa8247..00000000 Binary files a/src/main/java/.DS_Store and /dev/null differ diff --git a/src/main/java/org/telegram/telegrambots/Constants.java b/src/main/java/org/telegram/telegrambots/Constants.java index 60371d0f..ac241cc3 100644 --- a/src/main/java/org/telegram/telegrambots/Constants.java +++ b/src/main/java/org/telegram/telegrambots/Constants.java @@ -8,6 +8,7 @@ package org.telegram.telegrambots; */ public class Constants { public static final String BASEURL = "https://api.telegram.org/bot"; + public static final int GETUPDATESTIMEOUT = 50; public static final String RESPONSEFIELDOK = "ok"; public static final String RESPONSEFIELDRESULT = "result"; public static final String ERRORDESCRIPTIONFIELD = "description"; diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java index 17f37ff2..0f0577f8 100644 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -1,6 +1,8 @@ package org.telegram.telegrambots; import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.NoopHostnameVerifier; @@ -13,6 +15,7 @@ import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import org.telegram.telegrambots.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.bots.BotOptions; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramWebhookBot; import org.telegram.telegrambots.updatesreceivers.BotSession; @@ -21,6 +24,7 @@ import org.telegram.telegrambots.updatesreceivers.Webhook; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.text.MessageFormat; import static org.telegram.telegrambots.Constants.ERRORCODEFIELD; import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; @@ -32,11 +36,12 @@ import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; * @date 14 of January of 2016 */ public class TelegramBotsApi { - private boolean useWebhook; ///< - private Webhook webhook; ///< - private String extrenalUrl; ///< - private String pathToCertificate; ///< - private String publicCertificateName; ///< + private static final int SOCKET_TIMEOUT = 75 * 1000; + private static final String webhookUrlFormat = "{0}callback/"; + private boolean useWebhook; ///< True to enable webhook usage + private Webhook webhook; ///< Webhook instance + private String extrenalUrl; ///< External url of the bots + private String pathToCertificate; ///< Path to public key certificate /** * @@ -52,6 +57,13 @@ public class TelegramBotsApi { * @param internalUrl */ public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiException { + if (externalUrl == null || externalUrl.isEmpty()) { + throw new TelegramApiException("Parameter externalUrl can not be null or empty"); + } + if (internalUrl == null || internalUrl.isEmpty()) { + throw new TelegramApiException("Parameter internalUrl can not be null or empty"); + } + this.useWebhook = true; this.extrenalUrl = fixExternalUrl(externalUrl); webhook = new Webhook(keyStore, keyStorePassword, internalUrl); @@ -64,18 +76,42 @@ public class TelegramBotsApi { * @param keyStorePassword * @param externalUrl * @param internalUrl - * @param pathToCertificate - * @param publicCertificateName + * @param pathToCertificate Full path until .pem public certificate keys */ - public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate, String publicCertificateName) throws TelegramApiException { + public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiException { + if (externalUrl == null || externalUrl.isEmpty()) { + throw new TelegramApiException("Parameter externalUrl can not be null or empty"); + } + if (internalUrl == null || internalUrl.isEmpty()) { + throw new TelegramApiException("Parameter internalUrl can not be null or empty"); + } this.useWebhook = true; this.extrenalUrl = fixExternalUrl(externalUrl); this.pathToCertificate = pathToCertificate; - this.publicCertificateName = publicCertificateName; webhook = new Webhook(keyStore, keyStorePassword, internalUrl); webhook.startServer(); } + /** + * Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. + * @param bot the bot to register + */ + public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { + setWebhook(bot.getBotToken(), null, bot.getOptions()); + return new BotSession(bot.getBotToken(), bot, bot.getOptions()); + } + + /** + * + * @param bot + */ + public void registerBot(TelegramWebhookBot bot) throws TelegramApiException { + if (useWebhook) { + webhook.registerWebhook(bot); + setWebhook(bot.getBotToken(), bot.getBotPath(), bot.getOptions()); + } + } + /** * * @param externalUrl @@ -85,26 +121,40 @@ public class TelegramBotsApi { if (externalUrl != null && !externalUrl.endsWith("/")) { externalUrl = externalUrl + "/"; } - return externalUrl; + return MessageFormat.format(webhookUrlFormat, externalUrl); } /** - * - * @param webHookURL - * @param botToken - * @param publicCertificatePath - * @param publicCertificateName - * @throws TelegramApiException + * Set webhook or remove it if necessary + * @param webHookURL Webhook url or empty is removing it + * @param botToken Bot token + * @param publicCertificatePath Path to certificate public key + * @param options Bot options + * @throws TelegramApiException If any error occurs setting the webhook */ - private static void setWebhook(String webHookURL, String botToken, String publicCertificatePath, String publicCertificateName) throws TelegramApiException { + private static void setWebhook(String webHookURL, String botToken, + String publicCertificatePath, BotOptions options) throws TelegramApiException { try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) { String url = Constants.BASEURL + botToken + "/" + SetWebhook.PATH; + RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()) + .setSocketTimeout(SOCKET_TIMEOUT) + .setConnectTimeout(SOCKET_TIMEOUT) + .setConnectionRequestTimeout(SOCKET_TIMEOUT); + + if (options.hasProxy()) { + configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + } + HttpPost httppost = new HttpPost(url); + httppost.setConfig(configBuilder.build()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SetWebhook.URL_FIELD, webHookURL); if (publicCertificatePath != null) { - builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, new File(publicCertificatePath), ContentType.APPLICATION_OCTET_STREAM, publicCertificateName); + File certificate = new File(publicCertificatePath); + if (certificate.exists()) { + builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName()); + } } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -125,33 +175,16 @@ public class TelegramBotsApi { } /** - * Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. - * @param bot + * Set the webhook or remove it if necessary + * @param botToken Bot token + * @param urlPath Url for the webhook or null to remove it + * @param botOptions Bot Options */ - public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { - setWebhook(bot.getBotToken()); - return new BotSession(bot.getBotToken(), bot); - } - - /** - * - * @param bot - */ - public void registerBot(TelegramWebhookBot bot) throws TelegramApiException { - if (useWebhook) { - webhook.registerWebhook(bot); - setWebhook(bot.getBotToken()); - } - } - - /** - * - * @param botToken - */ - private void setWebhook(String botToken) throws TelegramApiException { + private void setWebhook(String botToken, String urlPath, BotOptions botOptions) throws TelegramApiException { if (botToken == null) { throw new TelegramApiException("Parameter botToken can not be null"); } - setWebhook(extrenalUrl == null ? "" : extrenalUrl, botToken, pathToCertificate, publicCertificateName); + String completeExternalUrl = urlPath == null ? "" : extrenalUrl + urlPath; + setWebhook(completeExternalUrl, botToken, pathToCertificate, botOptions); } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java b/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java new file mode 100644 index 00000000..fb107abe --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java @@ -0,0 +1,57 @@ +package org.telegram.telegrambots.api.methods; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Types of actions for SendChatAction method. + * @date 20 of June of 2016 + */ +public enum ActionType { + TYPING("typing"), + RECORDVIDEO("record_video"), + RECORDAUDIO("record_audio"), + UPLOADPHOTO("upload_photo"), + UPLOADVIDEO("upload_video"), + UPLOADAUDIO("upload_audio"), + UPLOADDOCUMENT("upload_document"), + FINDLOCATION("find_location"); + + private String text; + + ActionType(String text) { + this.text = text; + } + + /** + * @deprecated Added for backward compatibility, will be dropped in next mayor release + * @param text text of the action + * @return ActionType + */ + @Deprecated + public static ActionType GetActionType(String text) throws IllegalArgumentException { + switch (text) { + case "typing": + return TYPING; + case "record_video": + return RECORDVIDEO; + case "record_audio": + return RECORDAUDIO; + case "upload_photo": + return UPLOADPHOTO; + case "upload_video": + return UPLOADVIDEO; + case "upload_audio": + return UPLOADAUDIO; + case "upload_document": + return UPLOADDOCUMENT; + case "find_location": + return FINDLOCATION; + } + throw new IllegalArgumentException(text + " doesn't match any know ActionType"); + } + + @Override + public String toString() { + return text; + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java b/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java index 9f7d61b6..ed930884 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java @@ -109,7 +109,7 @@ public class AnswerCallbackQuery extends BotApiMethod { @Override public String toString() { - return "AnswerInlineQuery{" + + return "AnswerCallbackQuery{" + "callbackQueryId='" + callbackQueryId + '\'' + ", text=" + text + ", showAlert=" + showAlert + '\'' + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java b/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java index 14da4fa7..c7254102 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java @@ -19,12 +19,12 @@ import java.io.IOException; public class ForwardMessage extends BotApiMethod { public static final String PATH = "forwardmessage"; - public static final String CHATID_FIELD = "chat_id"; - public static final String FROMCHATID_FIELD = "from_chat_id"; - public static final String MESSAGEID_FIELD = "message_id"; - public static final String DISABLENOTIFICATION_FIELD = "disable_notification"; + private static final String CHATID_FIELD = "chat_id"; + private static final String FROMCHATID_FIELD = "from_chat_id"; + private static final String MESSAGEID_FIELD = "message_id"; + private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels) - private Integer fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id + private String fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id private Integer messageId; ///< Unique message identifier /** * Optional. Sends the message silently. @@ -47,11 +47,17 @@ public class ForwardMessage extends BotApiMethod { return this; } - public Integer getFromChatId() { + @Deprecated + public ForwardMessage setFromChatId(Integer fromChatId) { + this.fromChatId = fromChatId.toString(); + return this; + } + + public String getFromChatId() { return fromChatId; } - public ForwardMessage setFromChatId(Integer fromChatId) { + public ForwardMessage setFromChatId(String fromChatId) { this.fromChatId = fromChatId; return this; } @@ -82,7 +88,7 @@ public class ForwardMessage extends BotApiMethod { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(FROMCHATID_FIELD, fromChatId); + gen.writeStringField(FROMCHATID_FIELD, fromChatId); gen.writeNumberField(MESSAGEID_FIELD, messageId); if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java index 73648daf..a14a270f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java @@ -19,7 +19,7 @@ import java.io.IOException; * @date 20 of May of 2016 */ public class GetChatMember extends BotApiMethod { - public static final String PATH = "getChatAdministrators"; + public static final String PATH = "getChatMember"; private static final String CHATID_FIELD = "chat_id"; private static final String USERID_FIELD = "user_id"; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java index 3b350902..d75eb49f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java @@ -17,7 +17,7 @@ import java.io.IOException; * @date 20 of May of 2016 */ public class GetChatMemberCount extends BotApiMethod { - public static final String PATH = "getChatAdministrators"; + public static final String PATH = "getChatMembersCount"; private static final String CHATID_FIELD = "chat_id"; private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java index 2ce1f911..c1d53356 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java @@ -90,7 +90,7 @@ public class KickChatMember extends BotApiMethod { @Override public String toString() { - return "SendMessage{" + + return "KickChatMember{" + "chatId='" + chatId + '\'' + ", userId='" + userId + '}'; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java index 6c75940c..16381b69 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java @@ -86,7 +86,7 @@ public class UnbanChatMember extends BotApiMethod { @Override public String toString() { - return "SendMessage{" + + return "UnbanChatMember{" + "chatId='" + chatId + '\'' + ", userId='" + userId + '}'; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index 649906ca..e3e1afe8 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; +import java.io.InputStream; +import java.util.Objects; + /** * @author Ruben Bermudez * @version 1.0 @@ -27,17 +31,20 @@ public class SendAudio { private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender private String chatId; ///< Unique identifier for the chat to send the message to (or Username fro channels) private String audio; ///< Audio file to send. file_id as String to resend an audio that is already on the Telegram servers - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message /** * Optional. Sends the message silently. iOS users will not receive a notification, Android * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private String performer; ///< Optional. Performer of sent audio private String title; ///< Optional. Title of sent audio - private boolean isNewAudio; + + private boolean isNewAudio; ///< True to upload a new audio, false to use a fileId private String audioName; + private File newAudioFile; ///< New audio file + private InputStream newAudioStream; ///< New audio stream public SendAudio() { super(); @@ -82,7 +89,10 @@ public class SendAudio { * * @param audio Path to the new file in your server * @param audioName Name of the file itself + * + * @deprecated use {@link #setNewAudio(File)} or {@link #setNewAudio(InputStream)} instead. */ + @Deprecated public SendAudio setNewAudio(String audio, String audioName) { this.audio = audio; this.isNewAudio = true; @@ -90,22 +100,75 @@ public class SendAudio { return this; } + /** + * Use this method to set the audio to a new file + * + * @param file New audio file + */ + public SendAudio setNewAudio(File file) { + this.audio = file.getName(); + this.isNewAudio = true; + this.newAudioFile = file; + return this; + } + + public SendAudio setNewAudio(String audioName, InputStream inputStream) { + Objects.requireNonNull(audioName, "audioName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.audioName = audioName; + this.isNewAudio = true; + this.newAudioStream = inputStream; + return this; + } + + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendAudio setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendAudio setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendAudio setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendAudio setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendAudio setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendAudio setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public String getPerformer() { @@ -148,17 +211,24 @@ public class SendAudio { return audioName; } + public File getNewAudioFile() { + return newAudioFile; + } + + public InputStream getNewAudioStream() { + return newAudioStream; + } + @Override public String toString() { return "SendAudio{" + "chatId='" + chatId + '\'' + ", audio='" + audio + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", performer='" + performer + '\'' + ", title='" + title + '\'' + ", isNewAudio=" + isNewAudio + - ", audioName='" + audioName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java index 8e1e55bf..7ae28d9e 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import org.json.JSONObject; import org.telegram.telegrambots.Constants; +import org.telegram.telegrambots.api.methods.ActionType; import org.telegram.telegrambots.api.methods.BotApiMethod; import java.io.IOException; @@ -31,7 +32,7 @@ public class SendChatAction extends BotApiMethod { * videos 'record_audio' or 'upload_audio' for audio files 'upload_document' for general files, * 'find_location' for location data. */ - private String action; + private ActionType action; public String getChatId() { return chatId; @@ -42,12 +43,28 @@ public class SendChatAction extends BotApiMethod { return this; } + /** + * @deprecated + * @return Action type text + */ + @Deprecated public String getAction() { - return action; + return action.toString(); } - public SendChatAction setAction(String action) { + public void setAction(ActionType action) { this.action = action; + } + + /** + * @deprecated Use {@link #setAction(ActionType)} instead + * @param action Text of the action to create + * @return Reference to this same instance + * @throws IllegalArgumentException if action is not valid + */ + @Deprecated + public SendChatAction setAction(String action) throws IllegalArgumentException { + this.action = ActionType.GetActionType(action); return this; } @@ -76,7 +93,7 @@ public class SendChatAction extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(ACTION_FIELD, action); + gen.writeStringField(ACTION_FIELD, action.toString()); gen.writeEndObject(); } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java index 3fd86098..cef6aa93 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java @@ -38,8 +38,8 @@ public class SendContact extends BotApiMethod { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public String getChatId() { return chatId; @@ -50,22 +50,54 @@ public class SendContact extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendContact setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendContact setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendContact setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendContact setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendContact setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendContact setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableNotification() { @@ -134,11 +166,11 @@ public class SendContact extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -157,11 +189,11 @@ public class SendContact extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -175,13 +207,13 @@ public class SendContact extends BotApiMethod { @Override public String toString() { - return "SendLocation{" + + return "SendContact{" + "chatId='" + chatId + '\'' + ", phoneNumber=" + phoneNumber + ", firstName=" + firstName + ", lastName=" + lastName + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index dacf2bb2..493e566f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; +import java.io.InputStream; +import java.util.Objects; + /** * @author Ruben Bermudez * @version 1.0 @@ -25,11 +29,13 @@ public class SendDocument { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private boolean isNewDocument; + private boolean isNewDocument; ///< True to upload a new document, false to use a fileId private String documentName; + private File newDocumentFile; ///< New document file + private InputStream newDocumentStream; ///< New document stream public SendDocument() { super(); @@ -48,12 +54,27 @@ public class SendDocument { return document; } + /** + * Use this method to set the document to an document existing in Telegram system + * + * @param document File_id of the document to send + * @note The file_id must have already been received or sent by your bot + */ public SendDocument setDocument(String document) { this.document = document; this.isNewDocument = false; return this; } + /** + * Use this method to set the document to a new file + * + * @param document Path to the new file in your server + * @param documentName Name of the file itself + * + * @deprecated use {@link #setNewDocument(File)} or {@link #setNewDocument(InputStream)} instead. + */ + @Deprecated public SendDocument setNewDocument(String document, String documentName) { this.document = document; this.isNewDocument = true; @@ -61,6 +82,27 @@ public class SendDocument { return this; } + /** + * Use this method to set the document to a new file + * + * @param file New document file + */ + public SendDocument setNewDocument(File file) { + this.document = file.getName(); + this.isNewDocument = true; + this.newDocumentFile = file; + return this; + } + + public SendDocument setNewDocument(String documentName, InputStream inputStream) { + Objects.requireNonNull(documentName, "documentName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.documentName = documentName; + this.isNewDocument = true; + this.newDocumentStream = inputStream; + return this; + } + public boolean isNewDocument() { return isNewDocument; } @@ -69,15 +111,39 @@ public class SendDocument { return documentName; } - public Integer getReplayToMessageId() { - return replayToMessageId; + public File getNewDocumentFile() { + return newDocumentFile; } - public SendDocument setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; + public InputStream getNewDocumentStream() { + return newDocumentStream; + } + + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendDocument setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; return this; } + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated + public Integer getReplayToMessageId() { + return getReplyToMessageId(); + } + + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendDocument setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); + } + public Boolean getDisableNotification() { return disableNotification; } @@ -101,24 +167,39 @@ public class SendDocument { return this; } - public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; } - public SendDocument setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; + public SendDocument setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; return this; } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated + public ReplyKeyboard getReplayMarkup() { + return getReplyMarkup(); + } + + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendDocument setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); + } + @Override public String toString() { return "SendDocument{" + "chatId='" + chatId + '\'' + ", document='" + document + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewDocument=" + isNewDocument + - ", documentName='" + documentName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java index a9d2ee45..31f2701b 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java @@ -35,8 +35,8 @@ public class SendLocation extends BotApiMethod { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public String getChatId() { return chatId; @@ -65,22 +65,54 @@ public class SendLocation extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendLocation setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendLocation setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendLocation setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendLocation setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendLocation setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendLocation setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableNotification() { @@ -119,11 +151,11 @@ public class SendLocation extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -139,11 +171,11 @@ public class SendLocation extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -161,8 +193,8 @@ public class SendLocation extends BotApiMethod { "chatId='" + chatId + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java index 722b8f2a..b0f885bd 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java @@ -38,8 +38,8 @@ public class SendMessage extends BotApiMethod { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public SendMessage() { super(); @@ -63,22 +63,54 @@ public class SendMessage extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendMessage setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendMessage setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendMessage setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendMessage setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendMessage setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendMessage setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableWebPagePreview() { @@ -141,11 +173,11 @@ public class SendMessage extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -180,11 +212,11 @@ public class SendMessage extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -203,8 +235,8 @@ public class SendMessage extends BotApiMethod { ", text='" + text + '\'' + ", parseMode='" + parseMode + '\'' + ", disableWebPagePreview=" + disableWebPagePreview + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index fcb59daa..d4839fa7 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; +import java.io.InputStream; +import java.util.Objects; + /** * @author Ruben Bermudez * @version 1.0 @@ -25,12 +29,13 @@ public class SendPhoto { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< 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 - + private File newPhotoFile; // New photo file + private InputStream newPhotoStream; // New photo stream public SendPhoto() { super(); @@ -64,22 +69,54 @@ public class SendPhoto { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendPhoto setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendPhoto setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendPhoto setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendPhoto setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendPhoto setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendPhoto setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public boolean isNewPhoto() { @@ -90,6 +127,14 @@ public class SendPhoto { return photoName; } + public File getNewPhotoFile() { + return newPhotoFile; + } + + public InputStream getNewPhotoStream() { + return newPhotoStream; + } + public Boolean getDisableNotification() { return disableNotification; } @@ -104,6 +149,15 @@ public class SendPhoto { return this; } + /** + * Use this method to set the photo to a new file + * + * @param photo Path to the new file in your server + * @param photoName Name of the file itself + * + * @deprecated use {@link #setNewPhoto(File)} or {@link #setNewPhoto(InputStream)} instead. + */ + @Deprecated public SendPhoto setNewPhoto(String photo, String photoName) { this.photo = photo; this.isNewPhoto = true; @@ -111,16 +165,31 @@ public class SendPhoto { return this; } + public SendPhoto setNewPhoto(File file) { + this.photo = file.getName(); + this.newPhotoFile = file; + this.isNewPhoto = true; + return this; + } + + public SendPhoto setNewPhoto(String photoName, InputStream inputStream) { + Objects.requireNonNull(photoName, "photoName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.photoName = photoName; + this.newPhotoStream = inputStream; + this.isNewPhoto = true; + return this; + } + @Override public String toString() { return "SendPhoto{" + "chatId='" + chatId + '\'' + ", photo='" + photo + '\'' + ", caption='" + caption + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewPhoto=" + isNewPhoto + - ", photoName='" + photoName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index b9c9cd9a..2a06c9fb 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; +import java.io.InputStream; +import java.util.Objects; + /** * @author Ruben Bermudez * @version 1.0 @@ -23,11 +27,13 @@ public class SendSticker { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private boolean isNewSticker; + private boolean isNewSticker; ///< True to upload a new sticker, false to use a fileId private String stickerName; + private File newStickerFile; ///< New sticker file + private InputStream newStickerStream; ///< New sticker stream public SendSticker() { super(); @@ -52,24 +58,65 @@ public class SendSticker { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendSticker setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendSticker setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendSticker setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendSticker setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendSticker setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendSticker setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } + /** + * Use this method to set the sticker to a new file + * + * @param sticker Path to the new file in your server + * @param stickerName Name of the file itself + * + * @deprecated use {@link #setNewSticker(File)} or {@link #setNewSticker(InputStream)} instead. + */ + @Deprecated public SendSticker setSticker(String sticker, String stickerName) { this.sticker = sticker; this.isNewSticker = true; @@ -77,6 +124,22 @@ public class SendSticker { return this; } + public SendSticker setNewSticker(File file) { + this.sticker = file.getName(); + this.isNewSticker = true; + this.newStickerFile = file; + return this; + } + + public SendSticker setNewSticker(String stickerName, InputStream inputStream) { + Objects.requireNonNull(stickerName, "stickerName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.stickerName = stickerName; + this.isNewSticker = true; + this.newStickerStream = inputStream; + return this; + } + public Boolean getDisableNotification() { return disableNotification; } @@ -99,15 +162,22 @@ public class SendSticker { return stickerName; } + public File getNewStickerFile() { + return newStickerFile; + } + + public InputStream getNewStickerStream() { + return newStickerStream; + } + @Override public String toString() { return "SendSticker{" + "chatId='" + chatId + '\'' + ", sticker='" + sticker + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewSticker=" + isNewSticker + - ", stickerName='" + stickerName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java index a2512132..5e57207c 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java @@ -42,8 +42,8 @@ public class SendVenue extends BotApiMethod { private Boolean disableNotification; private String address; ///< Address of the venue private String foursquareId; ///< Optional. Foursquare identifier of the venue - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public String getChatId() { return chatId; @@ -72,22 +72,54 @@ public class SendVenue extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendVenue setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendVenue setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendVenue setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendVenue setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendVenue setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendVenue setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableNotification() { @@ -158,11 +190,11 @@ public class SendVenue extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -183,11 +215,11 @@ public class SendVenue extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -201,15 +233,15 @@ public class SendVenue extends BotApiMethod { @Override public String toString() { - return "SendLocation{" + + return "SendVenue{" + "chatId='" + chatId + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + ", title=" + title + ", address=" + address + ", foursquareId=" + foursquareId + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index 135ad939..f354f503 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; +import java.io.InputStream; +import java.util.Objects; + /** * @author Ruben Bermudez * @version 1.0 @@ -32,11 +36,13 @@ public class SendVideo { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< 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 + private File newVideoFile; ///< New video file + private InputStream newVideoStream; ///< New video stream public SendVideo() { super(); @@ -79,22 +85,54 @@ public class SendVideo { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendVideo setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendVideo setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendVideo setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendVideo setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendVideo setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendVideo setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public boolean isNewVideo() { @@ -105,6 +143,14 @@ public class SendVideo { return videoName; } + public File getNewVideoFile() { + return newVideoFile; + } + + public InputStream getNewVideoStream() { + return newVideoStream; + } + public Boolean getDisableNotification() { return disableNotification; } @@ -137,6 +183,15 @@ public class SendVideo { return this; } + /** + * Use this method to set the video to a new file + * + * @param video Path to the new file in your server + * @param videoName Name of the file itself + * + * @deprecated use {@link #setNewVideo(File)} or {@link #setNewVideo(InputStream)} instead. + */ + @Deprecated public SendVideo setNewVideo(String video, String videoName) { this.video = video; this.isNewVideo = true; @@ -144,6 +199,22 @@ public class SendVideo { return this; } + public SendVideo setNewVideo(File file) { + this.video = file.getName(); + this.isNewVideo = true; + this.newVideoFile = file; + return this; + } + + public SendVideo setNewVideo(String videoName, InputStream inputStream) { + Objects.requireNonNull(videoName, "videoName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.videoName = videoName; + this.isNewVideo = true; + this.newVideoStream = inputStream; + return this; + } + @Override public String toString() { return "SendVideo{" + @@ -151,10 +222,9 @@ public class SendVideo { ", video='" + video + '\'' + ", duration=" + duration + ", caption='" + caption + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewVideo=" + isNewVideo + - ", videoName='" + videoName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index fb01b1ea..3c8a865f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; +import java.io.InputStream; +import java.util.Objects; + /** * @author Ruben Bermudez * @version 1.0 @@ -14,24 +18,27 @@ public class SendVoice { public static final String PATH = "sendvoice"; public static final String CHATID_FIELD = "chat_id"; - public static final String AUDIO_FIELD = "audio"; + public static final String VOICE_FIELD = "voice"; public static final String DISABLENOTIFICATION_FIELD = "disable_notification"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String DURATION_FIELD = "duration"; + private String chatId; ///< Unique identifier for the chat sent message to (Or username for channels) - private String audio; ///< Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data. + private String voice; ///< Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data. /** * Optional. Sends the message silently. iOS users will not receive a notification, Android * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private Integer duration; ///< Optional. Duration of sent audio in seconds private boolean isNewVoice; ///< True to upload a new voice note, false to use a fileId private String voiceName; ///< Name of the voice note + private File newVoiceFile; ///< New voice note file + private InputStream newVoiceStream; ///< New voice note stream public SendVoice() { super(); @@ -41,9 +48,9 @@ public class SendVoice { public String toString() { return "SendVoice{" + "chatId='" + chatId + '\'' + - ", audio='" + audio + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", voice='" + voice + '\'' + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", duration=" + duration + '}'; } @@ -71,39 +78,130 @@ public class SendVoice { return this; } + public String getVoice() { + return voice; + } + + /** + * @deprecated Use {@link #getVoice()} instead + */ + @Deprecated public String getAudio() { - return audio; + return voice; } - public SendVoice setAudio(String audio) { - this.audio = audio; + public SendVoice setVoice(String voice) { + this.voice = voice; this.isNewVoice = false; return this; } - public SendVoice setNewAudio(String audio, String audioName) { - this.audio = audio; + /** + * @deprecated Use {@link #setVoice(String)} instead + */ + @Deprecated + public SendVoice setAudio(String voice) { + this.voice = voice; this.isNewVoice = false; - this.voiceName = audioName; return this; } + /** + * Use this method to set the voice to a new file + * + * @param voice Path to the new file in your server + * @param voiceName Name of the file itself + * + * @deprecated use {@link #setNewVoice(File)} or {@link #setNewVoice(InputStream)} instead. + */ + @Deprecated + public SendVoice setNewVoice(String voice, String voiceName) { + this.voice = voice; + this.isNewVoice = false; + this.voiceName = voiceName; + return this; + } + + /** + * Use this method to set the voice to a new file + * + * @param voice Path to the new file in your server + * @param voiceName Name of the file itself + * + * @deprecated use {@link #setNewVoice(File)} or {@link #setNewVoice(InputStream)} instead. + */ + @Deprecated + public SendVoice setNewAudio(String voice, String voiceName) { + this.voice = voice; + this.isNewVoice = false; + this.voiceName = voiceName; + return this; + } + + public SendVoice setNewVoice(File file) { + this.voice = file.getName(); + this.isNewVoice = true; + this.newVoiceFile = file; + return this; + } + + public SendVoice setNewVoice(String voiceName, InputStream inputStream) { + Objects.requireNonNull(voiceName, "voiceName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.voiceName = voiceName; + this.isNewVoice = true; + this.newVoiceStream = inputStream; + return this; + } + + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendVoice setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendVoice setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendVoice setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendVoice setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendVoice setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendVoice setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Integer getDuration() { @@ -122,4 +220,12 @@ public class SendVoice { public String getVoiceName() { return voiceName; } + + public File getNewVoiceFile() { + return newVoiceFile; + } + + public InputStream getNewVoiceStream() { + return newVoiceStream; + } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java b/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java new file mode 100644 index 00000000..ef89fc24 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java @@ -0,0 +1,64 @@ +package org.telegram.telegrambots.api.methods.updates; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; + +import org.json.JSONObject; +import org.telegram.telegrambots.Constants; +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.WebhookInfo; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.1 + * @brief Return webhook information for current bot. + * + * If webhook is not configured, this method raise an exception + * + * @date 12 of August of 2016 + */ +public class GetWebhookInfo extends BotApiMethod { + public static final String PATH = "getwebhookinfo"; + + public GetWebhookInfo() { + } + + @Override + public String toString() { + return "GetWebhookInfo{}"; + } + + @Override + public String getPath() { + return PATH; + } + + @Override + public WebhookInfo deserializeResponse(JSONObject answer) { + if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { + return new WebhookInfo(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + } + return null; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(METHOD_FIELD, PATH); + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } + + @Override + public JSONObject toJson() { + return new JSONObject(); + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java b/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java index af25cc10..6487d28d 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java @@ -107,7 +107,7 @@ public class CallbackQuery implements IBotApiObject { @Override public String toString() { - return "Contact{" + + return "CallbackQuery{" + "id='" + id + '\'' + ", from='" + from + '\'' + ", message='" + message + '\'' + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Chat.java b/src/main/java/org/telegram/telegrambots/api/objects/Chat.java index 065aac32..18b77d8f 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Chat.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/Chat.java @@ -28,6 +28,12 @@ public class Chat implements IBotApiObject { private static final String CHANNELCHATTYPE = "channel"; private static final String SUPERGROUPCHATTYPE = "supergroup"; @JsonProperty(ID_FIELD) + /** + * Unique identifier for this chat. + * This number may be greater than 32 bits and some programming languages may + * have difficulty/silent defects in interpreting it. But it smaller than 52 bits, + * so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + */ private Long id; ///< Unique identifier for this chat, not exciding 1e13 by absolute value @JsonProperty(TYPE_FIELD) private String type; ///< Type of the chat, one of “private”, “group” or “channel” diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Message.java b/src/main/java/org/telegram/telegrambots/api/objects/Message.java index b5029148..7cc91759 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Message.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/Message.java @@ -111,12 +111,40 @@ public class Message implements IBotApiObject { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters @JsonProperty(SUPERGROUPCREATED_FIELD) - private Boolean superGroupCreated; ///< Optional. Informs that the supergroup has been created + /** + * Optional. Service message: the supergroup has been created. + * This field can‘t be received in a message coming through updates, + * because bot can’t be a member of a supergroup when it is created. + * It can only be found in reply_to_message + * if someone replies to a very first message in a directly created supergroup. + */ + private Boolean superGroupCreated; @JsonProperty(CHANNELCHATCREATED_FIELD) - private Boolean channelChatCreated; ///< Optional. Informs that the channel has been created + /** + * Optional. Service message: the channel has been created. + * This field can‘t be received in a message coming through updates, + * because bot can’t be a member of a channel when it is created. + * It can only be found in reply_to_message if someone + * replies to a very first message in a channel. + */ + private Boolean channelChatCreated; @JsonProperty(MIGRATETOCHAT_FIELD) + /** + * Optional. The group has been migrated to a supergroup with the specified identifier. + * This number may be greater than 32 bits and some programming languages + * may have difficulty/silent defects in interpreting it. + * But it smaller than 52 bits, so a signed 64 bit integer or double-precision + * float type are safe for storing this identifier. + */ private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value @JsonProperty(MIGRATEFROMCHAT_FIELD) + /** + * Optional. The supergroup has been migrated from a group with the specified identifier. + * This number may be greater than 32 bits and some programming languages + * may have difficulty/silent defects in interpreting it. + * But it smaller than 52 bits, so a signed 64 bit integer or double-precision + * float type are safe for storing this identifier. + */ private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value @JsonProperty(EDITDATE_FIELD) private Integer editDate; ///< Optional. Date the message was last edited in Unix time @@ -381,6 +409,18 @@ public class Message implements IBotApiObject { return text != null && !text.isEmpty(); } + public boolean isCommand() { + if (hasText() && entities != null) { + for (MessageEntity entity : entities) { + if (entity != null && entity.getOffset() == 0 && + EntityType.BOTCOMMAND.equals(entity.getType())) { + return true; + } + } + } + return false; + } + public boolean hasDocument() { return this.document != null; } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java b/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java index fc8fefa9..52ae50f5 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java @@ -119,7 +119,7 @@ public class MessageEntity implements IBotApiObject { @Override public String toString() { - return "PhotoSize{" + + return "MessageEntity{" + "type='" + type + '\'' + ", offset=" + offset + ", length=" + length + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java b/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java new file mode 100644 index 00000000..63fc70f9 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java @@ -0,0 +1,94 @@ +package org.telegram.telegrambots.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; + +import org.json.JSONObject; +import org.telegram.telegrambots.api.interfaces.IBotApiObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.1 + * @brief Information about configured webhook + * @date 12 of August of 2016 + */ +public class WebhookInfo implements IBotApiObject { + + private static final String URL_FIELD = "url"; + private static final String HASCUSTOMCERTIFICATE_FIELD = "has_custom_certificate"; + private static final String PENDINGUPDATESCOUNT_FIELD = "pending_updates_count"; + private static final String LASTERRORDATE_FIELD = "last_error_date"; + private static final String LASTERRORMESSAGE_FIELD = "last_error_message"; + + @JsonProperty(URL_FIELD) + private String url; ///< Url of the webhook + @JsonProperty(HASCUSTOMCERTIFICATE_FIELD) + private Boolean hasCustomCertificate; ///< True if the webhook use a self signed certificate + @JsonProperty(PENDINGUPDATESCOUNT_FIELD) + private Integer pendingUpdatesCount; ///< Number of updates pending to be delivered + @JsonProperty(LASTERRORDATE_FIELD) + private Integer lastErrorDate; ///< Optional. Date of that error + @JsonProperty(LASTERRORMESSAGE_FIELD) + private String lastErrorMessage; ///< Optional. Error message + + + public WebhookInfo() { + } + + public WebhookInfo(JSONObject object) { + url = object.getString(URL_FIELD); + hasCustomCertificate = object.getBoolean(HASCUSTOMCERTIFICATE_FIELD); + pendingUpdatesCount = object.getInt(PENDINGUPDATESCOUNT_FIELD); + if (object.has(LASTERRORDATE_FIELD)) { + lastErrorDate = object.getInt(LASTERRORDATE_FIELD); + } + if (object.has(LASTERRORMESSAGE_FIELD)) { + lastErrorMessage = object.getString(LASTERRORMESSAGE_FIELD); + } + + } + + public String getUrl() { + return url; + } + + public boolean isHasCustomCertificate() { + return hasCustomCertificate; + } + + public int getPendingUpdatesCount() { + return pendingUpdatesCount; + } + + public int getLastErrorDate() { + return lastErrorDate; + } + + public String getLastErrorMessage() { + return lastErrorMessage; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(URL_FIELD, url); + gen.writeBooleanField(HASCUSTOMCERTIFICATE_FIELD, hasCustomCertificate); + gen.writeNumberField(PENDINGUPDATESCOUNT_FIELD, pendingUpdatesCount); + if (lastErrorDate != null) { + gen.writeNumberField(LASTERRORDATE_FIELD, lastErrorDate); + } + if (lastErrorMessage != null) { + gen.writeStringField(LASTERRORMESSAGE_FIELD, lastErrorMessage); + } + gen.writeEndObject(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java index d90f3acb..7bbc7549 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java @@ -107,9 +107,9 @@ public class InlineQueryResultVoice implements InlineQueryResult { JSONObject jsonObject = new JSONObject(); jsonObject.put(TYPE_FIELD, type); jsonObject.put(ID_FIELD, this.id); - jsonObject.put(VOICE_DURATION_FIELD, voiceUrl); + jsonObject.put(VOICEURL_FIELD, voiceUrl); if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); + jsonObject.put(TITLE_FIELD, title); } if (voiceDuration != null) { jsonObject.put(VOICE_DURATION_FIELD, voiceDuration); @@ -130,7 +130,7 @@ public class InlineQueryResultVoice implements InlineQueryResult { gen.writeStringField(ID_FIELD, id); gen.writeStringField(VOICEURL_FIELD, voiceUrl); if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); + gen.writeStringField(TITLE_FIELD, title); } if (voiceDuration != null) { gen.writeNumberField(VOICE_DURATION_FIELD, voiceDuration); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java index a53ca68c..08a504b3 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java @@ -87,7 +87,7 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { jsonObject.put(ID_FIELD, id); jsonObject.put(AUDIO_FILE_ID_FIELD, audioFileId); if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java index 21634824..e19cd3ee 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java @@ -128,7 +128,7 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { jsonObject.put(DESCRIPTION_FIELD, this.description); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java index c2ad9280..04790156 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java @@ -115,7 +115,7 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { jsonObject.put(CAPTION_FIELD, this.caption); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java index 00112f0b..df7dbbfc 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java @@ -115,7 +115,7 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { jsonObject.put(CAPTION_FIELD, this.caption); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java index a5a8306c..489d3a09 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java @@ -130,7 +130,7 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { jsonObject.put(CAPTION_FIELD, this.caption); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java index 76556a71..c52bf668 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java @@ -87,7 +87,7 @@ public class InlineQueryResultCachedSticker implements InlineQueryResult { jsonObject.put(ID_FIELD, this.id); jsonObject.put(STICKER_FILE_ID_FIELD, stickerFileId); if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java index d187fc5a..565f9943 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java @@ -130,7 +130,7 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { jsonObject.put(DESCRIPTION_FIELD, this.description); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java index 810656b6..b770252c 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java @@ -102,7 +102,7 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { jsonObject.put(TITLE_FIELD, this.title); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java index f086dc89..b03c2d98 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java @@ -19,7 +19,6 @@ import java.io.IOException; * @date 22 of June of 2015 */ public class ForceReplyKeyboard implements ReplyKeyboard { - private static final String FORCEREPLY_FIELD = "force_reply"; private static final String SELECTIVE_FIELD = "selective"; /** @@ -55,11 +54,6 @@ public class ForceReplyKeyboard implements ReplyKeyboard { return forceReply; } - public ForceReplyKeyboard setForceReply(Boolean forceReply) { - this.forceReply = forceReply; - return this; - } - public Boolean getSelective() { return selective; } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java index 2b5f9529..b47e5fc4 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java @@ -19,7 +19,6 @@ import java.io.IOException; * @date 20 of June of 2015 */ public class ReplyKeyboardHide implements ReplyKeyboard { - private static final String HIDEKEYBOARD_FIELD = "hide_keyboard"; private static final String SELECTIVE_FIELD = "selective"; @JsonProperty(HIDEKEYBOARD_FIELD) @@ -34,7 +33,7 @@ public class ReplyKeyboardHide implements ReplyKeyboard { public ReplyKeyboardHide() { super(); - this.selective = true; + this.hideKeyboard = true; } public ReplyKeyboardHide(JSONObject jsonObject) { @@ -51,11 +50,6 @@ public class ReplyKeyboardHide implements ReplyKeyboard { return hideKeyboard; } - public ReplyKeyboardHide setHideKeyboard(Boolean hideKeyboard) { - this.hideKeyboard = hideKeyboard; - return this; - } - public Boolean getSelective() { return selective; } diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 703bc816..c88b0575 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.bots; import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; @@ -43,6 +44,7 @@ import org.telegram.telegrambots.api.methods.send.SendSticker; import org.telegram.telegrambots.api.methods.send.SendVenue; import org.telegram.telegrambots.api.methods.send.SendVideo; import org.telegram.telegrambots.api.methods.send.SendVoice; +import org.telegram.telegrambots.api.methods.updates.GetWebhookInfo; import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageCaption; import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageReplyMarkup; import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText; @@ -52,6 +54,7 @@ import org.telegram.telegrambots.api.objects.File; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.User; import org.telegram.telegrambots.api.objects.UserProfilePhotos; +import org.telegram.telegrambots.api.objects.WebhookInfo; import org.telegram.telegrambots.updateshandlers.SentCallback; import java.io.IOException; @@ -74,19 +77,28 @@ import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; */ @SuppressWarnings("unused") public abstract class AbsSender { + private static final ContentType TEXT_PLAIN_CONTENT_TYPE = ContentType.create("text/plain", StandardCharsets.UTF_8); + private final ExecutorService exe = Executors.newSingleThreadExecutor(); + private final BotOptions options; private volatile CloseableHttpClient httpclient; private volatile RequestConfig requestConfig; private static final int SOCKET_TIMEOUT = 75 * 1000; - public AbsSender() { + AbsSender(BotOptions options) { + this.options = options; httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) .setMaxConnTotal(100) .build(); - requestConfig = RequestConfig.copy(RequestConfig.custom().build()) - .setSocketTimeout(SOCKET_TIMEOUT) + + RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()); + if (options.hasProxy()) { + configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + } + + requestConfig = configBuilder.setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); } @@ -97,168 +109,177 @@ public abstract class AbsSender { */ public abstract String getBotToken(); + public final BotOptions getOptions() { + return options; + } + // Send Requests - public Message sendMessage(SendMessage sendMessage) throws TelegramApiException { + public final Message sendMessage(SendMessage sendMessage) throws TelegramApiException { if (sendMessage == null) { throw new TelegramApiException("Parameter sendMessage can not be null"); } - return (Message) sendApiMethod(sendMessage); + return sendApiMethod(sendMessage); } - public Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { + public final Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { if (answerInlineQuery == null) { throw new TelegramApiException("Parameter answerInlineQuery can not be null"); } - return (Boolean) sendApiMethod(answerInlineQuery); + return sendApiMethod(answerInlineQuery); } - public Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { + public final Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { if (sendChatAction == null) { throw new TelegramApiException("Parameter sendChatAction can not be null"); } - return (Boolean) sendApiMethod(sendChatAction); + return sendApiMethod(sendChatAction); } - public Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { + public final Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { if (forwardMessage == null) { throw new TelegramApiException("Parameter forwardMessage can not be null"); } - return (Message) sendApiMethod(forwardMessage); + return sendApiMethod(forwardMessage); } - public Message sendLocation(SendLocation sendLocation) throws TelegramApiException { + public final Message sendLocation(SendLocation sendLocation) throws TelegramApiException { if (sendLocation == null) { throw new TelegramApiException("Parameter sendLocation can not be null"); } - return (Message) sendApiMethod(sendLocation); + return sendApiMethod(sendLocation); } - public Message sendVenue(SendVenue sendVenue) throws TelegramApiException { + public final Message sendVenue(SendVenue sendVenue) throws TelegramApiException { if (sendVenue == null) { throw new TelegramApiException("Parameter sendVenue can not be null"); } - return (Message) sendApiMethod(sendVenue); + return sendApiMethod(sendVenue); } - public Message sendContact(SendContact sendContact) throws TelegramApiException { + public final Message sendContact(SendContact sendContact) throws TelegramApiException { if (sendContact == null) { throw new TelegramApiException("Parameter sendContact can not be null"); } - return (Message) sendApiMethod(sendContact); + return sendApiMethod(sendContact); } - public Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { + public final Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { if (kickChatMember == null) { throw new TelegramApiException("Parameter kickChatMember can not be null"); } - return (Boolean) sendApiMethod(kickChatMember); + return sendApiMethod(kickChatMember); } - public Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { + public final Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { if (unbanChatMember == null) { throw new TelegramApiException("Parameter unbanChatMember can not be null"); } - return (Boolean) sendApiMethod(unbanChatMember); + return sendApiMethod(unbanChatMember); } - public Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { + public final Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { if (leaveChat == null) { throw new TelegramApiException("Parameter leaveChat can not be null"); } - return (Boolean) sendApiMethod(leaveChat); + return sendApiMethod(leaveChat); } - public Chat getChat(GetChat getChat) throws TelegramApiException { + public final Chat getChat(GetChat getChat) throws TelegramApiException { if (getChat == null) { throw new TelegramApiException("Parameter getChat can not be null"); } - return (Chat) sendApiMethod(getChat); + return sendApiMethod(getChat); } - public List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { + public final List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { if (getChatAdministrators == null) { throw new TelegramApiException("Parameter getChatAdministrators can not be null"); } - return (ArrayList) sendApiMethod(getChatAdministrators); + return sendApiMethod(getChatAdministrators); } - public ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { + public final ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { if (getChatMember == null) { throw new TelegramApiException("Parameter getChatMember can not be null"); } - return (ChatMember) sendApiMethod(getChatMember); + return sendApiMethod(getChatMember); } - public Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { + public final Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { if (getChatMemberCount == null) { throw new TelegramApiException("Parameter getChatMemberCount can not be null"); } - return (Integer) sendApiMethod(getChatMemberCount); + return sendApiMethod(getChatMemberCount); } - public Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { + public final Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { if (editMessageText == null) { throw new TelegramApiException("Parameter editMessageText can not be null"); } - return (Message) sendApiMethod(editMessageText); + return sendApiMethod(editMessageText); } - public Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { + public final Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { if (editMessageCaption == null) { throw new TelegramApiException("Parameter editMessageCaption can not be null"); } - return (Message) sendApiMethod(editMessageCaption); + return sendApiMethod(editMessageCaption); } - public Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { + public final Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { if (editMessageReplyMarkup == null) { throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); } - return (Message) sendApiMethod(editMessageReplyMarkup); + return sendApiMethod(editMessageReplyMarkup); } - public Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { + public final Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { if (answerCallbackQuery == null) { throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); } - return (Boolean) sendApiMethod(answerCallbackQuery); + return sendApiMethod(answerCallbackQuery); } - public UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { + public final UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { if (getUserProfilePhotos == null) { throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); } - return (UserProfilePhotos) sendApiMethod(getUserProfilePhotos); + return sendApiMethod(getUserProfilePhotos); } - public File getFile(GetFile getFile) throws TelegramApiException{ + public final File getFile(GetFile getFile) throws TelegramApiException{ if(getFile == null){ throw new TelegramApiException("Parameter getFile can not be null"); } else if(getFile.getFileId() == null){ throw new TelegramApiException("Attribute file_id in parameter getFile can not be null"); } - return (File) sendApiMethod(getFile); + return sendApiMethod(getFile); } - public User getMe() throws TelegramApiException { + public final User getMe() throws TelegramApiException { GetMe getMe = new GetMe(); - return (User) sendApiMethod(getMe); + return sendApiMethod(getMe); + } + + public final WebhookInfo getWebhookInfo() throws TelegramApiException { + GetWebhookInfo getWebhookInfo = new GetWebhookInfo(); + return sendApiMethod(getWebhookInfo); } // Send Requests Async - public void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { + public final void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { if (sendMessage == null) { throw new TelegramApiException("Parameter sendMessage can not be null"); } @@ -270,7 +291,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendMessage, sentCallback); } - public void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback sentCallback) throws TelegramApiException { + public final void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback sentCallback) throws TelegramApiException { if (answerInlineQuery == null) { throw new TelegramApiException("Parameter answerInlineQuery can not be null"); } @@ -282,7 +303,7 @@ public abstract class AbsSender { sendApiMethodAsync(answerInlineQuery, sentCallback); } - public void sendChatActionAsync(SendChatAction sendChatAction, SentCallback sentCallback) throws TelegramApiException { + public final void sendChatActionAsync(SendChatAction sendChatAction, SentCallback sentCallback) throws TelegramApiException { if (sendChatAction == null) { throw new TelegramApiException("Parameter sendChatAction can not be null"); } @@ -294,7 +315,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendChatAction, sentCallback); } - public void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback sentCallback) throws TelegramApiException { + public final void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback sentCallback) throws TelegramApiException { if (forwardMessage == null) { throw new TelegramApiException("Parameter forwardMessage can not be null"); } @@ -306,7 +327,7 @@ public abstract class AbsSender { sendApiMethodAsync(forwardMessage, sentCallback); } - public void sendLocationAsync(SendLocation sendLocation, SentCallback sentCallback) throws TelegramApiException { + public final void sendLocationAsync(SendLocation sendLocation, SentCallback sentCallback) throws TelegramApiException { if (sendLocation == null) { throw new TelegramApiException("Parameter sendLocation can not be null"); } @@ -318,7 +339,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendLocation, sentCallback); } - public void sendVenueAsync(SendVenue sendVenue, SentCallback sentCallback) throws TelegramApiException { + public final void sendVenueAsync(SendVenue sendVenue, SentCallback sentCallback) throws TelegramApiException { if (sendVenue == null) { throw new TelegramApiException("Parameter sendVenue can not be null"); } @@ -330,7 +351,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendVenue, sentCallback); } - public void sendContactAsync(SendContact sendContact, SentCallback sentCallback) throws TelegramApiException { + public final void sendContactAsync(SendContact sendContact, SentCallback sentCallback) throws TelegramApiException { if (sendContact == null) { throw new TelegramApiException("Parameter sendContact can not be null"); } @@ -341,7 +362,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendContact, sentCallback); } - public void kickMemberAsync(KickChatMember kickChatMember, SentCallback sentCallback) throws TelegramApiException { + public final void kickMemberAsync(KickChatMember kickChatMember, SentCallback sentCallback) throws TelegramApiException { if (kickChatMember == null) { throw new TelegramApiException("Parameter kickChatMember can not be null"); } @@ -352,7 +373,7 @@ public abstract class AbsSender { sendApiMethodAsync(kickChatMember, sentCallback); } - public void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback sentCallback) throws TelegramApiException { + public final void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback sentCallback) throws TelegramApiException { if (unbanChatMember == null) { throw new TelegramApiException("Parameter unbanChatMember can not be null"); } @@ -363,7 +384,7 @@ public abstract class AbsSender { sendApiMethodAsync(unbanChatMember, sentCallback); } - public void leaveChatAsync(LeaveChat leaveChat, SentCallback sentCallback) throws TelegramApiException { + public final void leaveChatAsync(LeaveChat leaveChat, SentCallback sentCallback) throws TelegramApiException { if (leaveChat == null) { throw new TelegramApiException("Parameter leaveChat can not be null"); } @@ -373,7 +394,7 @@ public abstract class AbsSender { sendApiMethodAsync(leaveChat, sentCallback); } - public void getChatAsync(GetChat getChat, SentCallback sentCallback) throws TelegramApiException { + public final void getChatAsync(GetChat getChat, SentCallback sentCallback) throws TelegramApiException { if (getChat == null) { throw new TelegramApiException("Parameter getChat can not be null"); } @@ -383,7 +404,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChat, sentCallback); } - public void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback> sentCallback) throws TelegramApiException { + public final void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback> sentCallback) throws TelegramApiException { if (getChatAdministrators == null) { throw new TelegramApiException("Parameter getChatAdministrators can not be null"); } @@ -393,7 +414,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChatAdministrators, sentCallback); } - public void getChatMemberAsync(GetChatMember getChatMember, SentCallback sentCallback) throws TelegramApiException { + public final void getChatMemberAsync(GetChatMember getChatMember, SentCallback sentCallback) throws TelegramApiException { if (getChatMember == null) { throw new TelegramApiException("Parameter getChatMember can not be null"); } @@ -403,7 +424,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChatMember, sentCallback); } - public void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback sentCallback) throws TelegramApiException { + public final void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback sentCallback) throws TelegramApiException { if (getChatMemberCount == null) { throw new TelegramApiException("Parameter getChatMemberCount can not be null"); } @@ -414,8 +435,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChatMemberCount, sentCallback); } - - public void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { + public final void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { if (editMessageText == null) { throw new TelegramApiException("Parameter editMessageText can not be null"); } @@ -426,7 +446,7 @@ public abstract class AbsSender { sendApiMethodAsync(editMessageText, sentCallback); } - public void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback sentCallback) throws TelegramApiException { + public final void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback sentCallback) throws TelegramApiException { if (editMessageCaption == null) { throw new TelegramApiException("Parameter editMessageCaption can not be null"); } @@ -437,7 +457,7 @@ public abstract class AbsSender { sendApiMethodAsync(editMessageCaption, sentCallback); } - public void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback sentCallback) throws TelegramApiException { + public final void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback sentCallback) throws TelegramApiException { if (editMessageReplyMarkup == null) { throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); } @@ -448,7 +468,7 @@ public abstract class AbsSender { sendApiMethodAsync(editMessageReplyMarkup, sentCallback); } - public void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback sentCallback) throws TelegramApiException { + public final void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback sentCallback) throws TelegramApiException { if (answerCallbackQuery == null) { throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); } @@ -459,7 +479,7 @@ public abstract class AbsSender { sendApiMethodAsync(answerCallbackQuery, sentCallback); } - public void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback sentCallback) throws TelegramApiException { + public final void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback sentCallback) throws TelegramApiException { if (getUserProfilePhotos == null) { throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); } @@ -471,7 +491,7 @@ public abstract class AbsSender { sendApiMethodAsync(getUserProfilePhotos, sentCallback); } - public void getFileAsync(GetFile getFile, SentCallback sentCallback) throws TelegramApiException { + public final void getFileAsync(GetFile getFile, SentCallback sentCallback) throws TelegramApiException { if (getFile == null) { throw new TelegramApiException("Parameter getFile can not be null"); } else if (getFile.getFileId() == null) { @@ -481,7 +501,7 @@ public abstract class AbsSender { sendApiMethodAsync(getFile, sentCallback); } - public void getMeAsync(SentCallback sentCallback) throws TelegramApiException { + public final void getMeAsync(SentCallback sentCallback) throws TelegramApiException { if (sentCallback == null) { throw new TelegramApiException("Parameter sentCallback can not be null"); } @@ -490,9 +510,18 @@ public abstract class AbsSender { sendApiMethodAsync(getMe, sentCallback); } + public final void getWebhookInfoAsync(SentCallback sentCallback) throws TelegramApiException { + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + GetWebhookInfo getWebhookInfo = new GetWebhookInfo(); + sendApiMethodAsync(getWebhookInfo, sentCallback); + } + // Specific Send Requests - public Message sendDocument(SendDocument sendDocument) throws TelegramApiException { + public final Message sendDocument(SendDocument sendDocument) throws TelegramApiException { String responseContent; try { @@ -502,15 +531,21 @@ public abstract class AbsSender { if (sendDocument.isNewDocument()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId()); - builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); - if (sendDocument.getReplayMarkup() != null) { - builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString()); + if (sendDocument.getNewDocumentFile() != null) { + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentFile()); + } else if (sendDocument.getNewDocumentStream() != null) { + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentStream(), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); + } else { + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); } - if (sendDocument.getReplayToMessageId() != null) { - builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString()); + if (sendDocument.getReplyMarkup() != null) { + builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendDocument.getReplyToMessageId() != null) { + builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString()); } if (sendDocument.getCaption() != null) { - builder.addTextBody(SendDocument.CAPTION_FIELD, sendDocument.getCaption(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendDocument.CAPTION_FIELD, sendDocument.getCaption(), TEXT_PLAIN_CONTENT_TYPE); } if (sendDocument.getDisableNotification() != null) { builder.addTextBody(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString()); @@ -521,16 +556,16 @@ public abstract class AbsSender { List 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().toJson().toString())); + if (sendDocument.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplyMarkup().toJson().toString())); } - if (sendDocument.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString())); + if (sendDocument.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString())); } if (sendDocument.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.CAPTION_FIELD, sendDocument.getCaption())); } - if (sendDocument.getReplayToMessageId() != null) { + if (sendDocument.getDisableNotification() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString())); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8)); @@ -553,7 +588,7 @@ public abstract class AbsSender { return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); } - public Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException { + public final Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException { String responseContent; try { String url = getBaseUrl() + SendPhoto.PATH; @@ -562,15 +597,21 @@ public abstract class AbsSender { if (sendPhoto.isNewPhoto()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()); - builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); - if (sendPhoto.getReplayMarkup() != null) { - builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString()); + if (sendPhoto.getNewPhotoFile() != null) { + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoFile()); + } else if (sendPhoto.getNewPhotoStream() != null) { + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoStream(), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); + } else { + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); } - if (sendPhoto.getReplayToMessageId() != null) { - builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString()); + if (sendPhoto.getReplyMarkup() != null) { + builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendPhoto.getReplyToMessageId() != null) { + builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString()); } if (sendPhoto.getCaption() != null) { - builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption(), TEXT_PLAIN_CONTENT_TYPE); } if (sendPhoto.getDisableNotification() != null) { builder.addTextBody(SendPhoto.DISABLENOTIFICATION_FIELD, sendPhoto.getDisableNotification().toString()); @@ -581,11 +622,11 @@ public abstract class AbsSender { List 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().toJson().toString())); + if (sendPhoto.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplyMarkup().toJson().toString())); } - if (sendPhoto.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString())); + if (sendPhoto.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString())); } if (sendPhoto.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption())); @@ -613,7 +654,7 @@ public abstract class AbsSender { return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); } - public Message sendVideo(SendVideo sendVideo) throws TelegramApiException { + public final Message sendVideo(SendVideo sendVideo) throws TelegramApiException { String responseContent; try { String url = getBaseUrl() + SendVideo.PATH; @@ -622,15 +663,21 @@ public abstract class AbsSender { if (sendVideo.isNewVideo()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId()); - builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); - if (sendVideo.getReplayMarkup() != null) { - builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString()); + if (sendVideo.getNewVideoFile() != null) { + builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoFile()); + } else if (sendVideo.getNewVideoStream() != null) { + builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoStream(), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); + } else { + builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); } - if (sendVideo.getReplayToMessageId() != null) { - builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString()); + if (sendVideo.getReplyMarkup() != null) { + builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendVideo.getReplyToMessageId() != null) { + builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplyToMessageId().toString()); } if (sendVideo.getCaption() != null) { - builder.addTextBody(SendVideo.CAPTION_FIELD, sendVideo.getCaption(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendVideo.CAPTION_FIELD, sendVideo.getCaption(), TEXT_PLAIN_CONTENT_TYPE); } if (sendVideo.getDuration() != null) { builder.addTextBody(SendVideo.DURATION_FIELD, sendVideo.getDuration().toString()); @@ -650,11 +697,11 @@ public abstract class AbsSender { List 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().toJson().toString())); + if (sendVideo.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplyMarkup().toJson().toString())); } - if (sendVideo.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString())); + if (sendVideo.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplyToMessageId().toString())); } if (sendVideo.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendVideo.CAPTION_FIELD, sendVideo.getCaption())); @@ -691,7 +738,7 @@ public abstract class AbsSender { return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); } - public Message sendSticker(SendSticker sendSticker) throws TelegramApiException { + public final Message sendSticker(SendSticker sendSticker) throws TelegramApiException { String responseContent; try { @@ -701,12 +748,18 @@ public abstract class AbsSender { if (sendSticker.isNewSticker()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId()); - builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); - if (sendSticker.getReplayMarkup() != null) { - builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString()); + if (sendSticker.getNewStickerFile() != null) { + builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerFile()); + } else if (sendSticker.getNewStickerStream() != null) { + builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerStream(), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); + } else { + builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); } - if (sendSticker.getReplayToMessageId() != null) { - builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString()); + if (sendSticker.getReplyMarkup() != null) { + builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendSticker.getReplyToMessageId() != null) { + builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString()); } if (sendSticker.getDisableNotification() != null) { builder.addTextBody(SendSticker.DISABLENOTIFICATION_FIELD, sendSticker.getDisableNotification().toString()); @@ -717,11 +770,11 @@ public abstract class AbsSender { List 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().toJson().toString())); + if (sendSticker.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplyMarkup().toJson().toString())); } - if (sendSticker.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString())); + if (sendSticker.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString())); } if (sendSticker.getDisableNotification() != null) { nameValuePairs.add(new BasicNameValuePair(SendSticker.DISABLENOTIFICATION_FIELD, sendSticker.getDisableNotification().toString())); @@ -752,7 +805,7 @@ public abstract class AbsSender { * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio */ - public Message sendAudio(SendAudio sendAudio) throws TelegramApiException { + public final Message sendAudio(SendAudio sendAudio) throws TelegramApiException { String responseContent; @@ -763,12 +816,18 @@ public abstract class AbsSender { if (sendAudio.isNewAudio()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendAudio.CHATID_FIELD, sendAudio.getChatId()); - builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); - if (sendAudio.getReplayMarkup() != null) { - builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString()); + if (sendAudio.getNewAudioFile() != null) { + builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioFile()); + } else if (sendAudio.getNewAudioStream() != null) { + builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioStream(), ContentType.APPLICATION_OCTET_STREAM, sendAudio.getAudioName()); + } else { + builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); } - if (sendAudio.getReplayToMessageId() != null) { - builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplayToMessageId().toString()); + if (sendAudio.getReplyMarkup() != null) { + builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendAudio.getReplyToMessageId() != null) { + builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString()); } if (sendAudio.getPerformer() != null) { builder.addTextBody(SendAudio.PERFOMER_FIELD, sendAudio.getPerformer()); @@ -788,11 +847,11 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendAudio.CHATID_FIELD, sendAudio.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendAudio.AUDIO_FIELD, sendAudio.getAudio())); - if (sendAudio.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString())); + if (sendAudio.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplyMarkup().toJson().toString())); } - if (sendAudio.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplayToMessageId().toString())); + if (sendAudio.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString())); } if (sendAudio.getPerformer() != null) { nameValuePairs.add(new BasicNameValuePair(SendAudio.PERFOMER_FIELD, sendAudio.getPerformer())); @@ -831,11 +890,12 @@ public abstract class AbsSender { /** * Sends a voice note using Send Voice method (https://core.telegram.org/bots/api#sendvoice) + * For this to work, your audio must be in an .ogg file encoded with OPUS * @param sendVoice Information to send * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio */ - public Message sendVoice(SendVoice sendVoice) throws TelegramApiException { + public final Message sendVoice(SendVoice sendVoice) throws TelegramApiException { String responseContent; try { @@ -845,12 +905,18 @@ public abstract class AbsSender { if (sendVoice.isNewVoice()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId()); - builder.addBinaryBody(SendVoice.AUDIO_FIELD, new java.io.File(sendVoice.getAudio()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); - if (sendVoice.getReplayMarkup() != null) { - builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString()); + if (sendVoice.getNewVoiceFile() != null) { + builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceFile()); + } else if (sendVoice.getNewVoiceStream() != null) { + builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceStream(), ContentType.APPLICATION_OCTET_STREAM, sendVoice.getVoiceName()); + } else { + builder.addBinaryBody(SendVoice.VOICE_FIELD, new java.io.File(sendVoice.getVoice()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); } - if (sendVoice.getReplayToMessageId() != null) { - builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplayToMessageId().toString()); + if (sendVoice.getReplyMarkup() != null) { + builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendVoice.getReplyToMessageId() != null) { + builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString()); } if (sendVoice.getDisableNotification() != null) { builder.addTextBody(SendVoice.DISABLENOTIFICATION_FIELD, sendVoice.getDisableNotification().toString()); @@ -863,12 +929,12 @@ public abstract class AbsSender { } else { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendVoice.CHATID_FIELD, sendVoice.getChatId())); - nameValuePairs.add(new BasicNameValuePair(SendVoice.AUDIO_FIELD, sendVoice.getAudio())); - if (sendVoice.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendVoice.VOICE_FIELD, sendVoice.getVoice())); + if (sendVoice.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplyMarkup().toJson().toString())); } - if (sendVoice.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplayToMessageId().toString())); + if (sendVoice.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString())); } if (sendVoice.getDisableNotification() != null) { nameValuePairs.add(new BasicNameValuePair(SendVoice.DISABLENOTIFICATION_FIELD, sendVoice.getDisableNotification().toString())); @@ -928,7 +994,7 @@ public abstract class AbsSender { }); } - private Serializable sendApiMethod(BotApiMethod method) throws TelegramApiException { + private T sendApiMethod(BotApiMethod method) throws TelegramApiException { String responseContent; try { String url = getBaseUrl() + method.getPath(); diff --git a/src/main/java/org/telegram/telegrambots/bots/BotOptions.java b/src/main/java/org/telegram/telegrambots/bots/BotOptions.java new file mode 100644 index 00000000..081481a9 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/BotOptions.java @@ -0,0 +1,35 @@ +package org.telegram.telegrambots.bots; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Configurations for the Bot + * @date 21 of July of 2016 + */ +public class BotOptions { + private String proxyHost; + private int proxyPort; + + public BotOptions() { + } + + public String getProxyHost() { + return proxyHost; + } + + public int getProxyPort() { + return proxyPort; + } + + public void setProxyHost(String proxyHost) { + this.proxyHost = proxyHost; + } + + public void setProxyPort(int proxyPort) { + this.proxyPort = proxyPort; + } + + public boolean hasProxy() { + return proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0; + } +} diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 7afdf9c8..40915803 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -7,5 +7,11 @@ package org.telegram.telegrambots.bots; * @date 14 of January of 2016 */ public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot { + public TelegramLongPollingBot() { + this(new BotOptions()); + } + public TelegramLongPollingBot(BotOptions options) { + super(options); + } } diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java new file mode 100644 index 00000000..b3b31cef --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -0,0 +1,125 @@ +package org.telegram.telegrambots.bots; + + +import org.telegram.telegrambots.bots.commands.BotCommand; +import org.telegram.telegrambots.bots.commands.CommandRegistry; +import org.telegram.telegrambots.bots.commands.ICommandRegistry; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.Update; + +import java.util.Collection; +import java.util.Map; +import java.util.function.BiConsumer; + +/** + * This class adds command functionality to the TelegramLongPollingBot + * + * @author Timo Schulz (Mit0x2) + */ +public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingBot implements ICommandRegistry { + private final CommandRegistry commandRegistry; + + /** + * Creates a TelegramLongPollingCommandBot using default options + * Use ICommandRegistry's methods on this bot to register commands + */ + public TelegramLongPollingCommandBot() { + this(new BotOptions()); + } + + /** + * Creates a TelegramLongPollingCommandBot with custom options and allowing commands with + * usernames + * Use ICommandRegistry's methods on this bot to register commands + * @param options Bot options + */ + public TelegramLongPollingCommandBot(BotOptions options) { + this(options, true); + } + + /** + * Creates a TelegramLongPollingCommandBot + * Use ICommandRegistry's methods on this bot to register commands + * @param options Bot options + * @param allowCommandsWithUsername true to allow commands with parameters (default), + * false otherwise + */ + public TelegramLongPollingCommandBot(BotOptions options, boolean allowCommandsWithUsername) { + super(options); + this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, getBotUsername()); + } + + @Override + public final void onUpdateReceived(Update update) { + if (update.hasMessage()) { + Message message = update.getMessage(); + if (message.isCommand() && !filter(message)) { + if (commandRegistry.executeCommand(this, message)) { + return; + } + } + } + processNonCommandUpdate(update); + } + + /** + * Override this function in your bot implementation to filter messages with commands + * + * For example, if you want to prevent commands execution incoming from group chat: + * # + * # return !message.getChat().isGroupChat(); + * # + * + * @note Default implementation doesn't filter anything + * @param message Received message + * @return true if the message must be ignored by the command bot and treated as a non command message, + * false otherwise + */ + protected boolean filter(Message message) { + return false; + } + + @Override + public final boolean register(BotCommand botCommand) { + return commandRegistry.register(botCommand); + } + + @Override + public final Map registerAll(BotCommand... botCommands) { + return commandRegistry.registerAll(botCommands); + } + + @Override + public final boolean deregister(BotCommand botCommand) { + return commandRegistry.deregister(botCommand); + } + + @Override + public final Map deregisterAll(BotCommand... botCommands) { + return commandRegistry.deregisterAll(botCommands); + } + + @Override + public final Collection getRegisteredCommands() { + return commandRegistry.getRegisteredCommands(); + } + + @Override + public void registerDefaultAction(BiConsumer defaultConsumer) { + commandRegistry.registerDefaultAction(defaultConsumer); + } + + @Override + public final BotCommand getRegisteredCommand(String commandIdentifier) { + return commandRegistry.getRegisteredCommand(commandIdentifier); + } + + /** + * Process all updates, that are not commands. + * @warning Commands that have valid syntax but are not registered on this bot, + * won't be forwarded to this method if a default action is present. + * + * @param update the update + */ + public abstract void processNonCommandUpdate(Update update); +} diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java index ddf56bca..b3f41afb 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java @@ -7,4 +7,11 @@ package org.telegram.telegrambots.bots; * @date 14 of January of 2016 */ public abstract class TelegramWebhookBot extends AbsSender implements ITelegramWebhookBot { + public TelegramWebhookBot() { + this(new BotOptions()); + } + + public TelegramWebhookBot(BotOptions options) { + super(options); + } } diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java new file mode 100644 index 00000000..4b0935fa --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java @@ -0,0 +1,78 @@ +package org.telegram.telegrambots.bots.commands; + +import org.telegram.telegrambots.api.objects.Chat; +import org.telegram.telegrambots.api.objects.User; +import org.telegram.telegrambots.bots.AbsSender; + +/** + * Representation of a command, which can be executed + * + * @author Timo Schulz (Mit0x2) + */ +public abstract class BotCommand { + public final static String COMMAND_INIT_CHARACTER = "/"; + public static final String COMMAND_PARAMETER_SEPARATOR = " "; + private final static int COMMAND_MAX_LENGTH = 32; + + private final String commandIdentifier; + private final String description; + + /** + * Construct a command + * + * @param commandIdentifier the unique identifier of this command (e.g. the command string to + * enter into chat) + * @param description the description of this command + */ + public BotCommand(String commandIdentifier, String description) { + + if (commandIdentifier == null || commandIdentifier.isEmpty()) { + throw new IllegalArgumentException("commandIdentifier for command cannot be null or empty"); + } + + if (commandIdentifier.startsWith(COMMAND_INIT_CHARACTER)) { + commandIdentifier = commandIdentifier.substring(1); + } + + if (commandIdentifier.length() + 1 > COMMAND_MAX_LENGTH) { + throw new IllegalArgumentException("commandIdentifier cannot be longer than " + COMMAND_MAX_LENGTH + " (including " + COMMAND_INIT_CHARACTER + ")"); + } + + this.commandIdentifier = commandIdentifier.toLowerCase(); + this.description = description; + } + + /** + * Get the identifier of this command + * + * @return the identifier + */ + public final String getCommandIdentifier() { + return commandIdentifier; + } + + /** + * Get the description of this command + * + * @return the description as String + */ + public final String getDescription() { + return description; + } + + @Override + public String toString() { + return "" + COMMAND_INIT_CHARACTER + getCommandIdentifier() + + "\n" + getDescription(); + } + + /** + * Execute the command + * + * @param absSender absSender to send messages over + * @param user the user who sent the command + * @param chat the chat, to be able to send replies + * @param arguments passed arguments + */ + public abstract void execute(AbsSender absSender, User user, Chat chat, String[] arguments); +} \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java new file mode 100644 index 00000000..e43c273b --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -0,0 +1,129 @@ +package org.telegram.telegrambots.bots.commands; + +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.bots.AbsSender; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; + +/** + * This class manages all the commands for a bot. You can register and deregister commands on demand + * + * @author Timo Schulz (Mit0x2) + */ +public final class CommandRegistry implements ICommandRegistry { + + private final Map commandRegistryMap = new HashMap<>(); + private final boolean allowCommandsWithUsername; + private final String botUsername; + private BiConsumer defaultConsumer; + + /** + * Creates a Command registry + * @param allowCommandsWithUsername True to allow commands with username, false otherwise + * @param botUsername Bot username + */ + public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) { + this.allowCommandsWithUsername = allowCommandsWithUsername; + this.botUsername = botUsername; + } + + @Override + public void registerDefaultAction(BiConsumer defaultConsumer) { + this.defaultConsumer = defaultConsumer; + } + + @Override + public final boolean register(BotCommand botCommand) { + if (commandRegistryMap.containsKey(botCommand.getCommandIdentifier())) { + return false; + } + commandRegistryMap.put(botCommand.getCommandIdentifier(), botCommand); + return true; + } + + @Override + public final Map registerAll(BotCommand... botCommands) { + Map resultMap = new HashMap<>(botCommands.length); + for (BotCommand botCommand : botCommands) { + resultMap.put(botCommand, register(botCommand)); + } + return resultMap; + } + + @Override + public final boolean deregister(BotCommand botCommand) { + if (commandRegistryMap.containsKey(botCommand.getCommandIdentifier())) { + commandRegistryMap.remove(botCommand.getCommandIdentifier()); + return true; + } + return false; + } + + @Override + public final Map deregisterAll(BotCommand... botCommands) { + Map resultMap = new HashMap<>(botCommands.length); + for (BotCommand botCommand : botCommands) { + resultMap.put(botCommand, deregister(botCommand)); + } + return resultMap; + } + + @Override + public final Collection getRegisteredCommands() { + return commandRegistryMap.values(); + } + + @Override + public final BotCommand getRegisteredCommand(String commandIdentifier) { + return commandRegistryMap.get(commandIdentifier); + } + + /** + * Executes a command action if the command is registered. + * + * @note If the command is not registered and there is a default consumer, + * that action will be performed + * + * @param absSender absSender + * @param message input message + * @return True if a command or default action is executed, false otherwise + */ + public final boolean executeCommand(AbsSender absSender, Message message) { + if (message.hasText()) { + String text = message.getText(); + if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { + String commandMessage = text.substring(1); + String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR); + + String command = removeUsernameFromCommandIfNeeded(commandSplit[0]); + + if (commandRegistryMap.containsKey(command)) { + String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); + commandRegistryMap.get(command).execute(absSender, message.getFrom(), message.getChat(), parameters); + return true; + } else if (defaultConsumer != null) { + defaultConsumer.accept(absSender, message); + return true; + } + } + } + return false; + } + + /** + * if {@link #allowCommandsWithUsername} is enabled, the username of the bot is removed from + * the command + * @param command Command to simplify + * @return Simplified command + */ + private String removeUsernameFromCommandIfNeeded(String command) { + if (allowCommandsWithUsername) { + return command.replace("@" + botUsername, "").trim(); + } + return command; + } +} \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java new file mode 100644 index 00000000..56ae4c6c --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java @@ -0,0 +1,71 @@ +package org.telegram.telegrambots.bots.commands; + +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.bots.AbsSender; + +import java.util.Collection; +import java.util.Map; +import java.util.function.BiConsumer; + +/** + * This Interface represents the gateway for registering and deregistering commands. + * + * @author Timo Schulz (Mit0x2) + */ +public interface ICommandRegistry { + + /** + * Register a default action when there is no command register that match the message sent + * @param defaultConsumer Consumer to evaluate the message + * + * @note Use this method if you want your bot to execute a default action when the user + * sends a command that is not registered. + */ + void registerDefaultAction(BiConsumer defaultConsumer); + + /** + * register a command + * + * @param botCommand the command to register + * @return whether the command could be registered, was not already registered + */ + boolean register(BotCommand botCommand); + + /** + * register multiple commands + * + * @param botCommands commands to register + * @return map with results of the command register per command + */ + Map registerAll(BotCommand... botCommands); + + /** + * deregister a command + * + * @param botCommand the command to deregister + * @return whether the command could be deregistered, was registered + */ + boolean deregister(BotCommand botCommand); + + /** + * deregister multiple commands + * + * @param botCommands commands to deregister + * @return map with results of the command deregistered per command + */ + Map deregisterAll(BotCommand... botCommands); + + /** + * get a collection of all registered commands + * + * @return a collection of registered commands + */ + Collection getRegisteredCommands(); + + /** + * get registered command + * + * @return registered command if exists or null if not + */ + BotCommand getRegisteredCommand(String commandIdentifier); +} \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java index 39b5f1ec..b13c5b2f 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.updatesreceivers; import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -14,12 +15,13 @@ import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.telegram.telegrambots.logging.BotLogger; import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.methods.updates.GetUpdates; import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.bots.BotOptions; import org.telegram.telegrambots.bots.ITelegramLongPollingBot; +import org.telegram.telegrambots.logging.BotLogger; import java.io.IOException; import java.io.InvalidObjectException; @@ -27,9 +29,6 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.TimeUnit; -import static org.telegram.telegrambots.Constants.ERRORCODEFIELD; -import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; - /** * @author Ruben Bermudez * @version 1.0 @@ -50,53 +49,74 @@ public class BotSession { private volatile CloseableHttpClient httpclient; private volatile RequestConfig requestConfig; - + /** + * Constructor present just to keep backward compatibility will be removed in next mayor release. + * + * @deprecated @deprecated use {@link #BotSession(String, ITelegramLongPollingBot, BotOptions)} + * @param token Token of the bot + * @param callback Callback for incomming updates + */ + @Deprecated public BotSession(String token, ITelegramLongPollingBot callback) { + this(token, callback, new BotOptions()); + } + + public BotSession(String token, ITelegramLongPollingBot callback, BotOptions options) { this.token = token; this.callback = callback; + httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) .setMaxConnTotal(100) .build(); - requestConfig = RequestConfig.copy(RequestConfig.custom().build()) - .setSocketTimeout(SOCKET_TIMEOUT) + + RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()); + if (options.hasProxy()) { + configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + } + + requestConfig = configBuilder.setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); - this.readerThread = new ReaderThread(); + + readerThread = new ReaderThread(); readerThread.setName(callback.getBotUsername() + " Telegram Connection"); - this.readerThread.start(); - this.handlerThread = new HandlerThread(); - handlerThread.setName(callback.getBotUsername() + " Executor"); - this.handlerThread.start(); + readerThread.start(); + + handlerThread = new HandlerThread(); + handlerThread.setName(callback.getBotUsername() + " Telegram Executor"); + handlerThread.start(); } - - public void close() - { - running = false; - if(httpclient != null) - { - try - { - httpclient.close(); - httpclient = null; + + public void close() { + running = false; + if (readerThread != null) { + readerThread.interrupt(); + } + if (handlerThread != null) { + handlerThread.interrupt(); + } + if (httpclient != null) { + try { + httpclient.close(); + httpclient = null; } catch (IOException e) { BotLogger.severe(LOGTAG, e); } - } - + } } private class ReaderThread extends Thread { - @Override + @Override public void run() { setPriority(Thread.MIN_PRIORITY); - while(running) { + while (running) { try { GetUpdates request = new GetUpdates(); request.setLimit(100); - request.setTimeout(50); + request.setTimeout(Constants.GETUPDATESTIMEOUT); request.setOffset(lastReceivedUpdate + 1); String url = Constants.BASEURL + token + "/" + GetUpdates.PATH; //http client @@ -111,7 +131,9 @@ public class BotSession { String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); JSONObject jsonObject = new JSONObject(responseContent); if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiException("Error getting updates", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD)); + throw new TelegramApiException("Error getting updates", + jsonObject.getString(Constants.ERRORDESCRIPTIONFIELD), + jsonObject.getInt(Constants.ERRORCODEFIELD)); } JSONArray jsonArray = jsonObject.getJSONArray(Constants.RESPONSEFIELDRESULT); if (jsonArray.length() != 0) { @@ -155,7 +177,7 @@ public class BotSession { @Override public void run() { setPriority(Thread.MIN_PRIORITY); - while(running) { + while (running) { try { Update update = receivedUpdates.pollLast(); if (update == null) { diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java index 4b0c4608..07748e4a 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java @@ -3,10 +3,16 @@ package org.telegram.telegrambots.updatesreceivers; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.bots.ITelegramWebhookBot; -import javax.ws.rs.*; +import java.util.concurrent.ConcurrentHashMap; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.concurrent.ConcurrentHashMap; /** * @author Ruben Bermudez @@ -15,7 +21,7 @@ import java.util.concurrent.ConcurrentHashMap; * @date 20 of June of 2015 */ @Path("callback") -class RestApi { +public class RestApi { private final ConcurrentHashMap callbacks = new ConcurrentHashMap<>(); diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java index 63824e38..96245969 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java @@ -10,6 +10,7 @@ import org.glassfish.jersey.server.ResourceConfig; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.bots.ITelegramWebhookBot; +import java.io.File; import java.io.IOException; import java.net.URI; @@ -20,17 +21,16 @@ import java.net.URI; * @date 20 of June of 2015 */ public class Webhook { - private static final String LOGTAG = "WEBHOOK"; - private final String KEYSTORE_SERVER_FILE; private final String KEYSTORE_SERVER_PWD; private final RestApi restApi; private final String internalUrl; - public Webhook(String keyStore, String keyStorePassword, String internalUrl) { + public Webhook(String keyStore, String keyStorePassword, String internalUrl) throws TelegramApiException { this.KEYSTORE_SERVER_FILE = keyStore; this.KEYSTORE_SERVER_PWD = keyStorePassword; + validateServerKeystoreFile(keyStore); this.internalUrl = internalUrl; this.restApi = new RestApi(); } @@ -65,4 +65,11 @@ public class Webhook { private URI getBaseURI() { return URI.create(internalUrl); } - } + + private static void validateServerKeystoreFile(String keyStore) throws TelegramApiException { + File file = new File(keyStore); + if (!file.exists() || !file.canRead()) { + throw new TelegramApiException("Can't find or access server keystore file."); + } + } +}