diff --git a/.travis.yml b/.travis.yml index dad1dfaf..74353a8f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: java jdk: - oraclejdk8 -install: mvn install -DskipTests -Dgpg.skip +install: mvn install -Dgpg.skip script: mvn clean compile notifications: webhooks: diff --git a/Bots.ipr b/Bots.ipr new file mode 100644 index 00000000..cea2e68f --- /dev/null +++ b/Bots.ipr @@ -0,0 +1,914 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /usr/local/bin/bower + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1.8 + + + + + + + + \ No newline at end of file diff --git a/HOWTO.md b/HOWTO.md deleted file mode 100644 index cd3721ce..00000000 --- a/HOWTO.md +++ /dev/null @@ -1,203 +0,0 @@ -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 -[Preparations](#preparations) -[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) - - - - -## Preparations -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 - -You can use it with Maven or Gradle directly from Central repository, just this to your *pom.xml* file: - -```xml - - org.telegram - telegrambots - 2.4.0 - -``` - -You can also find it in a different repository, just in case, search [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/LICENSE b/LICENSE index 733c0723..16d9ac5f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,675 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {one line to give the program's name and a brief idea of what it does.} - Copyright (C) {year} {name of author} - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - {project} Copyright (C) {year} {fullname} - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. - +MIT License + +Copyright (c) 2016 Ruben Bermudez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index e44e23ce..bbd55e26 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ # Telegram Bot Java Library +[![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi) + + [![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) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.telegram/telegrambots/badge.svg)](http://mvnrepository.com/artifact/org.telegram/telegrambots) -[![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi) - +[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/rubenlagus/TelegramBots/blob/master/LICENSE) A simple to use library to create Telegram Bots in Java ## Contributions @@ -24,12 +26,12 @@ Just import add the library to your project with one of these options: org.telegram telegrambots - 2.4.0 + 2.4.1 ``` - 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/v2.4.0) - 3. Download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.4.0) + 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/v2.4.1) + 3. Download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.4.1) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. @@ -87,16 +89,24 @@ This library use [Telegram bot API](https://core.telegram.org/bots), you can fin Feel free to create issues [here](https://github.com/rubenlagus/TelegramBots/issues) as you need or join the [chat](https://telegram.me/JavaBotsApi) ## License +MIT License -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. +Copyright (c) 2016 Ruben Bermudez -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -You should have received a copy of the GNU General Public License -along with this program. If not, see . +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md new file mode 100644 index 00000000..aeb6b287 --- /dev/null +++ b/TelegramBots.wiki/Changelog.md @@ -0,0 +1,10 @@ +### 2.4.1 ### +1. Split library in two modules to allow custom implementations. +2. Use [Guice](https://github.com/google/guice) for dependency injection. +3. Use [Jackson](https://github.com/FasterXML/jackson) for json (de)serialization. +4. Added extra validation to methods before performing requests. +5. BotOptions has been renamed ot DefaultBotOptions. It allows now to set number of threads for async methods execution and the complete `RequestConfig` for customization purpose. +6. Added convenient method for `setChatId` using just a `Long` value instead of an String. +7. Moved to MIT license + +**[[How to update to version 2.4.1|How-To-Update#2.4.1]]** \ No newline at end of file diff --git a/TelegramBots.wiki/Errors-Handling.md b/TelegramBots.wiki/Errors-Handling.md new file mode 100644 index 00000000..16f4d79c --- /dev/null +++ b/TelegramBots.wiki/Errors-Handling.md @@ -0,0 +1,5 @@ +* [Terminated by other long poll or webhook](#terminted_by_other) + +## Terminated by other long poll or webhook ## + +It means that you have already a running instance of your bot. To solve it, close all running ones and then you can start a new instance. \ No newline at end of file diff --git a/TelegramBots.wiki/FAQ.md b/TelegramBots.wiki/FAQ.md new file mode 100644 index 00000000..86c5db18 --- /dev/null +++ b/TelegramBots.wiki/FAQ.md @@ -0,0 +1,180 @@ +* [How to get picture?](#how_to_get_picture) +* [How to send photos?](#how_to_send_photos) +* [How to use custom keyboards?](#how_to_use_custom_keyboards) +* [How can I run my bot?](#how_to_host) +* [How can I compile my project?](#how_to_compile) + + +## How to download photo? ## + +To download a picture (or any other file), you will need the `file_path` of the file. Let start by finding the photo we want to download, the following method will extract the `PhotoSize` from a photo sent to the bot (in our case, we are taken the bigger size of those provided): + +```java +public PhotoSize getPhoto(Update update) { + // Check that the update contains a message and the message has a photo + if (update.hasMessage() && update.getMessage().hasPhoto()) { + // When receiving a photo, you usually get different sizes of it + List photos = update.getMessage().getPhoto(); + + // We fetch the bigger photo + return photos.stream() + .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()) + .findFirst() + .orElse(null); + } + + // Return null if not found + return null; +} +``` + +Once we have the *photo* we have to options: The `file_path` is already present or we need to get it, the following method will handle both of them and return the final `file_path`: + +```java +public String getFilePath(PhotoSize photo) { + Objects.requireNonNull(photo); + + if (photo.hasFilePath()) { // If the file_path is already present, we are done! + return photo.getFilePath(); + } else { // If not, let find it + // We create a GetFile method and set the file_id from the photo + GetFile getFileMethod = new GetFile(); + getFileMethod.setFileId(photo.getFileId()); + try { + // We execute the method using AbsSender::getFile method. + File file = getFile(getFileMethod); + // We now have the file_path + return file.getFilePath(); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } + + return null; // Just in case +} +``` + +Now that we have the `file_path` we can download it: + +```java +public java.io.File downloadPhotoByFilePath(String filePath) { + try { + // Download the file calling AbsSender::downloadFile method + return downloadFile(filePath); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + + return null; +} +``` + +The returned `java.io.File` object will be your photo + +## How to send photos? ## + +There are several method to send a photo to an user using `sendPhoto` method: With a `file_id`, with an `url` or uploading the file. In this example, we assume that we already have the *chat_id* where we want to send the photo: + +```java + public void sendImageFromUrl(String url, String chatId) { + // Create send method + SendPhoto sendPhotoRequest = new SendPhoto(); + // Set destination chat id + sendPhotoRequest.setChatId(chatId); + // Set the photo url as a simple photo + sendPhotoRequest.setPhoto(url); + try { + // Execute the method + sendPhoto(sendPhotoRequest); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } + + public void sendImageFromFileId(String fileId, String chatId) { + // Create send method + SendPhoto sendPhotoRequest = new SendPhoto(); + // Set destination chat id + sendPhotoRequest.setChatId(chatId); + // Set the photo url as a simple photo + sendPhotoRequest.setPhoto(fileId); + try { + // Execute the method + sendPhoto(sendPhotoRequest); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } + + public void sendImageUploadingAFile(String filePath, String chatId) { + // Create send method + SendPhoto sendPhotoRequest = new SendPhoto(); + // Set destination chat id + sendPhotoRequest.setChatId(chatId); + // Set the photo file as a new photo (You can also use InputStream with a method overload) + sendPhotoRequest.setNewPhoto(new File(filePath)); + try { + // Execute the method + sendPhoto(sendPhotoRequest); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } +``` + + +## How to use custom keyboards? ## + +Custom keyboards can be appended to messages using the `setReplyMarkup`. In this example, we will build a simple [ReplyKeyboardMarkup](https://core.telegram.org/bots/api#replykeyboardmarkup) with two rows and three buttons per row, but you can also use other types like [ReplyKeyboardHide](https://core.telegram.org/bots/api#replykeyboardhide), [ForceReply](https://core.telegram.org/bots/api#forcereply) or [InlineKeyboardMarkup](https://core.telegram.org/bots/api#inlinekeyboardmarkup): + +```java + public void sendCustomKeyboard(String chatId) { + SendMessage message = new SendMessage(); + message.setChatId(chatId); + message.setText("Custom message text"); + + // Create ReplyKeyboardMarkup object + ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); + // Create the keyboard (list of keyboard rows) + List keyboard = new ArrayList<>(); + // Create a keyboard row + KeyboardRow row = new KeyboardRow(); + // Set each button, you can also use KeyboardButton objects if you need something else than text + row.add("Row 1 Button 1"); + row.add("Row 1 Button 2"); + row.add("Row 1 Button 3"); + // Add the first row to the keyboard + keyboard.add(row); + // Create another keyboard row + row = new KeyboardRow(); + // Set each button for the second line + row.add("Row 2 Button 1"); + row.add("Row 2 Button 2"); + row.add("Row 2 Button 3"); + // Add the second row to the keyboard + keyboard.add(row); + // Set the keyboard to the markup + keyboardMarkup.setKeyboard(keyboard); + // Add it to the message + message.setReplyMarkup(keyboardMarkup); + + try { + // Send the message + sendMessage(message); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } +``` + +## How can I run my bot? ## + +You don't need to spend a lot of money into hosting your own telegram bot. Basically, there are two options around how to host: + + 1. Hosting on your own hardware. It can be a Mini-PC like a Raspberry Pi. The costs for the hardware (~35€) and annual costs for power (~7-8€) are low. Keep in mind that your internet connection might be limited and a Mini-Pc is not ideal for a large users base. + 2. Run your bot in a Virtual Server/dedicated root server. There are many hosters out there that are providing cheap servers that fit your needs. The cheapest one should be openVZ-Containers or a KVM vServer. Example providers are [Hetzner](https://www.hetzner.de/ot/), [DigitalOcean](https://www.digitalocean.com/), (are providing systems that have a high availability but cost's a bit more) and [OVH](https://ovh.com) + +## How can I compile my project? ## + +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) \ No newline at end of file diff --git a/TelegramBots.wiki/Getting-Started.md b/TelegramBots.wiki/Getting-Started.md new file mode 100644 index 00000000..a44eebaf --- /dev/null +++ b/TelegramBots.wiki/Getting-Started.md @@ -0,0 +1,174 @@ +So, you just wanna program your own Telegram bot with TelegramBots? Let's see the fast version. + +## Grab the library +First you need ot get the library and add it to your project. There are few possibilities for this: + +1. If you use [Maven](https://maven.apache.org/), [Gradle](https://gradle.org/), etc; you should be able to import the dependency directly from [Maven Central Repository](http://mvnrepository.com/artifact/org.telegram/telegrambots). For example: + + * With **Maven**: + + ```xml + + org.telegram + telegrambots + 2.4.1 + + ``` + * With **Gradle**: + + ```groovy + compile group: 'org.telegram', name: 'telegrambots', version: '2.4.1' + ``` + +2. Don't like **Maven Central Repository**? It can also be taken from [Jitpack](https://jitpack.io/#rubenlagus/TelegramBots). +3. Import the library *.jar* direclty to your project. You can find it [here](https://github.com/rubenlagus/TelegramBots/releases), don't forget to take last version, it usually is a good idea. Depending on the IDE you are using, the process to add a library is different, here is a video that may help with [Intellij](https://www.youtube.com/watch?v=NZaH4tjwMYg) or [Eclipse](https://www.youtube.com/watch?v=VWnfHkBgO1I) + + +## Build our first bot +Now that we have the library, we can start coding. There are few steps to follow, in this tutorial (for the sake of simplicity), we are going to build a [Long Polling Bot](http://en.wikipedia.org/wiki/Push_technology#Long_polling): + +1. **Create your actual bot:** + The class must extends `TelegramLongPollingBot` and implement necessary methods: + + ```java + + public class MyAmazingBot extends TelegramLongPollingBot { + @Override + public void onUpdateReceived(Update update) { + // TODO + } + + @Override + public String getBotUsername() { + // TODO + return null; + } + + @Override + public String getBotToken() { + // TODO + return null; + } + } + + ``` + + * `getBotUsermane()`: This method must always return your **Bot username**. May look like: + + + ```java + + @Override + public String getBotUsername() { + return "myamazingbot"; + } + + ``` + + * `getBotToken()`: This method must always return your **Bot Token** (If you don't know it, you may want to talk with [@BotFather](https://telegram.me/BotFather)). May look like: + + ```java + + @Override + public String getBotToken() { + return "123456789:qwertyuioplkjhgfdsazxcvbnm"; + } + + ``` + + * `onUpdateReceived`: This method will be called when an [Update](https://core.telegram.org/bots/api#update) is received by your bot. In this example, this method will just read messages and echo the same text: + + ```java + + @Override + public void onUpdateReceived(Update update) { + // We check if the update has a message and the message has text + if (update.hasMessage() && update.getMessage().hasText()) { + SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields + .setChatId(update.getMessage().getChatId()) + .setText(update.getMessage().getText()); + try { + sendMessage(message); // Call method to send the message + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } + } + + ``` + +2. **Instantiate `TelegramBotsApi` and register our new bot:** + For this part, we need to actually perform 3 steps: _Initialize Api Context_, _Instantiate Telegram Api_ and _Register our Bot_. In this tutorial, we are going to make it in our `main` method: + + ```java + + public class Main { + public static void main(String[] args) { + + // TODO Initialize Api Context + + // TODO Instantiate Telegram Bots API + + // TODO Register our bot + } + } + + ``` + + * **Initialize Api Context**: This can be easily done calling the only method present in `ApiContextInitializer`: + + ```java + + public class Main { + public static void main(String[] args) { + + ApiContextInitializer.init(); + + // TODO Instantiate Telegram Bots API + + // TODO Register our bot + } + } + + ``` + + * **Instantiate Telegram Bots API**: Easy as well, just create a new instance. Remember that a single instance can handle different bots but each bot can run only once (Telegram doesn't support concurrent calls to `GetUpdates`): + + ```java + + public class Main { + public static void main(String[] args) { + + ApiContextInitializer.init(); + + TelegramBotsApi botsApi = new TelegramBotsApi(); + + // TODO Register our bot + } + } + + ``` + + * **Register our bot**: Now we need to register a new instance of our previously created bot class in the api: + + ```java + + public class Main { + public static void main(String[] args) { + + ApiContextInitializer.init(); + + TelegramBotsApi botsApi = new TelegramBotsApi(); + + try { + botsApi.registerBot(new MyAmazingBot()); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } + } + + ``` + +3. **Play with your bot:** + Done, now you just need to run this `main` method and your Bot should start working. \ No newline at end of file diff --git a/TelegramBots.wiki/Home.md b/TelegramBots.wiki/Home.md new file mode 100644 index 00000000..869d59d9 --- /dev/null +++ b/TelegramBots.wiki/Home.md @@ -0,0 +1 @@ +Welcome to the TelegramBots wiki. Use the sidebar on the right. If you're not sure what to look at, why not take a look at the [[Getting Started|Getting-Started]] guide? \ No newline at end of file diff --git a/TelegramBots.wiki/How-To-Update.md b/TelegramBots.wiki/How-To-Update.md new file mode 100644 index 00000000..fd8f7c57 --- /dev/null +++ b/TelegramBots.wiki/How-To-Update.md @@ -0,0 +1,10 @@ +### To version 2.4.1 ### +1. Replace `BotOptions` by `DefaultBotOptions`. +2. At the beginning of your program (before creating your `TelegramBotsApi` instance, add the following line: + ```java + ApiContextInitializer.init(); + ``` +3. **Deprecated** (will be removed in next version): + * `org.telegram.telegrambots.bots.BotOptions`. Use `org.telegram.telegrambots.bots.DefaultBotOptions` instead. + * `getPersonal` from `AnswerInlineQuery`. Use `isPersonal` instead. + * `FILEBASEURL` from `File`. Use `getFileUrl` instead. \ No newline at end of file diff --git a/TelegramBots.wiki/_Footer.md b/TelegramBots.wiki/_Footer.md new file mode 100644 index 00000000..225d1d16 --- /dev/null +++ b/TelegramBots.wiki/_Footer.md @@ -0,0 +1 @@ +[Telegram Bots Library Wiki](https://github.com/rubenlagus/TelegramBots) for contributions, make a pull request again [Telegram.wiki module](https://github.com/rubenlagus/TelegramBots/tree/dev/TelegramBots.wiki) \ No newline at end of file diff --git a/TelegramBots.wiki/_Sidebar.md b/TelegramBots.wiki/_Sidebar.md new file mode 100644 index 00000000..132020b0 --- /dev/null +++ b/TelegramBots.wiki/_Sidebar.md @@ -0,0 +1,6 @@ +* Users guide + * [[Getting Started]] + * [[Errors Handling]] + * [[FAQ]] +* [[Changelog]] + * [[How To Update]] diff --git a/badge.svg b/badge.svg deleted file mode 100644 index 73163190..00000000 --- a/badge.svg +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - chat - chat - on telegram - on telegram - - - diff --git a/pom.xml b/pom.xml index c85c3028..8c2b3bb3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,254 +1,29 @@ - 4.0.0 - jar + org.telegram - telegrambots - 2.4.0 + Bots + pom + 2.4.1 - Telegram Bots - https://github.com/rubenlagus/TelegramBots - Easy to use library to create Telegram Bots - - - https://github.com/rubenlagus/TelegramBots/issues - GitHub Issues - - - - https://github.com/rubenlagus/TelegramBots - scm:git:git://github.com/rubenlagus/TelegramBots.git - scm:git:git@github.com:rubenlagus/TelegramBots.git - - - - - rberlopez@gmail.com - Ruben Bermudez - https://github.com/rubenlagus - rubenlagus - - + + telegrambots + telegrambots-meta + - GNU General Public License (GPL) - http://www.gnu.org/licenses/gpl.html + MIT License + http://www.opensource.org/licenses/mit-license.php + repo - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - UTF-8 - UTF-8 - 2.23.2 - 1.19.2 - 4.5.2 - 20160810 - 2.7.4 - 2.5 + true + 2.4.1 - - - - - org.glassfish.jersey - jersey-bom - ${jersey.version} - pom - import - - - - - - - org.glassfish.jersey.containers - jersey-container-grizzly2-http - ${jersey.version} - - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey.version} - - - com.sun.jersey - jersey-bundle - ${jerseybundle.version} - - - com.sun.jersey - jersey-grizzly2-servlet - ${jerseybundle.version} - - - org.json - json - ${json.version} - - - org.apache.httpcomponents - httpclient - ${httpcompontents.version} - - - org.apache.httpcomponents - httpmime - ${httpcompontents.version} - - - commons-io - commons-io - ${commons.version} - - - - - ${project.basedir}/target - ${project.build.directory}/classes - ${project.artifactId}-${project.version} - ${project.build.directory}/test-classes - ${project.basedir}/src/main/java - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.3 - true - - ossrh - https://oss.sonatype.org/ - true - - - - 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 - - - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - - jar - - - -Xdoclint:none - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - - \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/Constants.java b/src/main/java/org/telegram/telegrambots/Constants.java deleted file mode 100644 index 15922931..00000000 --- a/src/main/java/org/telegram/telegrambots/Constants.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.telegram.telegrambots; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief Constants needed for Telegram Bots API - * @date 20 of June of 2015 - */ -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"; -} diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java deleted file mode 100644 index a24cc8cf..00000000 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ /dev/null @@ -1,183 +0,0 @@ -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; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.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.exceptions.TelegramApiRequestException; -import org.telegram.telegrambots.updatesreceivers.BotSession; -import org.telegram.telegrambots.updatesreceivers.Webhook; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.text.MessageFormat; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief Bots manager - * @date 14 of January of 2016 - */ -public class TelegramBotsApi { - 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 - - /** - * - */ - public TelegramBotsApi() { - } - - /** - * - * @param keyStore KeyStore for the server - * @param keyStorePassword Key store password for the server - * @param externalUrl External base url for the webhook - * @param internalUrl Internal base url for the webhook - */ - public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiRequestException { - if (externalUrl == null || externalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); - } - if (internalUrl == null || internalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); - } - - this.useWebhook = true; - this.extrenalUrl = fixExternalUrl(externalUrl); - webhook = new Webhook(keyStore, keyStorePassword, internalUrl); - webhook.startServer(); - } - - /** - * - * @param keyStore KeyStore for the server - * @param keyStorePassword Key store password for the server - * @param externalUrl External base url for the webhook - * @param internalUrl Internal base url for the webhook - * @param pathToCertificate Full path until .pem public certificate keys - */ - public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiRequestException { - if (externalUrl == null || externalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); - } - if (internalUrl == null || internalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); - } - this.useWebhook = true; - this.extrenalUrl = fixExternalUrl(externalUrl); - this.pathToCertificate = pathToCertificate; - 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 TelegramApiRequestException { - setWebhook(bot.getBotToken(), null, bot.getOptions()); - return new BotSession(bot.getBotToken(), bot, bot.getOptions()); - } - - /** - * Register a bot in the api that will receive updates using webhook method - * @param bot Bot to register - */ - public void registerBot(TelegramWebhookBot bot) throws TelegramApiRequestException { - if (useWebhook) { - webhook.registerWebhook(bot); - setWebhook(bot.getBotToken(), bot.getBotPath(), bot.getOptions()); - } - } - - private static String fixExternalUrl(String externalUrl) { - if (externalUrl != null && !externalUrl.endsWith("/")) { - externalUrl = externalUrl + "/"; - } - return MessageFormat.format(webhookUrlFormat, externalUrl); - } - - /** - * 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 TelegramApiRequestException If any error occurs setting the webhook - */ - private static void setWebhook(String webHookURL, String botToken, - String publicCertificatePath, BotOptions options) throws TelegramApiRequestException { - 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) { - 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); - try (CloseableHttpResponse response = httpclient.execute(httppost)) { - HttpEntity ht = response.getEntity(); - BufferedHttpEntity buf = new BufferedHttpEntity(ht); - String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException(webHookURL == null ? "Error removing old webhook" : "Error setting webhook", jsonObject); - } - } - } catch (JSONException e) { - throw new TelegramApiRequestException("Error deserializing setWebhook method response", e); - } catch (IOException e) { - throw new TelegramApiRequestException("Error executing setWebook method", e); - } - } - - /** - * 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 - */ - private void setWebhook(String botToken, String urlPath, BotOptions botOptions) throws TelegramApiRequestException { - if (botToken == null) { - throw new TelegramApiRequestException("Parameter botToken can not be null"); - } - String completeExternalUrl = urlPath == null ? "" : extrenalUrl + urlPath; - setWebhook(completeExternalUrl, botToken, pathToCertificate, botOptions); - } -} diff --git a/src/main/java/org/telegram/telegrambots/api/interfaces/IBotApiObject.java b/src/main/java/org/telegram/telegrambots/api/interfaces/IBotApiObject.java deleted file mode 100644 index 5841be31..00000000 --- a/src/main/java/org/telegram/telegrambots/api/interfaces/IBotApiObject.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.telegram.telegrambots.api.interfaces; - -import com.fasterxml.jackson.databind.JsonSerializable; - -import java.io.Serializable; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief An object of Telegram Bots Api - * @date 07 of September of 2015 - */ -public interface IBotApiObject extends JsonSerializable, Serializable { -} diff --git a/src/main/java/org/telegram/telegrambots/api/interfaces/IToJson.java b/src/main/java/org/telegram/telegrambots/api/interfaces/IToJson.java deleted file mode 100644 index c58b6b12..00000000 --- a/src/main/java/org/telegram/telegrambots/api/interfaces/IToJson.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.telegram.telegrambots.api.interfaces; - -import org.json.JSONObject; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief Add conversion to JSON object - * @date 08 of September of 2015 - */ -public interface IToJson { - - /** - * Convert to json object - * @return JSONObject created in the conversion - */ - JSONObject toJson(); -} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java b/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java deleted file mode 100644 index db1a79cf..00000000 --- a/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java +++ /dev/null @@ -1,29 +0,0 @@ -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; - } - - @Override - public String toString() { - return text; - } -} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/BotApiMethod.java b/src/main/java/org/telegram/telegrambots/api/methods/BotApiMethod.java deleted file mode 100644 index 3380b582..00000000 --- a/src/main/java/org/telegram/telegrambots/api/methods/BotApiMethod.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.telegram.telegrambots.api.methods; - -import com.fasterxml.jackson.databind.JsonSerializable; - -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IToJson; -import org.telegram.telegrambots.api.interfaces.Validable; - -import java.io.Serializable; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief A method of Telegram Bots Api that is fully supported in json format - * @date 07 of September of 2015 - */ -public abstract class BotApiMethod implements JsonSerializable, IToJson, Validable { - protected static final String METHOD_FIELD = "method"; - - /** - * Getter for method path (that is the same as method name) - * @return Method path - */ - public abstract String getPath(); - - /** - * Deserialize a json answer to the response type to a method - * @param answer Json answer received - * @return Answer for the method - */ - public abstract T deserializeResponse(JSONObject answer); -} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/GetMe.java b/src/main/java/org/telegram/telegrambots/api/methods/GetMe.java deleted file mode 100644 index 56b65639..00000000 --- a/src/main/java/org/telegram/telegrambots/api/methods/GetMe.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.telegram.telegrambots.api.methods; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; - -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; -import org.telegram.telegrambots.api.objects.User; -import org.telegram.telegrambots.exceptions.TelegramApiValidationException; - -import java.io.IOException; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief A simple method for testing your bot's auth token. Requires no parameters. - * Returns basic information about the bot in form of a User object - * @date 20 of June of 2015 - */ -public class GetMe extends BotApiMethod { - public static final String PATH = "getme"; - - @Override - public JSONObject toJson() { - return new JSONObject(); - } - - @Override - public String getPath() { - return PATH; - } - - @Override - public User deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new User(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); - } - return null; - } - - @Override - public void validate() throws TelegramApiValidationException { - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeEndObject(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - -} 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 deleted file mode 100644 index d62b675c..00000000 --- a/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java +++ /dev/null @@ -1,70 +0,0 @@ -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 org.telegram.telegrambots.exceptions.TelegramApiValidationException; - -import java.io.IOException; - -/** - * @author Ruben Bermudez - * @version 2.4 - * @brief Use this method to get current webhook status. - * Requires no parameters. - * On success, returns a WebhookInfo object. - * Will throw an error, if the bot is using getUpdates. - * - * @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 validate() throws TelegramApiValidationException { - } - - @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/ChatMember.java b/src/main/java/org/telegram/telegrambots/api/objects/ChatMember.java deleted file mode 100644 index 9a022778..00000000 --- a/src/main/java/org/telegram/telegrambots/api/objects/ChatMember.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.telegram.telegrambots.api.objects; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; - -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; - -import java.io.IOException; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief This object contains information about one member of the chat. - * @date 20 of May of 2016 - */ -public class ChatMember implements IBotApiObject { - private static final String USER_FIELD = "user"; - private static final String STATUS_FIELD = "status"; - - private User user; ///< Information about the user - private String status; ///< The member's status in the chat. Can be “creator”, “administrator”, “member”, “left” or “kicked” - - public ChatMember(JSONObject object) { - user = new User(object.getJSONObject(USER_FIELD)); - status = object.getString(STATUS_FIELD); - } - - public User getUser() { - return user; - } - - public String getStatus() { - return status; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeObjectField(USER_FIELD, user); - gen.writeStringField(STATUS_FIELD, status); - gen.writeEndObject(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public String toString() { - return "ChatMember{" + - "user=" + user + - ", status='" + status + '\'' + - '}'; - } -} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Location.java b/src/main/java/org/telegram/telegrambots/api/objects/Location.java deleted file mode 100644 index 979f73be..00000000 --- a/src/main/java/org/telegram/telegrambots/api/objects/Location.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.telegram.telegrambots.api.objects; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; - -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; - -import java.io.IOException; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief This object represents a point on the map. - * @date 20 of June of 2015 - */ -public class Location implements IBotApiObject { - - private static final String LONGITUDE_FIELD = "longitude"; - private static final String LATITUDE_FIELD = "latitude"; - @JsonProperty(LONGITUDE_FIELD) - private Double longitude; ///< Longitude as defined by sender - @JsonProperty(LATITUDE_FIELD) - private Double latitude; ///< Latitude as defined by sender - - public Location() { - super(); - } - - public Location(JSONObject jsonObject) { - super(); - this.longitude = jsonObject.getDouble(LONGITUDE_FIELD); - this.latitude = jsonObject.getDouble(LATITUDE_FIELD); - } - - public Double getLongitude() { - return longitude; - } - - public Double getLatitude() { - return latitude; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public String toString() { - return "Location{" + - "longitude=" + longitude + - ", latitude=" + latitude + - '}'; - } -} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/UserProfilePhotos.java b/src/main/java/org/telegram/telegrambots/api/objects/UserProfilePhotos.java deleted file mode 100644 index f9d81817..00000000 --- a/src/main/java/org/telegram/telegrambots/api/objects/UserProfilePhotos.java +++ /dev/null @@ -1,91 +0,0 @@ -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.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief This object represent a user's profile pictures. - * @date 22 of June of 2015 - */ -public class UserProfilePhotos implements IBotApiObject { - - private static final String TOTALCOUNT_FIELD = "total_count"; - private static final String PHOTOS_FIELD = "photos"; - @JsonProperty(TOTALCOUNT_FIELD) - private Integer totalCount; ///< Total number of profile pictures the target user has - @JsonProperty(PHOTOS_FIELD) - private List> photos; ///< Requested profile pictures (in up to 4 sizes each) - - public UserProfilePhotos() { - super(); - } - - public UserProfilePhotos(JSONObject jsonObject) { - super(); - this.totalCount = jsonObject.getInt(TOTALCOUNT_FIELD); - if (totalCount > 0) { - this.photos = new ArrayList<>(); - JSONArray photos = jsonObject.getJSONArray(PHOTOS_FIELD); - for (int i = 0; i < photos.length(); i++) { - JSONArray innerArray = photos.getJSONArray(i); - List innerPhotos = new ArrayList<>(); - for (int j = 0; j < innerArray.length(); j++) { - innerPhotos.add(new PhotoSize(innerArray.getJSONObject(j))); - } - this.photos.add(innerPhotos); - } - } - } - - public Integer getTotalCount() { - return totalCount; - } - - public List> getPhotos() { - return photos; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(TOTALCOUNT_FIELD, totalCount); - if (totalCount > 0) { - gen.writeArrayFieldStart(PHOTOS_FIELD); - for (List photoSizeList : photos) { - gen.writeStartArray(); - for (PhotoSize photoSize: photoSizeList) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - } - gen.writeEndArray(); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public String toString() { - return "UserProfilePhotos{" + - "totalCount=" + totalCount + - ", photos=" + photos + - '}'; - } -} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/games/CallbackGame.java b/src/main/java/org/telegram/telegrambots/api/objects/games/CallbackGame.java deleted file mode 100644 index 7a260d97..00000000 --- a/src/main/java/org/telegram/telegrambots/api/objects/games/CallbackGame.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of TelegramBots. - * - * TelegramBots is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * TelegramBots is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with TelegramBots. If not, see . - */ - -package org.telegram.telegrambots.api.objects.games; - -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.4 - * @brief A placeholder, currently holds no information. Use BotFather to set up your game. - * @date 16 of September of 2016 - */ -public class CallbackGame implements IBotApiObject { - private final JSONObject content; - - public CallbackGame(JSONObject object) { - super(); - content = object; - } - - public JSONObject getContent() { - return content; - } - - public String getContentText() { - return content.toString(); - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeObject(content); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public String toString() { - return "CallbackGame{" + - "content=" + content + - '}'; - } -} diff --git a/src/main/java/org/telegram/telegrambots/bots/BotOptions.java b/src/main/java/org/telegram/telegrambots/bots/BotOptions.java deleted file mode 100644 index 081481a9..00000000 --- a/src/main/java/org/telegram/telegrambots/bots/BotOptions.java +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 6d4b8da5..00000000 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.telegram.telegrambots.bots; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief Base abstract class for a bot that will get updates using - * long-polling method - * @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/TelegramWebhookBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java deleted file mode 100644 index a5e7bdc7..00000000 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.telegram.telegrambots.bots; - -/** - * @author Ruben Bermudez - * @version 1.0 - * @brief Base abstract class for a bot that will receive updates using a - * webhook - * @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/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml new file mode 100644 index 00000000..917bc462 --- /dev/null +++ b/telegrambots-meta/pom.xml @@ -0,0 +1,197 @@ + + + 4.0.0 + org.telegram + telegrambots-meta + 2.4.1 + jar + + Telegram Bots Meta + https://github.com/rubenlagus/TelegramBots + Easy to use library to create Telegram Bots + + + https://github.com/rubenlagus/TelegramBots/issues + GitHub Issues + + + + https://github.com/rubenlagus/TelegramBots + scm:git:git://github.com/rubenlagus/TelegramBots.git + scm:git:git@github.com:rubenlagus/TelegramBots.git + + + + + rberlopez@gmail.com + Ruben Bermudez + https://github.com/rubenlagus + rubenlagus + + + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + repo + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + UTF-8 + UTF-8 + 4.1.0 + 2.8.5 + 20160810 + 4.12 + + + + + com.google.inject + guice + ${guice.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + org.json + json + ${json.version} + + + junit + junit + ${junit.version} + test + + + + + ${project.basedir}/target + ${project.build.directory}/classes + ${project.artifactId}-${project.version} + ${project.build.directory}/test-classes + ${project.basedir}/src/main/java + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + true + + + + 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 + + + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + + jar + + + -Xdoclint:none + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + UTF-8 + + + + + + \ No newline at end of file diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/ApiConstants.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/ApiConstants.java new file mode 100644 index 00000000..2fd218f4 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/ApiConstants.java @@ -0,0 +1,14 @@ +package org.telegram.telegrambots; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Constants needed for Telegram Bots API + * @date 20 of June of 2015 + */ +public class ApiConstants { + public static final String BASE_URL = "https://api.telegram.org/bot"; + public static final int GETUPDATES_TIMEOUT = 50; + public static final String RESPONSE_FIELD_OK = "ok"; + public static final String RESPONSE_FIELD_RESULT = "result"; +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/ApiContext.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/ApiContext.java new file mode 100644 index 00000000..76bab484 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/ApiContext.java @@ -0,0 +1,64 @@ +package org.telegram.telegrambots; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Singleton; + +import org.telegram.telegrambots.logging.BotLogger; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Ruben Bermudez + * @version 1.0 + */ +public class ApiContext { + private static final Object lock = new Object(); + private static Injector INJECTOR; + private static Map bindings = new HashMap<>(); + private static Map singletonBindings = new HashMap<>(); + + public static T getInstance(Class type) { + return getInjector().getInstance(type); + } + + public static void register(Class type, Class implementation) { + if (bindings.containsKey(type)) { + BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName())); + } + bindings.put(type, implementation); + } + + public static void registerSingleton(Class type, Class implementation) { + if (singletonBindings.containsKey(type)) { + BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName())); + } + singletonBindings.put(type, implementation); + } + + private static Injector getInjector() { + if (INJECTOR == null) { + synchronized (lock) { + if (INJECTOR == null) { + INJECTOR = Guice.createInjector(new ApiModule()); + } + } + } + return INJECTOR; + } + + private static class ApiModule extends AbstractModule { + @Override + protected void configure() { + for (Map.Entry binding : bindings.entrySet()) { + bind(binding.getKey()).to(binding.getValue()); + } + for (Map.Entry binding : singletonBindings.entrySet()) { + bind(binding.getKey()).to(binding.getValue()).in(Singleton.class); + } + } + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java new file mode 100644 index 00000000..3978c0a3 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -0,0 +1,108 @@ +package org.telegram.telegrambots; + +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.generics.BotSession; +import org.telegram.telegrambots.generics.LongPollingBot; +import org.telegram.telegrambots.generics.Webhook; +import org.telegram.telegrambots.generics.WebhookBot; + +import java.text.MessageFormat; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Bots manager + * @date 14 of January of 2016 + */ +public class TelegramBotsApi { + 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 + + /** + * + */ + public TelegramBotsApi() { + } + + /** + * + * @param keyStore KeyStore for the server + * @param keyStorePassword Key store password for the server + * @param externalUrl External base url for the webhook + * @param internalUrl Internal base url for the webhook + */ + public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiRequestException { + if (externalUrl == null || externalUrl.isEmpty()) { + throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); + } + if (internalUrl == null || internalUrl.isEmpty()) { + throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); + } + + this.useWebhook = true; + this.extrenalUrl = fixExternalUrl(externalUrl); + webhook = ApiContext.getInstance(Webhook.class); + webhook.setInternalUrl(internalUrl); + webhook.setKeyStore(keyStore, keyStorePassword); + webhook.startServer(); + } + + /** + * + * @param keyStore KeyStore for the server + * @param keyStorePassword Key store password for the server + * @param externalUrl External base url for the webhook + * @param internalUrl Internal base url for the webhook + * @param pathToCertificate Full path until .pem public certificate keys + */ + public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiRequestException { + if (externalUrl == null || externalUrl.isEmpty()) { + throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); + } + if (internalUrl == null || internalUrl.isEmpty()) { + throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); + } + this.useWebhook = true; + this.extrenalUrl = fixExternalUrl(externalUrl); + this.pathToCertificate = pathToCertificate; + webhook = ApiContext.getInstance(Webhook.class); + webhook.setInternalUrl(internalUrl); + webhook.setKeyStore(keyStore, keyStorePassword); + 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(LongPollingBot bot) throws TelegramApiRequestException { + bot.clearWebhook(); + BotSession session = ApiContext.getInstance(BotSession.class); + session.setToken(bot.getBotToken()); + session.setOptions(bot.getOptions()); + session.setCallback(bot); + session.start(); + return session; + } + + /** + * Register a bot in the api that will receive updates using webhook method + * @param bot Bot to register + */ + public void registerBot(WebhookBot bot) throws TelegramApiRequestException { + if (useWebhook) { + webhook.registerWebhook(bot); + bot.setWebhook(extrenalUrl + bot.getBotPath(), pathToCertificate); + } + } + + private static String fixExternalUrl(String externalUrl) { + if (externalUrl != null && !externalUrl.endsWith("/")) { + externalUrl = externalUrl + "/"; + } + return MessageFormat.format(webhookUrlFormat, externalUrl); + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/BotApiObject.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/BotApiObject.java new file mode 100644 index 00000000..f60bf13d --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/BotApiObject.java @@ -0,0 +1,16 @@ +package org.telegram.telegrambots.api.interfaces; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; + +import java.io.Serializable; + +/** + * @author Ruben Bermudez + * @version 1.0 + * An object from the Bots API received from Telegram Servers + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public interface BotApiObject extends Serializable { +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/InputBotApiObject.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/InputBotApiObject.java new file mode 100644 index 00000000..8fb68c0b --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/InputBotApiObject.java @@ -0,0 +1,18 @@ +package org.telegram.telegrambots.api.interfaces; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import java.io.Serializable; + +/** + * @author Ruben Bermudez + * @version 1.0 + * An object used in the Bots API to answer updates + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") +public interface InputBotApiObject extends Serializable { +} diff --git a/src/main/java/org/telegram/telegrambots/api/interfaces/Validable.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/Validable.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/api/interfaces/Validable.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/interfaces/Validable.java diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java new file mode 100644 index 00000000..7a85db3d --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java @@ -0,0 +1,55 @@ +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; + } + + @Override + public String toString() { + return text; + } + + public static ActionType get(String text) { + if (text == null) { + return null; + } + 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; + default: + return null; + } + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java similarity index 64% rename from src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java index 125ef24d..59390331 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java @@ -1,12 +1,10 @@ package org.telegram.telegrambots.api.methods; 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 com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; @@ -37,13 +35,13 @@ public class AnswerCallbackQuery extends BotApiMethod { private String text; ///< Optional Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters @JsonProperty(SHOWALERT_FIELD) private Boolean showAlert; ///< Optional. If true, an alert will be shown by the client instead of a notificaiton at the top of the chat screen. Defaults to false. - @JsonProperty(URL_FIELD) /** * Optional. URL that will be opened by the user's client. * If you have created a Game and accepted the conditions via @Botfather, * specify the URL that opens your game. Otherwise you may use links * InlineQueryResultGamelike telegram.me/your_bot?start=XXXX that open your bot with a parameter. */ + @JsonProperty(URL_FIELD) private String url; public AnswerCallbackQuery() { @@ -54,8 +52,9 @@ public class AnswerCallbackQuery extends BotApiMethod { return this.callbackQueryId; } - public void setCallbackQueryId(String callbackQueryId) { + public AnswerCallbackQuery setCallbackQueryId(String callbackQueryId) { this.callbackQueryId = callbackQueryId; + return this; } public String getText() { @@ -86,32 +85,23 @@ public class AnswerCallbackQuery extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CALLBACKQUERYID_FIELD, callbackQueryId); - if (text != null) { - jsonObject.put(TEXT_FIELD, text); - } - if (showAlert != null) { - jsonObject.put(SHOWALERT_FIELD, showAlert); - } - if (url != null) { - jsonObject.put(URL_FIELD, url); - } - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Boolean deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getBoolean(Constants.RESPONSEFIELDRESULT); + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error answering callback query", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -121,29 +111,6 @@ public class AnswerCallbackQuery extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CALLBACKQUERYID_FIELD, callbackQueryId); - if (text != null) { - gen.writeStringField(TEXT_FIELD, text); - } - if (showAlert != null) { - gen.writeBooleanField(SHOWALERT_FIELD, showAlert); - } - if (url != null) { - gen.writeStringField(URL_FIELD, url); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "AnswerCallbackQuery{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/AnswerInlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/AnswerInlineQuery.java similarity index 62% rename from src/main/java/org/telegram/telegrambots/api/methods/AnswerInlineQuery.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/AnswerInlineQuery.java index 54ba81c7..115202e9 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/AnswerInlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/AnswerInlineQuery.java @@ -1,23 +1,22 @@ package org.telegram.telegrambots.api.methods; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** * @author Ruben Bermudez * @version 1.0 - * @brief Use this method to send answers to an inline query. On success, True is returned. - * @date 01 of January of 2016 + * Use this method to send answers to an inline query. On success, True is returned. */ public class AnswerInlineQuery extends BotApiMethod { public static final String PATH = "answerInlineQuery"; @@ -29,12 +28,20 @@ public class AnswerInlineQuery extends BotApiMethod { private static final String NEXTOFFSET_FIELD = "next_offset"; private static final String SWITCH_PM_TEXT_FIELD = "switch_pm_text"; private static final String SWITCH_PM_PARAMETER_FIELD = "switch_pm_parameter"; + + @JsonProperty(INLINEQUERYID_FIELD) private String inlineQueryId; ///< Unique identifier for answered query + @JsonProperty(RESULTS_FIELD) private List results; ///< A JSON-serialized array of results for the inline query + @JsonProperty(CACHETIME_FIELD) private Integer cacheTime; ///< Optional The maximum amount of time the result of the inline query may be cached on the server + @JsonProperty(ISPERSONAL_FIELD) private Boolean isPersonal; ///< Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query + @JsonProperty(NEXTOFFSET_FIELD) private String nextOffset; ///< Optional. Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. + @JsonProperty(SWITCH_PM_TEXT_FIELD) private String switchPmText; ///< Optional. If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter + @JsonProperty(SWITCH_PM_PARAMETER_FIELD) private String switchPmParameter; ///< Optional. Parameter for the start message sent to the bot when user presses the switch button public AnswerInlineQuery() { @@ -59,6 +66,12 @@ public class AnswerInlineQuery extends BotApiMethod { return this; } + @JsonIgnore + public AnswerInlineQuery setResults(InlineQueryResult... results) { + this.results = Arrays.asList(results); + return this; + } + public Integer getCacheTime() { return cacheTime; } @@ -68,10 +81,16 @@ public class AnswerInlineQuery extends BotApiMethod { return this; } + @Deprecated + @JsonIgnore public Boolean getPersonal() { return isPersonal; } + public Boolean isPersonal() { + return isPersonal; + } + public AnswerInlineQuery setPersonal(Boolean personal) { isPersonal = personal; return this; @@ -118,77 +137,23 @@ public class AnswerInlineQuery extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(INLINEQUERYID_FIELD, inlineQueryId); - JSONArray JSONResults = new JSONArray(); - for (InlineQueryResult result: results) { - JSONResults.put(result.toJson()); - } - jsonObject.put(RESULTS_FIELD, JSONResults); - if (cacheTime != null) { - jsonObject.put(CACHETIME_FIELD, cacheTime); - } - if (isPersonal != null) { - jsonObject.put(ISPERSONAL_FIELD, isPersonal); - } - if (nextOffset != null) { - jsonObject.put(NEXTOFFSET_FIELD, nextOffset); - } - if (switchPmText != null) { - jsonObject.put(SWITCH_PM_TEXT_FIELD, switchPmText); - } - if (switchPmParameter != null) { - jsonObject.put(SWITCH_PM_PARAMETER_FIELD, switchPmParameter); - } - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Boolean deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getBoolean(Constants.RESPONSEFIELDRESULT); + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error answering inline query", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeArrayFieldStart(RESULTS_FIELD); - for (InlineQueryResult result: results) { - gen.writeObject(result); - } - gen.writeEndArray(); - if (cacheTime != null) { - gen.writeNumberField(CACHETIME_FIELD, cacheTime); - } - if (isPersonal != null) { - gen.writeBooleanField(ISPERSONAL_FIELD, isPersonal); - } - if (nextOffset != null) { - gen.writeStringField(NEXTOFFSET_FIELD, nextOffset); - } - if (switchPmText != null) { - gen.writeStringField(SWITCH_PM_TEXT_FIELD, switchPmText); - } - if (switchPmParameter != null) { - gen.writeStringField(SWITCH_PM_PARAMETER_FIELD, switchPmParameter); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/BotApiMethod.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/BotApiMethod.java new file mode 100644 index 00000000..2a1e34f2 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/BotApiMethod.java @@ -0,0 +1,26 @@ +package org.telegram.telegrambots.api.methods; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +/** + * @author Ruben Bermudez + * @version 1.0 + * + * A method of Telegram Bots Api that is fully supported in json format + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public abstract class BotApiMethod extends PartialBotApiMethod { + protected static final String METHOD_FIELD = "method"; + + /** + * Getter for method path (that is the same as method name) + * @return Method path + */ + @JsonProperty(METHOD_FIELD) + public abstract String getMethod(); +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java similarity index 65% rename from src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java index 31b4e4e5..bf2e6f25 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java @@ -1,15 +1,15 @@ package org.telegram.telegrambots.api.methods; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -24,8 +24,12 @@ public class ForwardMessage extends BotApiMethod { 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"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels) + @JsonProperty(FROMCHATID_FIELD) private String fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id + @JsonProperty(MESSAGEID_FIELD) private Integer messageId; ///< Unique message identifier /** * Optional. Sends the message silently. @@ -33,6 +37,7 @@ public class ForwardMessage extends BotApiMethod { * Android users will receive a notification with no sound. * Other apps coming soon */ + @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; public ForwardMessage() { @@ -48,6 +53,12 @@ public class ForwardMessage extends BotApiMethod { return this; } + public ForwardMessage setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getFromChatId() { return fromChatId; } @@ -94,47 +105,23 @@ public class ForwardMessage extends BotApiMethod { } @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(FROMCHATID_FIELD, fromChatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - if (disableNotification != null) { - gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(FROMCHATID_FIELD, fromChatId); - jsonObject.put(MESSAGEID_FIELD, messageId); - if (disableNotification != null) { - jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); - } - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error forwarding message", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/GetFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetFile.java similarity index 58% rename from src/main/java/org/telegram/telegrambots/api/methods/GetFile.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetFile.java index 3d44d8c8..a278c3aa 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/GetFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetFile.java @@ -1,12 +1,11 @@ package org.telegram.telegrambots.api.methods; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.objects.File; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; @@ -27,6 +26,8 @@ public class GetFile extends BotApiMethod { public static final String PATH = "getFile"; private static final String FILEID_FIELD = "file_id"; + + @JsonProperty(FILEID_FIELD) private String fileId; ///< File identifier to get info about public GetFile() { @@ -50,37 +51,23 @@ public class GetFile extends BotApiMethod { } @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(FILEID_FIELD, fileId); - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public File deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new File(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public File deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting file", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetMe.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetMe.java new file mode 100644 index 00000000..d2991d55 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetMe.java @@ -0,0 +1,50 @@ +package org.telegram.telegrambots.api.methods; + +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.objects.User; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief A simple method for testing your bot's auth token. Requires no parameters. + * Returns basic information about the bot in form of a User object + * @date 20 of June of 2015 + */ +public class GetMe extends BotApiMethod { + public static final String PATH = "getme"; + + public GetMe() { + super(); + } + + @Override + public String getMethod() { + return PATH; + } + + @Override + public User deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>() { + }); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting me", result); + } + } catch (IOException e2) { + throw new TelegramApiRequestException("Unable to deserialize response", e2); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/GetUserProfilePhotos.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetUserProfilePhotos.java similarity index 61% rename from src/main/java/org/telegram/telegrambots/api/methods/GetUserProfilePhotos.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetUserProfilePhotos.java index 80e68a5c..65c0d117 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/GetUserProfilePhotos.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/GetUserProfilePhotos.java @@ -1,12 +1,11 @@ package org.telegram.telegrambots.api.methods; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.objects.UserProfilePhotos; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; @@ -23,21 +22,24 @@ public class GetUserProfilePhotos extends BotApiMethod { private static final String USERID_FIELD = "user_id"; private static final String OFFSET_FIELD = "offset"; private static final String LIMIT_FIELD = "limit"; + + @JsonProperty(USERID_FIELD) private Integer userId; ///< Unique identifier of the target user /** * Sequential number of the first photo to be returned. By default, all photos are returned. */ + @JsonProperty(OFFSET_FIELD) private Integer offset; /** * Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100. */ + @JsonProperty(LIMIT_FIELD) private Integer limit; public GetUserProfilePhotos() { super(); } - public Integer getUserId() { return userId; } @@ -66,27 +68,23 @@ public class GetUserProfilePhotos extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(USERID_FIELD, userId); - jsonObject.put(OFFSET_FIELD, offset); - if (limit != null) { - jsonObject.put(LIMIT_FIELD, limit); - } - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public UserProfilePhotos deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new UserProfilePhotos(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public UserProfilePhotos deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting user profile photos", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -99,24 +97,6 @@ public class GetUserProfilePhotos extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeNumberField(USERID_FIELD, userId); - gen.writeNumberField(OFFSET_FIELD, offset); - if (limit != null) { - gen.writeNumberField(LIMIT_FIELD, limit); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "GetUserProfilePhotos{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ParseMode.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ParseMode.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/api/methods/ParseMode.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/ParseMode.java diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/PartialBotApiMethod.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/PartialBotApiMethod.java new file mode 100644 index 00000000..d8a49e94 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/PartialBotApiMethod.java @@ -0,0 +1,26 @@ +package org.telegram.telegrambots.api.methods; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.telegram.telegrambots.api.interfaces.Validable; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; + +import java.io.Serializable; + +/** + * @author Ruben Bermudez + * @version 1.0 + * Api method that can't be use completely as Json + */ +public abstract class PartialBotApiMethod implements Validable { + @JsonIgnore + protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** + * Deserialize a json answer to the response type to a method + * @param answer Json answer received + * @return Answer for the method + */ + public abstract T deserializeResponse(String answer) throws TelegramApiRequestException; +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/games/GetGameHighScores.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/games/GetGameHighScores.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/methods/games/GetGameHighScores.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/games/GetGameHighScores.java index 3d0490bc..4c15322d 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/games/GetGameHighScores.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/games/GetGameHighScores.java @@ -16,19 +16,18 @@ */ package org.telegram.telegrambots.api.methods.games; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.games.GameHighScore; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; import java.util.ArrayList; +import java.util.Objects; /** * @author Ruben Bermudez @@ -52,12 +51,17 @@ public class GetGameHighScores extends BotApiMethod> { private static final String INLINE_MESSAGE_ID_FIELD = "inline_message_id"; private static final String USER_ID_FIELD = "user_id"; + @JsonProperty(CHATID_FIELD) private String chatId; ///< Optional Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) + @JsonProperty(MESSAGEID_FIELD) private Integer messageId; ///< Optional Required if inline_message_id is not specified. Unique identifier of the sent message + @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message + @JsonProperty(USER_ID_FIELD) private Integer userId; ///> { return this; } + public GetGameHighScores setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public GetGameHighScores setMessageId(Integer messageId) { this.messageId = messageId; return this; @@ -97,21 +107,23 @@ public class GetGameHighScores extends BotApiMethod> { } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public ArrayList deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - JSONArray highScores = answer.getJSONArray(Constants.RESPONSEFIELDRESULT); - ArrayList scores = new ArrayList<>(); - for (int i = 0; i < highScores.length(); i++) { - scores.add(new GameHighScore(highScores.getJSONObject(i))); + public ArrayList deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse> result = OBJECT_MAPPER.readValue(answer, + new TypeReference>>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting game high scores", result); } - return scores; + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -136,41 +148,6 @@ public class GetGameHighScores extends BotApiMethod> { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - if (chatId != null) { - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - } - if (inlineMessageId != null) { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - gen.writeNumberField(USER_ID_FIELD, userId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - if (chatId != null) { - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(MESSAGEID_FIELD, messageId); - } - if (inlineMessageId != null) { - jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - jsonObject.put(USER_ID_FIELD, userId); - - return jsonObject; - } - @Override public String toString() { return "GetGameHighScores{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/games/SetGameScore.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/games/SetGameScore.java similarity index 71% rename from src/main/java/org/telegram/telegrambots/api/methods/games/SetGameScore.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/games/SetGameScore.java index d0f3c08e..43b6276f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/games/SetGameScore.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/games/SetGameScore.java @@ -17,18 +17,18 @@ package org.telegram.telegrambots.api.methods.games; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; import java.io.Serializable; +import java.util.Objects; /** * @author Ruben Bermudez @@ -50,14 +50,21 @@ public class SetGameScore extends BotApiMethod { private static final String INLINE_MESSAGE_ID_FIELD = "inline_message_id"; private static final String EDIT_MESSAGE_FIELD = "edit_message"; + @JsonProperty(CHATID_FIELD) private String chatId; ///< Optional Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) + @JsonProperty(MESSAGEID_FIELD) private Integer messageId; ///< Optional Required if inline_message_id is not specified. Unique identifier of the sent message + @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message + @JsonProperty(EDIT_MESSAGE_FIELD) private Boolean editMessage; ///< Optional Pass True, if the message should be edited to include the current scoreboard + @JsonProperty(USER_ID_FIELD) private Integer userId; ///< User identifier + @JsonProperty(SCORE_FIELD) private Integer score; ///< New score, must be positive public SetGameScore() { + super(); } public String getChatId() { @@ -89,6 +96,12 @@ public class SetGameScore extends BotApiMethod { return this; } + public SetGameScore setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public SetGameScore setMessageId(Integer messageId) { this.messageId = messageId; return this; @@ -115,22 +128,34 @@ public class SetGameScore extends BotApiMethod { } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Serializable deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - Object result = answer.get(Constants.RESPONSEFIELDRESULT); - if (result instanceof Boolean) { - return (Boolean) result; + public Serializable deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error setting game score", result); } - if (result instanceof JSONObject) { - return new Message((JSONObject) result); + } catch (IOException e) { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>() { + }); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error setting game score", result); + } + } catch (IOException e2) { + throw new TelegramApiRequestException("Unable to deserialize response", e2); } } - return null; } @Override @@ -158,49 +183,6 @@ public class SetGameScore extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - if (chatId != null) { - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - } - if (inlineMessageId != null) { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - if (editMessage != null) { - gen.writeBooleanField(EDIT_MESSAGE_FIELD, editMessage); - } - gen.writeNumberField(USER_ID_FIELD, userId); - gen.writeNumberField(SCORE_FIELD, score); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - if (chatId != null) { - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(MESSAGEID_FIELD, messageId); - } - if (inlineMessageId != null) { - jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - if (editMessage != null) { - jsonObject.put(EDIT_MESSAGE_FIELD, editMessage); - } - jsonObject.put(USER_ID_FIELD, userId); - jsonObject.put(SCORE_FIELD, score); - - return jsonObject; - } - @Override public String toString() { return "SetGameScore{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChat.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChat.java similarity index 54% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChat.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChat.java index c90a36fa..f5e43108 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChat.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChat.java @@ -1,16 +1,16 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Chat; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -22,6 +22,8 @@ public class GetChat extends BotApiMethod { public static final String PATH = "getChat"; private static final String CHATID_FIELD = "chat_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public GetChat() { @@ -37,24 +39,30 @@ public class GetChat extends BotApiMethod { return this; } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - return jsonObject; + public GetChat setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Chat deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Chat(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Chat deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting chat", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -64,20 +72,6 @@ public class GetChat extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "GetChat{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatAdministrators.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatAdministrators.java similarity index 55% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatAdministrators.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatAdministrators.java index ca98c41a..2e8be8e0 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatAdministrators.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatAdministrators.java @@ -1,18 +1,17 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.ChatMember; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; import java.util.ArrayList; +import java.util.Objects; /** * @author Ruben Bermudez @@ -28,6 +27,8 @@ public class GetChatAdministrators extends BotApiMethod> { public static final String PATH = "getChatAdministrators"; private static final String CHATID_FIELD = "chat_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public GetChatAdministrators() { @@ -43,29 +44,30 @@ public class GetChatAdministrators extends BotApiMethod> { return this; } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - return jsonObject; + public GetChatAdministrators setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public ArrayList deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - JSONArray admins = answer.getJSONArray(Constants.RESPONSEFIELDRESULT); - ArrayList members = new ArrayList<>(); - for (int i = 0; i < admins.length(); i++) { - members.add(new ChatMember(admins.getJSONObject(i))); + public ArrayList deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse> result = OBJECT_MAPPER.readValue(answer, + new TypeReference>>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting chat administrators", result); } - return members; + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -75,20 +77,6 @@ public class GetChatAdministrators extends BotApiMethod> { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "GetChatAdministrators{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java similarity index 60% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java index 651f85a3..26e3555e 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java @@ -1,16 +1,16 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.ChatMember; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -24,7 +24,10 @@ public class GetChatMember extends BotApiMethod { private static final String CHATID_FIELD = "chat_id"; private static final String USERID_FIELD = "user_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(USERID_FIELD) private Integer userId; ///< Unique identifier of the target user public GetChatMember() { @@ -40,6 +43,12 @@ public class GetChatMember extends BotApiMethod { return this; } + public GetChatMember setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getUserId() { return userId; } @@ -50,24 +59,23 @@ public class GetChatMember extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(USERID_FIELD, userId); - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public ChatMember deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new ChatMember(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public ChatMember deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting chat member", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -80,21 +88,6 @@ public class GetChatMember extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(USERID_FIELD, userId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "GetChatMember{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java similarity index 54% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java index 7c413b6b..23f2068d 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java @@ -1,15 +1,15 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -21,6 +21,8 @@ public class GetChatMemberCount extends BotApiMethod { public static final String PATH = "getChatMembersCount"; private static final String CHATID_FIELD = "chat_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public GetChatMemberCount() { @@ -36,24 +38,30 @@ public class GetChatMemberCount extends BotApiMethod { return this; } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - return jsonObject; + public GetChatMemberCount setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Integer deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getInt(Constants.RESPONSEFIELDRESULT); + public Integer deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting chat member count", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -63,20 +71,6 @@ public class GetChatMemberCount extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "GetChatMemberCount{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java similarity index 64% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java index 56e7e1f0..b55027d7 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java @@ -1,15 +1,15 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -28,7 +28,10 @@ public class KickChatMember extends BotApiMethod { private static final String CHATID_FIELD = "chat_id"; private static final String USER_ID_FIELD = "user_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(USER_ID_FIELD) private Integer userId; ///< Unique identifier of the target user public KickChatMember() { @@ -44,6 +47,12 @@ public class KickChatMember extends BotApiMethod { return this; } + public KickChatMember setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getUserId() { return userId; } @@ -54,24 +63,23 @@ public class KickChatMember extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(USER_ID_FIELD, userId); - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Boolean deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getBoolean(Constants.RESPONSEFIELDRESULT); + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error kicking chat member", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -84,21 +92,6 @@ public class KickChatMember extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(USER_ID_FIELD, userId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "KickChatMember{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/LeaveChat.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/LeaveChat.java similarity index 54% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/LeaveChat.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/LeaveChat.java index b2c671fc..10a2861a 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/LeaveChat.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/LeaveChat.java @@ -1,15 +1,15 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -21,6 +21,8 @@ public class LeaveChat extends BotApiMethod { public static final String PATH = "leaveChat"; private static final String CHATID_FIELD = "chat_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) public LeaveChat() { @@ -36,24 +38,30 @@ public class LeaveChat extends BotApiMethod { return this; } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - return jsonObject; + public LeaveChat setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Boolean deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getBoolean(Constants.RESPONSEFIELDRESULT); + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error leaving chat", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -63,20 +71,6 @@ public class LeaveChat extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "LeaveChat{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java similarity index 61% rename from src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java index 931eaaf1..b2448999 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java @@ -1,15 +1,15 @@ package org.telegram.telegrambots.api.methods.groupadministration; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -24,7 +24,10 @@ public class UnbanChatMember extends BotApiMethod { private static final String CHATID_FIELD = "chat_id"; private static final String USER_ID_FIELD = "user_id"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(USER_ID_FIELD) private Integer userId; ///< Unique identifier of the target user public UnbanChatMember() { @@ -40,6 +43,12 @@ public class UnbanChatMember extends BotApiMethod { return this; } + public UnbanChatMember setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getUserId() { return userId; } @@ -50,24 +59,23 @@ public class UnbanChatMember extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(USER_ID_FIELD, userId); - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Boolean deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getBoolean(Constants.RESPONSEFIELDRESULT); + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error unbanning chat member", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -80,21 +88,6 @@ public class UnbanChatMember extends BotApiMethod { } } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(USER_ID_FIELD, userId); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "UnbanChatMember{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java similarity index 75% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index b79f9922..0bd726cd 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.api.methods.send; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.Objects; @@ -16,7 +24,7 @@ import java.util.Objects; * @note For sending voice notes, use sendVoice method instead. * @date 16 of July of 2015 */ -public class SendAudio { +public class SendAudio extends PartialBotApiMethod { public static final String PATH = "sendaudio"; public static final String DURATION_FIELD = "duration"; @@ -70,6 +78,12 @@ public class SendAudio { return this; } + public SendAudio setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getAudio() { return audio; } @@ -92,7 +106,6 @@ public class SendAudio { * @param file New audio file */ public SendAudio setNewAudio(File file) { - this.audio = file.getName(); this.isNewAudio = true; this.newAudioFile = file; return this; @@ -182,6 +195,43 @@ public class SendAudio { return this; } + @Override + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending audio", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + + if (isNewAudio) { + if (newAudioFile == null && newAudioStream == null) { + throw new TelegramApiValidationException("Audio can't be empty", this); + } + if (newAudioStream != null && (audioName == null || audioName.isEmpty())) { + throw new TelegramApiValidationException("Audio name can't be empty", this); + } + } else if (audio == null) { + throw new TelegramApiValidationException("Audio can't be empty", this); + } + + if (replyMarkup != null) { + replyMarkup.validate(); + } + } + @Override public String toString() { return "SendAudio{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java similarity index 59% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java index dd9d6277..46bcafbb 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java @@ -1,16 +1,17 @@ package org.telegram.telegrambots.api.methods.send; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.ActionType; import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -26,6 +27,8 @@ public class SendChatAction extends BotApiMethod { public static final String CHATID_FIELD = "chat_id"; public static final String ACTION_FIELD = "action"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) /** * Type of action to broadcast. Choose one, depending on what the user is about to receive: @@ -33,32 +36,57 @@ 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 ActionType action; + @JsonProperty(ACTION_FIELD) + private String action; + + public SendChatAction() { + super(); + } public String getChatId() { return chatId; } + @JsonIgnore + public ActionType getAction() { + return ActionType.get(action); + } + public SendChatAction setChatId(String chatId) { this.chatId = chatId; return this; } - public void setAction(ActionType action) { - this.action = action; + public SendChatAction setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + + @JsonIgnore + public SendChatAction setAction(ActionType action) { + this.action = action.toString(); + return this; } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Boolean deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return answer.getBoolean(Constants.RESPONSEFIELDRESULT); + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending chat action", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -71,27 +99,6 @@ public class SendChatAction extends BotApiMethod { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(ACTION_FIELD, action); - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(ACTION_FIELD, action.toString()); - gen.writeEndObject(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "SendChatAction{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java similarity index 65% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java index 734eb89a..1e0765fc 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java @@ -1,17 +1,17 @@ package org.telegram.telegrambots.api.methods.send; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -30,18 +30,30 @@ public class SendContact extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(PHONE_NUMBER_FIELD) private String phoneNumber; ///< User's phone number + @JsonProperty(FIRST_NAME_FIELD) private String firstName; ///< User's first name + @JsonProperty(LAST_NAME_FIELD) private String lastName; ///< Optional. User's last name /** * 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 */ + @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; + @JsonProperty(REPLYTOMESSAGEID_FIELD) private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + public SendContact() { + super(); + } + public String getChatId() { return chatId; } @@ -51,6 +63,12 @@ public class SendContact extends BotApiMethod { return this; } + public SendContact setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getReplyToMessageId() { return replyToMessageId; } @@ -111,16 +129,23 @@ public class SendContact extends BotApiMethod { } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending contact", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -134,57 +159,9 @@ public class SendContact extends BotApiMethod { if (firstName == null) { throw new TelegramApiValidationException("FirstName parameter can't be empty", this); } - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(PHONE_NUMBER_FIELD, phoneNumber); - jsonObject.put(FIRST_NAME_FIELD, firstName); - if (lastName != null) { - jsonObject.put(LAST_NAME_FIELD, lastName); - } - if (disableNotification != null) { - jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); + replyMarkup.validate(); } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(PHONE_NUMBER_FIELD, phoneNumber); - gen.writeStringField(FIRST_NAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LAST_NAME_FIELD, lastName); - } - if (disableNotification != null) { - gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java similarity index 69% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index 465b738e..82ccf0ee 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.api.methods.send; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.Objects; @@ -12,7 +20,7 @@ import java.util.Objects; * @brief Use this method to send general files. On success, the sent Message is returned. * @date 20 of June of 2015 */ -public class SendDocument { +public class SendDocument extends PartialBotApiMethod { public static final String PATH = "senddocument"; public static final String CHATID_FIELD = "chat_id"; @@ -50,6 +58,12 @@ public class SendDocument { return this; } + public SendDocument setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getDocument() { return document; } @@ -72,7 +86,7 @@ public class SendDocument { * @param file New document file */ public SendDocument setNewDocument(File file) { - this.document = file.getName(); + Objects.requireNonNull(file, "documentName cannot be null!"); this.isNewDocument = true; this.newDocumentFile = file; return this; @@ -144,6 +158,43 @@ public class SendDocument { return this; } + @Override + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending document", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + + if (isNewDocument) { + if (newDocumentFile == null && newDocumentStream == null) { + throw new TelegramApiValidationException("Document can't be empty", this); + } + if (newDocumentStream != null && (documentName == null || documentName.isEmpty())) { + throw new TelegramApiValidationException("Document name can't be empty", this); + } + } else if (document == null) { + throw new TelegramApiValidationException("Document can't be empty", this); + } + + if (replyMarkup != null) { + replyMarkup.validate(); + } + } + @Override public String toString() { return "SendDocument{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendGame.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendGame.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendGame.java index 0b50d0da..54bb240d 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendGame.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendGame.java @@ -17,18 +17,18 @@ package org.telegram.telegrambots.api.methods.send; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -45,14 +45,19 @@ public class SendGame extends BotApiMethod { private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(GAMESHORTNAME_FIELD) private String gameShortName; ///< Short name of the game /** * 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 */ + @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; + @JsonProperty(REPLYTOMESSAGEID_FIELD) private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public SendGame() { @@ -68,6 +73,12 @@ public class SendGame extends BotApiMethod { return this; } + public SendGame setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getReplyToMessageId() { return replyToMessageId; } @@ -110,34 +121,23 @@ public class SendGame extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(GAMESHORTNAME_FIELD, gameShortName); - if (disableNotification != null) { - jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } - if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); - } - - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending game", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -148,30 +148,9 @@ public class SendGame extends BotApiMethod { if (gameShortName == null || gameShortName.isEmpty()) { throw new TelegramApiValidationException("GameShortName parameter can't be empty", this); } - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(GAMESHORTNAME_FIELD, gameShortName); - if (disableNotification != null) { - gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); + replyMarkup.validate(); } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java similarity index 66% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java index a9b483b0..e36a2927 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java @@ -1,17 +1,17 @@ package org.telegram.telegrambots.api.methods.send; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -28,17 +28,28 @@ public class SendLocation extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(LATITUDE_FIELD) private Float latitude; ///< Latitude of location + @JsonProperty(LONGITUDE_FIELD) private Float longitude; ///< Longitude of location /** * 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 */ + @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; + @JsonProperty(REPLYTOMESSAGEID_FIELD) private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + public SendLocation() { + super(); + } + public String getChatId() { return chatId; } @@ -48,6 +59,12 @@ public class SendLocation extends BotApiMethod { return this; } + public SendLocation setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Float getLatitude() { return latitude; } @@ -99,16 +116,23 @@ public class SendLocation extends BotApiMethod { } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending location", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -122,51 +146,9 @@ public class SendLocation extends BotApiMethod { if (longitude == null) { throw new TelegramApiValidationException("Longitude parameter can't be empty", this); } - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(LATITUDE_FIELD, latitude); - jsonObject.put(LONGITUDE_FIELD, longitude); - if (disableNotification != null) { - jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); + replyMarkup.validate(); } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - if (disableNotification != null) { - gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java similarity index 66% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java index 209e2cff..42db3e56 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java @@ -1,18 +1,18 @@ package org.telegram.telegrambots.api.methods.send; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.methods.ParseMode; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -30,16 +30,24 @@ public class SendMessage extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(TEXT_FIELD) private String text; ///< Text of the message to be sent + @JsonProperty(PARSEMODE_FIELD) private String parseMode; ///< Optional. Send Markdown, if you want Telegram apps to show bold, italic and URL text in your bot's message. + @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this 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 */ + @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; + @JsonProperty(REPLYTOMESSAGEID_FIELD) private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public SendMessage() { @@ -55,6 +63,12 @@ public class SendMessage extends BotApiMethod { return this; } + public SendMessage setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getText() { return text; } @@ -110,6 +124,11 @@ public class SendMessage extends BotApiMethod { return this; } + public SendMessage setParseMode(String parseMode) { + this.parseMode = parseMode; + return this; + } + public SendMessage enableMarkdown(boolean enable) { if (enable) { this.parseMode = ParseMode.MARKDOWN; @@ -129,40 +148,23 @@ public class SendMessage extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(TEXT_FIELD, text); - if (parseMode != null) { - jsonObject.put(PARSEMODE_FIELD, parseMode); - } - if (disableWebPagePreview != null) { - jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview); - } - if (disableNotification != null) { - jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } - if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); - } - - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending message", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -173,38 +175,9 @@ public class SendMessage extends BotApiMethod { if (text == null || text.isEmpty()) { throw new TelegramApiValidationException("Text parameter can't be empty", this); } - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(TEXT_FIELD, text); - - if (parseMode != null) { - gen.writeStringField(PARSEMODE_FIELD, parseMode); - } - if (disableWebPagePreview != null) { - gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview); - } - if (disableNotification != null) { - gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); + replyMarkup.validate(); } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index 688c1e59..66999b2c 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.api.methods.send; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.Objects; @@ -12,7 +20,7 @@ import java.util.Objects; * @brief Use this method to send photos. On success, the sent Message is returned. * @date 20 of June of 2015 */ -public class SendPhoto { +public class SendPhoto extends PartialBotApiMethod { public static final String PATH = "sendphoto"; public static final String CHATID_FIELD = "chat_id"; @@ -50,6 +58,12 @@ public class SendPhoto { return this; } + public SendPhoto setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getPhoto() { return photo; } @@ -118,7 +132,6 @@ public class SendPhoto { } public SendPhoto setNewPhoto(File file) { - this.photo = file.getName(); this.newPhotoFile = file; this.isNewPhoto = true; return this; @@ -133,6 +146,42 @@ public class SendPhoto { return this; } + @Override + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending photo", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + + if (isNewPhoto) { + if (newPhotoFile == null && newPhotoStream == null) { + throw new TelegramApiValidationException("Photo can't be empty", this); + } + if (newPhotoStream != null && (photoName == null || photoName.isEmpty())) { + throw new TelegramApiValidationException("Photo name can't be empty", this); + } + } else if (photo == null) { + throw new TelegramApiValidationException("Photo can't be empty", this); + } + if (replyMarkup != null) { + replyMarkup.validate(); + } + } + @Override public String toString() { return "SendPhoto{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java similarity index 66% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index f0ead297..3bb9d4e9 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.api.methods.send; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.Objects; @@ -12,7 +20,7 @@ import java.util.Objects; * @brief Use this method to send .webp stickers. On success, the sent Message is returned. * @date 20 of June of 2015 */ -public class SendSticker { +public class SendSticker extends PartialBotApiMethod { public static final String PATH = "sendsticker"; public static final String CHATID_FIELD = "chat_id"; @@ -48,6 +56,12 @@ public class SendSticker { return this; } + public SendSticker setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getSticker() { return sticker; } @@ -77,7 +91,6 @@ public class SendSticker { } public SendSticker setNewSticker(File file) { - this.sticker = file.getName(); this.isNewSticker = true; this.newStickerFile = file; return this; @@ -122,6 +135,42 @@ public class SendSticker { return newStickerStream; } + @Override + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending sticker", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + + if (isNewSticker) { + if (newStickerFile == null && newStickerStream == null) { + throw new TelegramApiValidationException("Sticker can't be empty", this); + } + if (newStickerStream != null && (stickerName == null || stickerName.isEmpty())) { + throw new TelegramApiValidationException("Sticker name can't be empty", this); + } + } else if (sticker == null) { + throw new TelegramApiValidationException("Sticker can't be empty", this); + } + if (replyMarkup != null) { + replyMarkup.validate(); + } + } + @Override public String toString() { return "SendSticker{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java index 3cd5337a..3ca54999 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java @@ -1,17 +1,17 @@ package org.telegram.telegrambots.api.methods.send; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -32,20 +32,34 @@ public class SendVenue extends BotApiMethod { private static final String FOURSQUARE_ID_FIELD = "foursquare_id"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + + @JsonProperty(CHATID_FIELD) private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @JsonProperty(LATITUDE_FIELD) private Float latitude; ///< Latitude of venue location + @JsonProperty(LONGITUDE_FIELD) private Float longitude; ///< Longitude of venue location + @JsonProperty(TITLE_FIELD) private String title; ///< Title of the venue /** * 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 */ + @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; + @JsonProperty(ADDRESS_FIELD) private String address; ///< Address of the venue + @JsonProperty(FOURSQUARE_ID_FIELD) private String foursquareId; ///< Optional. Foursquare identifier of the venue + @JsonProperty(REPLYTOMESSAGEID_FIELD) private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + public SendVenue() { + super(); + } + public String getChatId() { return chatId; } @@ -55,6 +69,12 @@ public class SendVenue extends BotApiMethod { return this; } + public SendVenue setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Float getLatitude() { return latitude; } @@ -133,16 +153,23 @@ public class SendVenue extends BotApiMethod { } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending venue", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -162,61 +189,9 @@ public class SendVenue extends BotApiMethod { if (address == null) { throw new TelegramApiValidationException("Address parameter can't be empty", this); } - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(LATITUDE_FIELD, latitude); - jsonObject.put(LONGITUDE_FIELD, longitude); - jsonObject.put(TITLE_FIELD, title); - jsonObject.put(ADDRESS_FIELD, address); - if (foursquareId != null) { - jsonObject.put(FOURSQUARE_ID_FIELD, foursquareId); - } - if (disableNotification != null) { - jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); + replyMarkup.validate(); } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeStringField(TITLE_FIELD, title); - gen.writeStringField(ADDRESS_FIELD, address); - if (foursquareId != null) { - gen.writeStringField(FOURSQUARE_ID_FIELD, foursquareId); - } - if (disableNotification != null) { - gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); - } - if (replyToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index f303f2d3..1424ef16 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.api.methods.send; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.Objects; @@ -13,7 +21,7 @@ import java.util.Objects; * may be sent as Document). On success, the sent Message is returned. * @date 20 of June of 2015 */ -public class SendVideo { +public class SendVideo extends PartialBotApiMethod { public static final String PATH = "sendvideo"; public static final String CHATID_FIELD = "chat_id"; @@ -67,6 +75,12 @@ public class SendVideo { return this; } + public SendVideo setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getDuration() { return duration; } @@ -152,7 +166,6 @@ public class SendVideo { } public SendVideo setNewVideo(File file) { - this.video = file.getName(); this.isNewVideo = true; this.newVideoFile = file; return this; @@ -167,6 +180,42 @@ public class SendVideo { return this; } + @Override + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending video", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + + if (isNewVideo) { + if (newVideoFile == null && newVideoStream == null) { + throw new TelegramApiValidationException("Video can't be empty", this); + } + if (newVideoStream != null && (videoName == null || videoName.isEmpty())) { + throw new TelegramApiValidationException("Video name can't be empty", this); + } + } else if (video == null) { + throw new TelegramApiValidationException("Video can't be empty", this); + } + if (replyMarkup != null) { + replyMarkup.validate(); + } + } + @Override public String toString() { return "SendVideo{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java similarity index 71% rename from src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index febad10d..d350594a 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.api.methods.send; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.Objects; @@ -14,7 +22,7 @@ import java.util.Objects; * (other formats may be sent as Audio or Document). * @date 16 of July of 2015 */ -public class SendVoice { +public class SendVoice extends PartialBotApiMethod { public static final String PATH = "sendvoice"; public static final String CHATID_FIELD = "chat_id"; @@ -69,6 +77,12 @@ public class SendVoice { return this; } + public SendVoice setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public String getVoice() { return voice; } @@ -80,7 +94,6 @@ public class SendVoice { } public SendVoice setNewVoice(File file) { - this.voice = file.getName(); this.isNewVoice = true; this.newVoiceFile = file; return this; @@ -147,6 +160,43 @@ public class SendVoice { return this; } + @Override + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error sending voice", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + + if (isNewVoice) { + if (newVoiceFile == null && newVoiceStream == null) { + throw new TelegramApiValidationException("Voice can't be empty", this); + } + if (newVoiceStream != null && (voiceName == null || voiceName.isEmpty())) { + throw new TelegramApiValidationException("Voice name can't be empty", this); + } + } else if (voice == null) { + throw new TelegramApiValidationException("Voice can't be empty", this); + } + + if (replyMarkup != null) { + replyMarkup.validate(); + } + } + @Override public String toString() { return "SendVoice{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updates/GetUpdates.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/GetUpdates.java similarity index 61% rename from src/main/java/org/telegram/telegrambots/api/methods/updates/GetUpdates.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/GetUpdates.java index fc4ff9b2..b7fa957d 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/updates/GetUpdates.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/GetUpdates.java @@ -1,7 +1,16 @@ package org.telegram.telegrambots.api.methods.updates; -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IToJson; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; + +import java.io.IOException; +import java.util.ArrayList; /** * @author Ruben Bermudez @@ -10,7 +19,7 @@ import org.telegram.telegrambots.api.interfaces.IToJson; * objects is returned. * @date 20 of June of 2015 */ -public class GetUpdates implements IToJson { +public class GetUpdates extends BotApiMethod>{ public static final String PATH = "getupdates"; private static final String OFFSET_FIELD = "offset"; @@ -24,16 +33,19 @@ public class GetUpdates implements IToJson { * specified to retrieve updates starting from -offset update from the end of the updates queue. * All previous updates will forgotten. */ + @JsonProperty(OFFSET_FIELD) private Integer offset; /** * Optional Limits the number of updates to be retrieved. Values between 1—100 are accepted. * Defaults to 100 */ + @JsonProperty(LIMIT_FIELD) private Integer limit; /** * Optional. Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. * Should be positive, 0 should be used for testing purposes only. */ + @JsonProperty(TIMEOUT_FIELD) private Integer timeout; public GetUpdates() { @@ -68,18 +80,28 @@ public class GetUpdates implements IToJson { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - if (offset != null) { - jsonObject.put(OFFSET_FIELD, offset); + public String getMethod() { + return PATH; + } + + @Override + public ArrayList deserializeResponse(String answer) throws + TelegramApiRequestException { + try { + ApiResponse> result = OBJECT_MAPPER.readValue(answer, + new TypeReference>>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting updates", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - if (limit != null) { - jsonObject.put(LIMIT_FIELD, limit); - } - if (timeout != null) { - jsonObject.put(TIMEOUT_FIELD, timeout); - } - return jsonObject; + } + + @Override + public void validate() throws TelegramApiValidationException { } @Override diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java new file mode 100644 index 00000000..e74e4c81 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java @@ -0,0 +1,59 @@ +package org.telegram.telegrambots.api.methods.updates; + +import com.fasterxml.jackson.core.type.TypeReference; + +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.WebhookInfo; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.4 + * @brief Use this method to get current webhook status. + * Requires no parameters. + * On success, returns a WebhookInfo object. + * Will throw an error, if the bot is using getUpdates. + * + * @date 12 of August of 2016 + */ +public class GetWebhookInfo extends BotApiMethod { + public static final String PATH = "getwebhookinfo"; + + public GetWebhookInfo() { + super(); + } + + @Override + public String toString() { + return "GetWebhookInfo{}"; + } + + @Override + public String getMethod() { + return PATH; + } + + @Override + public WebhookInfo deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>() { + }); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error getting webhook info", result); + } + } catch (IOException e2) { + throw new TelegramApiRequestException("Unable to deserialize response", e2); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updates/SetWebhook.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/SetWebhook.java similarity index 99% rename from src/main/java/org/telegram/telegrambots/api/methods/updates/SetWebhook.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/SetWebhook.java index b61bfc71..31ae5555 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/updates/SetWebhook.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updates/SetWebhook.java @@ -14,6 +14,7 @@ public class SetWebhook { public static final String URL_FIELD = "url"; public static final String CERTIFICATE_FIELD = "certificate"; + private String url; ///< Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration private String certificateFile; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageCaption.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageCaption.java similarity index 66% rename from src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageCaption.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageCaption.java index 2a377f70..f3d76aaf 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageCaption.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageCaption.java @@ -1,15 +1,13 @@ package org.telegram.telegrambots.api.methods.updatingmessages; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONException; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; @@ -34,16 +32,21 @@ public class EditMessageCaption extends BotApiMethod { * Required if inline_message_id is not specified. Unique identifier for the chat to send the * message to (Or username for channels) */ + @JsonProperty(CHATID_FIELD) private String chatId; /** * Required if inline_message_id is not specified. Unique identifier of the sent message */ + @JsonProperty(MESSAGEID_FIELD) private Integer messageId; /** * Required if chat_id and message_id are not specified. Identifier of the inline message */ + @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; + @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. New caption of the message + @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. public EditMessageCaption() { @@ -96,38 +99,23 @@ public class EditMessageCaption extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - if (inlineMessageId == null) { - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(MESSAGEID_FIELD, messageId); - } else { - jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); - } - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - try { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); - } catch (JSONException e) { - return new Message(); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error editing message caption", result); } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -147,31 +135,9 @@ public class EditMessageCaption extends BotApiMethod { throw new TelegramApiValidationException("MessageId parameter must be empty if inlineMessageId is provided", this); } } - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - if (inlineMessageId == null) { - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - } else { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); + replyMarkup.validate(); } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageReplyMarkup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageReplyMarkup.java similarity index 67% rename from src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageReplyMarkup.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageReplyMarkup.java index da755f2f..0d8c8bef 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageReplyMarkup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageReplyMarkup.java @@ -1,18 +1,17 @@ package org.telegram.telegrambots.api.methods.updatingmessages; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONException; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -33,15 +32,19 @@ public class EditMessageReplyMarkup extends BotApiMethod { * Required if inline_message_id is not specified. Unique identifier for the chat to send the * message to (Or username for channels) */ + @JsonProperty(CHATID_FIELD) private String chatId; /** * Required if inline_message_id is not specified. Unique identifier of the sent message */ + @JsonProperty(MESSAGEID_FIELD) private Integer messageId; /** * Required if chat_id and message_id are not specified. Identifier of the inline message */ + @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; + @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. public EditMessageReplyMarkup() { @@ -57,6 +60,12 @@ public class EditMessageReplyMarkup extends BotApiMethod { return this; } + public EditMessageReplyMarkup setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getMessageId() { return messageId; } @@ -85,35 +94,23 @@ public class EditMessageReplyMarkup extends BotApiMethod { } @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - if (inlineMessageId == null) { - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(MESSAGEID_FIELD, messageId); - } else { - jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); - } - return jsonObject; - } - - @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - try { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); - } catch (JSONException e) { - return new Message(); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error editing message reply markup", result); } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -133,28 +130,9 @@ public class EditMessageReplyMarkup extends BotApiMethod { throw new TelegramApiValidationException("MessageId parameter must be empty if inlineMessageId is provided", this); } } - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - if (inlineMessageId == null) { - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - } else { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); + replyMarkup.validate(); } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageText.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageText.java similarity index 69% rename from src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageText.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageText.java index 6663accd..debf64fb 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageText.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/methods/updatingmessages/EditMessageText.java @@ -1,19 +1,18 @@ package org.telegram.telegrambots.api.methods.updatingmessages; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; -import org.json.JSONException; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.methods.ParseMode; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.util.Objects; /** * @author Ruben Bermudez @@ -37,25 +36,32 @@ public class EditMessageText extends BotApiMethod { * Required if inline_message_id is not specified. Unique identifier for the chat to send the * message to (Or username for channels) */ + @JsonProperty(CHATID_FIELD) private String chatId; /** * Required if inline_message_id is not specified. Unique identifier of the sent message */ + @JsonProperty(MESSAGEID_FIELD) private Integer messageId; /** * Required if chat_id and message_id are not specified. Identifier of the inline message */ + @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; /** * New text of the message */ + @JsonProperty(TEXT_FIELD) private String text; /** * Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width * text or inline URLs in your bot's message. */ + @JsonProperty(PARSE_MODE_FIELD) private String parseMode; + @JsonProperty(DISABLE_WEB_PREVIEW_FIELD) private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message + @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. public EditMessageText() { @@ -71,6 +77,12 @@ public class EditMessageText extends BotApiMethod { return this; } + public EditMessageText setChatId(Long chatId) { + Objects.requireNonNull(chatId); + this.chatId = chatId.toString(); + return this; + } + public Integer getMessageId() { return messageId; } @@ -135,43 +147,30 @@ public class EditMessageText extends BotApiMethod { return this; } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - if (inlineMessageId == null) { - jsonObject.put(CHATID_FIELD, chatId); - jsonObject.put(MESSAGEID_FIELD, messageId); - } else { - jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - jsonObject.put(TEXT_FIELD, text); - if (parseMode != null) { - jsonObject.put(PARSE_MODE_FIELD, parseMode); - } - if (disableWebPagePreview != null) { - jsonObject.put(DISABLE_WEB_PREVIEW_FIELD, disableWebPagePreview); - } - if (replyMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); - } - return jsonObject; + + public EditMessageText setParseMode(String parseMode) { + this.parseMode = parseMode; + return this; } @Override - public String getPath() { + public String getMethod() { return PATH; } @Override - public Message deserializeResponse(JSONObject answer) { - if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { - try { - return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); - } catch (JSONException e) { - return new Message(); + public Message deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error editing message text", result); } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); } - return null; } @Override @@ -194,35 +193,9 @@ public class EditMessageText extends BotApiMethod { if (text == null || text.isEmpty()) { throw new TelegramApiValidationException("Text parameter can't be empty", this); } - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(METHOD_FIELD, PATH); - if (inlineMessageId == null) { - gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - } else { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - gen.writeStringField(TEXT_FIELD, text); - if (parseMode != null) { - gen.writeStringField(PARSE_MODE_FIELD, parseMode); - } - if (disableWebPagePreview != null) { - gen.writeBooleanField(DISABLE_WEB_PREVIEW_FIELD, disableWebPagePreview); - } if (replyMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); + replyMarkup.validate(); } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Audio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Audio.java similarity index 52% rename from src/main/java/org/telegram/telegrambots/api/objects/Audio.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Audio.java index ce3e2653..31c9bc5e 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Audio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Audio.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,7 +10,7 @@ import java.io.IOException; * @brief This object represents an audio file * @date 16 of July of 2015 */ -public class Audio implements IBotApiObject { +public class Audio implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String DURATION_FIELD = "duration"; @@ -24,6 +18,7 @@ public class Audio implements IBotApiObject { private static final String FILESIZE_FIELD = "file_size"; private static final String TITLE_FIELD = "title"; private static final String PERFORMER_FIELD = "performer"; + @JsonProperty(FILEID_FIELD) private String fileId; ///< Unique identifier for this file @JsonProperty(DURATION_FIELD) @@ -41,24 +36,6 @@ public class Audio implements IBotApiObject { super(); } - public Audio(JSONObject jsonObject) { - super(); - this.fileId = jsonObject.getString(FILEID_FIELD); - this.duration = jsonObject.getInt(DURATION_FIELD); - if (jsonObject.has(MIMETYPE_FIELD)) { - this.mimeType = jsonObject.getString(MIMETYPE_FIELD); - } - if (jsonObject.has(FILEID_FIELD)) { - this.fileSize = jsonObject.getInt(FILESIZE_FIELD); - } - if (jsonObject.has(TITLE_FIELD)) { - this.title = jsonObject.getString(TITLE_FIELD); - } - if (jsonObject.has(PERFORMER_FIELD)) { - this.performer = jsonObject.getString(PERFORMER_FIELD); - } - } - public String getFileId() { return fileId; } @@ -83,32 +60,6 @@ public class Audio implements IBotApiObject { return performer; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(DURATION_FIELD, duration); - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, title); - } - if (performer != null) { - gen.writeStringField(PERFORMER_FIELD, performer); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Audio{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java similarity index 63% rename from src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java index 3857fc6f..7125421f 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -25,7 +19,7 @@ import java.io.IOException; * (e.g., without specifying any of the optional parameters). * @date 10 of April of 2016 */ -public class CallbackQuery implements IBotApiObject { +public class CallbackQuery implements BotApiObject { private static final String ID_FIELD = "id"; private static final String FROM_FIELD = "from"; @@ -39,58 +33,39 @@ public class CallbackQuery implements IBotApiObject { private String id; ///< Unique identifier for this query @JsonProperty(FROM_FIELD) private User from; ///< Sender - @JsonProperty(MESSAGE_FIELD) /** * Optional. * Message with the callback button that originated the query. * * @note The message content and message date will not be available if the message is too old */ + @JsonProperty(MESSAGE_FIELD) private Message message; @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; ///< Optional. Identifier of the message sent via the bot in inline mode, that originated the query - @JsonProperty(DATA_FIELD) /** * * Optional. Data associated with the callback button. * @note Be aware that a bad client can send arbitrary data in this field */ + @JsonProperty(DATA_FIELD) private String data; - @JsonProperty(GAMESHORTNAME_FIELD) /** * Optional. Short name of a Game to be returned, serves as the unique identifier for the game */ + @JsonProperty(GAMESHORTNAME_FIELD) private String gameShortName; - @JsonProperty(CHAT_INSTANCE_FIELD) /** * Identifier, uniquely corresponding to the chat to which the message with the * callback button was sent. Useful for high scores in games. */ + @JsonProperty(CHAT_INSTANCE_FIELD) private String chatInstance; public CallbackQuery() { super(); } - public CallbackQuery(JSONObject jsonObject) { - super(); - this.id = jsonObject.getString(ID_FIELD); - this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); - chatInstance = jsonObject.getString(CHAT_INSTANCE_FIELD); - if (jsonObject.has(MESSAGE_FIELD)) { - this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD)); - } - if (jsonObject.has(INLINE_MESSAGE_ID_FIELD)) { - this.inlineMessageId = jsonObject.getString(INLINE_MESSAGE_ID_FIELD); - } - if (jsonObject.has(DATA_FIELD)) { - data = jsonObject.getString(DATA_FIELD); - } - if (jsonObject.has(GAMESHORTNAME_FIELD)) { - gameShortName = jsonObject.getString(GAMESHORTNAME_FIELD); - } - } - public String getId() { return this.id; } @@ -119,33 +94,6 @@ public class CallbackQuery implements IBotApiObject { return chatInstance; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(ID_FIELD, id); - gen.writeObjectField(FROM_FIELD, from); - gen.writeStringField(CHAT_INSTANCE_FIELD, chatInstance); - if (message != null) { - gen.writeObjectField(MESSAGE_FIELD, message); - } - if (inlineMessageId != null) { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - if (data != null) { - gen.writeStringField(DATA_FIELD, data); - } - if (gameShortName != null) { - gen.writeStringField(GAMESHORTNAME_FIELD, gameShortName); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "CallbackQuery{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Chat.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Chat.java similarity index 60% rename from src/main/java/org/telegram/telegrambots/api/objects/Chat.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Chat.java index 1dc523ea..df34e665 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Chat.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Chat.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,7 +10,8 @@ import java.io.IOException; * @brief This object represents a Telegram chat with an user or a group * @date 24 of June of 2015 */ -public class Chat implements IBotApiObject { +public class Chat implements BotApiObject { + private static final String ID_FIELD = "id"; private static final String TYPE_FIELD = "type"; private static final String TITLE_FIELD = "title"; @@ -28,13 +23,14 @@ public class Chat implements IBotApiObject { private static final String GROUPCHATTYPE = "group"; 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. */ + @JsonProperty(ID_FIELD) 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” @@ -46,37 +42,16 @@ public class Chat implements IBotApiObject { private String lastName; ///< Optional. Interlocutor's first name for private chats @JsonProperty(USERNAME_FIELD) private String userName; ///< Optional. Interlocutor's last name for private chats - @JsonProperty(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD) /** * Optional. True if the group or supergroup has ‘All Members Are Admins’ enabled. */ + @JsonProperty(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD) private Boolean allMembersAreAdministrators; public Chat() { super(); } - public Chat(JSONObject jsonObject) { - super(); - this.id = jsonObject.getLong(ID_FIELD); - this.type = jsonObject.getString(TYPE_FIELD); - if (jsonObject.has(TITLE_FIELD)) { - this.title = jsonObject.getString(TITLE_FIELD); - } - if (jsonObject.has(FIRSTNAME_FIELD)) { - this.firstName = jsonObject.getString(FIRSTNAME_FIELD); - } - if (jsonObject.has(LASTNAME_FIELD)) { - this.lastName = jsonObject.getString(LASTNAME_FIELD); - } - if (jsonObject.has(USERNAME_FIELD)) { - this.userName = jsonObject.getString(USERNAME_FIELD); - } - if (jsonObject.has(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD)) { - allMembersAreAdministrators = jsonObject.getBoolean(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD); - } - } - public Long getId() { return id; } @@ -117,38 +92,6 @@ public class Chat implements IBotApiObject { return allMembersAreAdministrators; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(ID_FIELD, id); - gen.writeStringField(TYPE_FIELD, type); - if (isUserChat()) { - if (firstName != null) { - gen.writeStringField(FIRSTNAME_FIELD, firstName); - } - if (lastName != null) { - gen.writeStringField(LASTNAME_FIELD, lastName); - } - } else { - if (title != null) { - gen.writeStringField(TITLE_FIELD, title); - } - } - if (!isGroupChat() && userName != null) { - gen.writeStringField(USERNAME_FIELD, userName); - } - if (allMembersAreAdministrators != null) { - gen.writeBooleanField(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD, allMembersAreAdministrators); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Chat{" + diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/ChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/ChatMember.java new file mode 100644 index 00000000..cde37ea2 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/ChatMember.java @@ -0,0 +1,41 @@ +package org.telegram.telegrambots.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.telegram.telegrambots.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief This object contains information about one member of the chat. + * @date 20 of May of 2016 + */ +public class ChatMember implements BotApiObject { + private static final String USER_FIELD = "user"; + private static final String STATUS_FIELD = "status"; + + @JsonProperty(USER_FIELD) + private User user; ///< Information about the user + @JsonProperty(STATUS_FIELD) + private String status; ///< The member's status in the chat. Can be “creator”, “administrator”, “member”, “left” or “kicked” + + public ChatMember() { + super(); + } + + public User getUser() { + return user; + } + + public String getStatus() { + return status; + } + + @Override + public String toString() { + return "ChatMember{" + + "user=" + user + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Contact.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Contact.java similarity index 50% rename from src/main/java/org/telegram/telegrambots/api/objects/Contact.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Contact.java index 2a6e4897..a50d748d 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Contact.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Contact.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,12 +10,13 @@ import java.io.IOException; * @brief This object represents a phone contact. * @date 20 of June of 2015 */ -public class Contact implements IBotApiObject { +public class Contact implements BotApiObject { private static final String PHONENUMBER_FIELD = "phone_number"; private static final String FIRSTNAME_FIELD = "first_name"; private static final String LASTNAME_FIELD = "last_name"; private static final String USERID_FIELD = "user_id"; + @JsonProperty(PHONENUMBER_FIELD) private String phoneNumber; ///< Contact's phone number @JsonProperty(FIRSTNAME_FIELD) @@ -35,18 +30,6 @@ public class Contact implements IBotApiObject { super(); } - public Contact(JSONObject jsonObject) { - super(); - this.phoneNumber = jsonObject.getString(PHONENUMBER_FIELD); - this.firstName = jsonObject.getString(FIRSTNAME_FIELD); - if (jsonObject.has(LASTNAME_FIELD)) { - this.lastName = jsonObject.getString(LASTNAME_FIELD); - } - if (jsonObject.has(USERID_FIELD)) { - this.userID = jsonObject.getInt(USERID_FIELD); - } - } - public String getPhoneNumber() { return phoneNumber; } @@ -63,26 +46,6 @@ public class Contact implements IBotApiObject { return userID; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(PHONENUMBER_FIELD, phoneNumber); - gen.writeStringField(FIRSTNAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LASTNAME_FIELD, lastName); - } - if (userID != null) { - gen.writeNumberField(USERID_FIELD, userID); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Contact{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Document.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Document.java similarity index 51% rename from src/main/java/org/telegram/telegrambots/api/objects/Document.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Document.java index 313ed105..501a84be 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Document.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Document.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -17,13 +11,14 @@ import java.io.IOException; * Telegram users can send files of any type of up to 1.5 GB in size. * @date 20 of June of 2015 */ -public class Document implements IBotApiObject { +public class Document implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String THUMB_FIELD = "thumb"; private static final String FILENAME_FIELD = "file_name"; private static final String MIMETYPE_FIELD = "mime_type"; private static final String FILESIZE_FIELD = "file_size"; + @JsonProperty(FILEID_FIELD) private String fileId; ///< Unique identifier for this file @JsonProperty(THUMB_FIELD) @@ -39,22 +34,6 @@ public class Document implements IBotApiObject { super(); } - public Document(JSONObject jsonObject) { - this.fileId = jsonObject.getString(FILEID_FIELD); - if (jsonObject.has(THUMB_FIELD)) { - this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD)); - } - if (jsonObject.has(FILENAME_FIELD)) { - this.fileName = jsonObject.getString(FILENAME_FIELD); - } - if (jsonObject.has(MIMETYPE_FIELD)) { - this.mimeType = jsonObject.getString(MIMETYPE_FIELD); - } - if (jsonObject.has(FILESIZE_FIELD)) { - this.fileSize = jsonObject.getInt(FILESIZE_FIELD); - } - } - public String getFileId() { return fileId; } @@ -75,29 +54,6 @@ public class Document implements IBotApiObject { return fileSize; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeObjectField(THUMB_FIELD, thumb); - if (fileName != null) { - gen.writeStringField(FILENAME_FIELD, fileName); - } - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Document{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/EntityType.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/EntityType.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/api/objects/EntityType.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/EntityType.java diff --git a/src/main/java/org/telegram/telegrambots/api/objects/File.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/File.java similarity index 51% rename from src/main/java/org/telegram/telegrambots/api/objects/File.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/File.java index fb93da7f..b5f76228 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/File.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/File.java @@ -1,14 +1,12 @@ package org.telegram.telegrambots.api.objects; +import com.fasterxml.jackson.annotation.JsonIgnore; 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 org.telegram.telegrambots.api.interfaces.BotApiObject; -import java.io.IOException; +import java.security.InvalidParameterException; +import java.text.MessageFormat; /** * @author Ruben Bermudez @@ -16,12 +14,19 @@ import java.io.IOException; * @brief This object represents a file ready to be downloaded * @date 24 of June of 2015 */ -public class File implements IBotApiObject { +public class File implements BotApiObject { + @JsonIgnore + /** + * @deprecated It is still public for backward compatibility, will be removed in next big release. + * use {@link #getFileUrl(String, String)} or {@link #getFileUrl(String)} instead. + */ + @Deprecated public static final String FILEBASEURL = "https://api.telegram.org/file/bot{0}/{1}"; private static final String FILE_ID = "file_id"; private static final String FILE_SIZE_FIELD = "file_size"; private static final String FILE_PATH_FIELD = "file_path"; + @JsonProperty(FILE_ID) private String fileId; ///< Unique identifier for this file @JsonProperty(FILE_SIZE_FIELD) @@ -33,17 +38,6 @@ public class File implements IBotApiObject { super(); } - public File(JSONObject jsonObject) { - super(); - this.fileId = jsonObject.getString(FILE_ID); - if (jsonObject.has(FILE_SIZE_FIELD)) { - this.fileSize = jsonObject.getInt(FILE_SIZE_FIELD); - } - if (jsonObject.has(FILE_PATH_FIELD)) { - this.filePath = jsonObject.getString(FILE_PATH_FIELD); - } - } - public String getFileId() { return fileId; } @@ -56,25 +50,6 @@ public class File implements IBotApiObject { return filePath; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILE_ID, fileId); - if (fileSize != null) { - gen.writeNumberField(FILE_SIZE_FIELD, fileSize); - } - if (filePath != null) { - gen.writeStringField(FILE_PATH_FIELD, filePath); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "File{" + @@ -83,4 +58,15 @@ public class File implements IBotApiObject { ", filePath='" + filePath + '\'' + '}'; } + + public String getFileUrl(String botToken) { + return getFileUrl(botToken, filePath); + } + + public static String getFileUrl(String botToken, String filePath) { + if (botToken == null || botToken.isEmpty()) { + throw new InvalidParameterException("Bot token can't be empty"); + } + return MessageFormat.format("https://api.telegram.org/file/bot{0}/{1}", botToken, filePath); + } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Location.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Location.java new file mode 100644 index 00000000..026faf24 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Location.java @@ -0,0 +1,42 @@ +package org.telegram.telegrambots.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.telegram.telegrambots.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief This object represents a point on the map. + * @date 20 of June of 2015 + */ +public class Location implements BotApiObject { + + private static final String LONGITUDE_FIELD = "longitude"; + private static final String LATITUDE_FIELD = "latitude"; + + @JsonProperty(LONGITUDE_FIELD) + private Double longitude; ///< Longitude as defined by sender + @JsonProperty(LATITUDE_FIELD) + private Double latitude; ///< Latitude as defined by sender + + public Location() { + super(); + } + + public Double getLongitude() { + return longitude; + } + + public Double getLatitude() { + return latitude; + } + + @Override + public String toString() { + return "Location{" + + "longitude=" + longitude + + ", latitude=" + latitude + + '}'; + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/MemberStatus.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/MemberStatus.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/api/objects/MemberStatus.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/MemberStatus.java diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Message.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Message.java similarity index 59% rename from src/main/java/org/telegram/telegrambots/api/objects/Message.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Message.java index d6866c01..c8c028c3 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Message.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Message.java @@ -1,17 +1,10 @@ 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.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; +import org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.games.Game; -import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,7 +13,7 @@ import java.util.List; * @brief This object represents a message. * @date 20 of June of 2015 */ -public class Message implements IBotApiObject { +public class Message implements BotApiObject { private static final String MESSAGEID_FIELD = "message_id"; private static final String FROM_FIELD = "from"; private static final String DATE_FIELD = "date"; @@ -71,11 +64,11 @@ public class Message implements IBotApiObject { private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent @JsonProperty(TEXT_FIELD) private String text; ///< Optional. For text messages, the actual UTF-8 text of the message - @JsonProperty(ENTITIES_FIELD) /** * Optional. For text messages, special entities like usernames, URLs, * bot commands, etc. that appear in the text */ + @JsonProperty(ENTITIES_FIELD) private List entities; @JsonProperty(AUDIO_FIELD) private Audio audio; ///< Optional. Message is an audio file, information about the file @@ -113,7 +106,6 @@ public class Message implements IBotApiObject { private Voice voice; ///< Optional. Message is a voice message, information about the file @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters - @JsonProperty(SUPERGROUPCREATED_FIELD) /** * Optional. Service message: the supergroup has been created. * This field can‘t be received in a message coming through updates, @@ -121,8 +113,8 @@ public class Message implements IBotApiObject { * It can only be found in reply_to_message * if someone replies to a very first message in a directly created supergroup. */ + @JsonProperty(SUPERGROUPCREATED_FIELD) private Boolean superGroupCreated; - @JsonProperty(CHANNELCHATCREATED_FIELD) /** * Optional. Service message: the channel has been created. * This field can‘t be received in a message coming through updates, @@ -130,8 +122,8 @@ public class Message implements IBotApiObject { * It can only be found in reply_to_message if someone * replies to a very first message in a channel. */ + @JsonProperty(CHANNELCHATCREATED_FIELD) 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 @@ -139,8 +131,8 @@ public class Message implements IBotApiObject { * But it smaller than 52 bits, so a signed 64 bit integer or double-precision * float type are safe for storing this identifier. */ + @JsonProperty(MIGRATETOCHAT_FIELD) 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 @@ -148,6 +140,7 @@ public class Message implements IBotApiObject { * But it smaller than 52 bits, so a signed 64 bit integer or double-precision * float type are safe for storing this identifier. */ + @JsonProperty(MIGRATEFROMCHAT_FIELD) 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 @@ -158,120 +151,6 @@ public class Message implements IBotApiObject { super(); } - public Message(JSONObject jsonObject) { - super(); - this.messageId = jsonObject.getInt(MESSAGEID_FIELD); - if (jsonObject.has(FROM_FIELD)) { - this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); - } - if (jsonObject.has(DATE_FIELD)) { - this.date = jsonObject.getInt(DATE_FIELD); - } - this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD)); - if (jsonObject.has(FORWARDFROMCHAT_FIELD)) { - this.forwardFromChat = new Chat(jsonObject.getJSONObject(FORWARDFROMCHAT_FIELD)); - } - if (jsonObject.has(FORWARDFROM_FIELD)) { - this.forwardFrom = new User(jsonObject.getJSONObject(FORWARDFROM_FIELD)); - } - if (jsonObject.has(FORWARDDATE_FIELD)) { - this.forwardDate = jsonObject.getInt(FORWARDDATE_FIELD); - } - if (jsonObject.has(TEXT_FIELD)) { - this.text = jsonObject.getString(TEXT_FIELD); - } - if (jsonObject.has(ENTITIES_FIELD)) { - this.entities = new ArrayList<>(); - JSONArray entities = jsonObject.getJSONArray(ENTITIES_FIELD); - for (int i = 0; i < entities.length(); i++) { - this.entities.add(new MessageEntity(entities.getJSONObject(i))); - } - } - if (jsonObject.has(AUDIO_FIELD)) { - this.audio = new Audio(jsonObject.getJSONObject(AUDIO_FIELD)); - } - if (jsonObject.has(DOCUMENT_FIELD)) { - this.document = new Document(jsonObject.getJSONObject(DOCUMENT_FIELD)); - } - if (jsonObject.has(PHOTO_FIELD)) { - this.photo = new ArrayList<>(); - JSONArray photos = jsonObject.getJSONArray(PHOTO_FIELD); - for (int i = 0; i < photos.length(); i++) { - this.photo.add(new PhotoSize(photos.getJSONObject(i))); - } - } - if (jsonObject.has(STICKER_FIELD)) { - this.sticker = new Sticker(jsonObject.getJSONObject(STICKER_FIELD)); - } - if (jsonObject.has(VIDEO_FIELD)) { - this.video = new Video(jsonObject.getJSONObject(VIDEO_FIELD)); - } - if (jsonObject.has(CONTACT_FIELD)) { - this.contact = new Contact(jsonObject.getJSONObject(CONTACT_FIELD)); - } - if (jsonObject.has(LOCATION_FIELD)) { - this.location = new Location(jsonObject.getJSONObject(LOCATION_FIELD)); - } - if (jsonObject.has(VENUE_FIELD)) { - venue = new Venue(jsonObject.getJSONObject(VENUE_FIELD)); - } - if (jsonObject.has(PINNED_MESSAGE_FIELD)) { - pinnedMessage = new Message(jsonObject.getJSONObject(PINNED_MESSAGE_FIELD)); - } - if (jsonObject.has(VOICE_FIELD)) { - this.voice = new Voice(jsonObject.getJSONObject(VOICE_FIELD)); - } - if (jsonObject.has(CAPTION_FIELD)) { - this.caption = jsonObject.getString(CAPTION_FIELD); - } - if (jsonObject.has(NEWCHATMEMBER_FIELD)) { - this.newChatMember = new User(jsonObject.getJSONObject(NEWCHATMEMBER_FIELD)); - } - if (jsonObject.has(LEFTCHATMEMBER_FIELD)) { - this.leftChatMember = new User(jsonObject.getJSONObject(LEFTCHATMEMBER_FIELD)); - } - if (jsonObject.has(REPLYTOMESSAGE_FIELD)) { - this.replyToMessage = new Message(jsonObject.getJSONObject(REPLYTOMESSAGE_FIELD)); - } - if (jsonObject.has(NEWCHATTITLE_FIELD)) { - this.newChatTitle = jsonObject.getString(NEWCHATTITLE_FIELD); - } - if (jsonObject.has(NEWCHATPHOTO_FIELD)) { - JSONArray photoArray = jsonObject.getJSONArray(NEWCHATPHOTO_FIELD); - this.newChatPhoto = new ArrayList<>(); - for (int i = 0; i < photoArray.length(); i++) { - this.newChatPhoto.add(new PhotoSize(photoArray.getJSONObject(i))); - } - } - if (jsonObject.has(DELETECHATPHOTO_FIELD)) { - this.deleteChatPhoto = true; - } - if (jsonObject.has(GROUPCHATCREATED_FIELD)) { - this.groupchatCreated = true; - } - if (jsonObject.has(SUPERGROUPCREATED_FIELD)) { - this.superGroupCreated = true; - } - if (jsonObject.has(CHANNELCHATCREATED_FIELD)) { - this.channelChatCreated = true; - } - if (jsonObject.has(MIGRATETOCHAT_FIELD)) { - this.migrateToChatId = jsonObject.getLong(MIGRATETOCHAT_FIELD); - } - if (jsonObject.has(MIGRATEFROMCHAT_FIELD)) { - this.migrateFromChatId = jsonObject.getLong(MIGRATEFROMCHAT_FIELD); - } - if (jsonObject.has(EDITDATE_FIELD)) { - editDate = jsonObject.getInt(EDITDATE_FIELD); - } - if (jsonObject.has(GAME_FIELD)) { - game = new Game(jsonObject.getJSONObject(GAME_FIELD)); - } - if (hasText() && entities != null) { - entities.forEach(x -> x.computeText(text)); - } - } - public Integer getMessageId() { return messageId; } @@ -301,6 +180,7 @@ public class Message implements IBotApiObject { } public List getEntities() { + entities.forEach(x -> x.computeText(text)); return entities; } @@ -460,120 +340,8 @@ public class Message implements IBotApiObject { return entities != null && !entities.isEmpty(); } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(MESSAGEID_FIELD, messageId); - if (from != null) { - gen.writeObjectField(FROM_FIELD, from); - } - if (date != null) { - gen.writeNumberField(DATE_FIELD, date); - } - gen.writeObjectField(CHAT_FIELD, chat); - if (forwardFromChat != null) { - gen.writeObjectField(FORWARDFROMCHAT_FIELD, forwardFromChat); - } - if (forwardFrom != null) { - gen.writeObjectField(FORWARDFROM_FIELD, forwardFrom); - } - if (forwardDate != null) { - gen.writeNumberField(FORWARDDATE_FIELD, forwardDate); - } - if (text != null) { - gen.writeStringField(TEXT_FIELD, text); - } - if (audio != null) { - gen.writeObjectField(AUDIO_FIELD, audio); - } - if (document != null) { - gen.writeObjectField(DOCUMENT_FIELD, document); - } - if (photo != null && photo.size() > 0) { - gen.writeArrayFieldStart(PHOTO_FIELD); - for (PhotoSize photoSize : photo) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - } - if (sticker != null) { - gen.writeObjectField(STICKER_FIELD, sticker); - } - if (video != null) { - gen.writeObjectField(VIDEO_FIELD, video); - } - if (contact != null) { - gen.writeObjectField(CONTACT_FIELD, contact); - } - if (location != null) { - gen.writeObjectField(LOCATION_FIELD, location); - } - if (venue != null) { - gen.writeObjectField(VENUE_FIELD, venue); - } - if (voice != null) { - gen.writeObjectField(VOICE_FIELD, voice); - } - if (caption != null) { - gen.writeObjectField(CAPTION_FIELD, caption); - } - if (newChatMember != null) { - gen.writeObjectField(NEWCHATMEMBER_FIELD, newChatMember); - } - if (leftChatMember != null) { - gen.writeObjectField(LEFTCHATMEMBER_FIELD, leftChatMember); - } - if (replyToMessage != null) { - gen.writeObjectField(REPLYTOMESSAGE_FIELD, replyToMessage); - } - if (newChatTitle != null) { - gen.writeStringField(NEWCHATTITLE_FIELD, newChatTitle); - } - if (newChatPhoto != null && newChatPhoto.size() > 0) { - gen.writeArrayFieldStart(NEWCHATPHOTO_FIELD); - for (PhotoSize photoSize: newChatPhoto) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - } - if (deleteChatPhoto != null) { - gen.writeBooleanField(DELETECHATPHOTO_FIELD, deleteChatPhoto); - } - if (groupchatCreated != null) { - gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated); - } - if (superGroupCreated != null) { - gen.writeBooleanField(SUPERGROUPCREATED_FIELD, superGroupCreated); - } - if (channelChatCreated != null) { - gen.writeBooleanField(CHANNELCHATCREATED_FIELD, channelChatCreated); - } - if (migrateToChatId != null) { - gen.writeNumberField(MIGRATETOCHAT_FIELD, migrateToChatId); - } - if (migrateFromChatId != null) { - gen.writeNumberField(MIGRATEFROMCHAT_FIELD, migrateFromChatId); - } - if (editDate != null) { - gen.writeNumberField(EDITDATE_FIELD, editDate); - } - if (game != null) { - gen.writeObjectField(GAME_FIELD, game); - } - if (entities != null) { - gen.writeArrayFieldStart(ENTITIES_FIELD); - for (MessageEntity entity : entities) { - gen.writeObject(entity); - } - gen.writeEndArray(); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); + public boolean hasPhoto() { + return photo != null && !photo.isEmpty(); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java similarity index 58% rename from src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java index 52ae50f5..72afee1f 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java @@ -1,14 +1,9 @@ package org.telegram.telegrambots.api.objects; +import com.fasterxml.jackson.annotation.JsonIgnore; 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -17,14 +12,13 @@ import java.io.IOException; * usernames, URL. * @date 20 of June of 2015 */ -public class MessageEntity implements IBotApiObject { +public class MessageEntity implements BotApiObject { private static final String TYPE_FIELD = "type"; private static final String OFFSET_FIELD = "offset"; private static final String LENGTH_FIELD = "length"; private static final String URL_FIELD = "url"; private static final String USER_FIELD = "user"; - @JsonProperty(TYPE_FIELD) /** * Type of the entity. One of * mention (@username), @@ -39,6 +33,8 @@ public class MessageEntity implements IBotApiObject { * text_link (for clickable text URLs) * text_mention (for users without usernames) */ + + @JsonProperty(TYPE_FIELD) private String type; @JsonProperty(OFFSET_FIELD) private Integer offset; ///< Offset in UTF-16 code units to the start of the entity @@ -48,26 +44,13 @@ public class MessageEntity implements IBotApiObject { private String url; ///< Optional. For “text_link” only, url that will be opened after user taps on the text @JsonProperty(USER_FIELD) private User user; ///< Optional. For “text_mention” only, the mentioned user - + @JsonIgnore private String text; ///< Text present in the entity. Computed from offset and length public MessageEntity() { super(); } - public MessageEntity(JSONObject jsonObject) { - super(); - this.type = jsonObject.getString(TYPE_FIELD); - this.offset = jsonObject.getInt(OFFSET_FIELD); - this.length = jsonObject.getInt(LENGTH_FIELD); - if (EntityType.TEXTLINK.equals(type)) { - this.url = jsonObject.getString(URL_FIELD); - } - if (EntityType.TEXTMENTION.equals(type)) { - this.user = new User(jsonObject.getJSONObject(USER_FIELD)); - } - } - public String getType() { return type; } @@ -93,28 +76,9 @@ public class MessageEntity implements IBotApiObject { } protected void computeText(String message) { - text = message.substring(offset, offset + length); - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeNumberField(OFFSET_FIELD, offset); - gen.writeNumberField(LENGTH_FIELD, length); - if (url != null && EntityType.TEXTLINK.equals(type)) { - gen.writeStringField(URL_FIELD, url); + if (message != null) { + text = message.substring(offset, offset + length); } - if (user != null && EntityType.TEXTMENTION.equals(type)) { - gen.writeObjectField(USER_FIELD, user); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/objects/PhotoSize.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/PhotoSize.java similarity index 52% rename from src/main/java/org/telegram/telegrambots/api/objects/PhotoSize.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/PhotoSize.java index 69d1a912..96f3254c 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/PhotoSize.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/PhotoSize.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,13 +10,14 @@ import java.io.IOException; * @brief This object represents one size of a photo or a file / sticker thumbnail. * @date 20 of June of 2015 */ -public class PhotoSize implements IBotApiObject { +public class PhotoSize implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String WIDTH_FIELD = "width"; private static final String HEIGHT_FIELD = "height"; private static final String FILESIZE_FIELD = "file_size"; private static final String FILEPATH_FIELD = "file_path"; + @JsonProperty(FILEID_FIELD) private String fileId; ///< Unique identifier for this file @JsonProperty(WIDTH_FIELD) @@ -38,19 +33,6 @@ public class PhotoSize implements IBotApiObject { super(); } - public PhotoSize(JSONObject jsonObject) { - super(); - this.fileId = jsonObject.getString(FILEID_FIELD); - this.width = jsonObject.getInt(WIDTH_FIELD); - this.height = jsonObject.getInt(HEIGHT_FIELD); - if (jsonObject.has(FILESIZE_FIELD)) { - this.fileSize = jsonObject.getInt(FILESIZE_FIELD); - } - if (jsonObject.has(FILEPATH_FIELD)) { - this.filePath = jsonObject.getString(FILEPATH_FIELD); - } - } - public String getFileId() { return fileId; } @@ -71,25 +53,8 @@ public class PhotoSize implements IBotApiObject { return filePath; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(WIDTH_FIELD, width); - gen.writeNumberField(HEIGHT_FIELD, height); - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - if (filePath != null) { - gen.writeStringField(FILEPATH_FIELD, filePath); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); + public boolean hasFilePath() { + return filePath != null && !filePath.isEmpty(); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/objects/ResponseParameters.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/ResponseParameters.java similarity index 59% rename from src/main/java/org/telegram/telegrambots/api/objects/ResponseParameters.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/ResponseParameters.java index 205b5718..fb6915a5 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/ResponseParameters.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/ResponseParameters.java @@ -18,14 +18,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -33,34 +27,27 @@ import java.io.IOException; * @brief Contains information about why a request was unsuccessfull. * @date 28 of September of 2016 */ -public class ResponseParameters implements IBotApiObject { +public class ResponseParameters implements BotApiObject { private static final String MIGRATETOCHATID_FIELD = "migrate_to_chat_id"; private static final String RETRYAFTER_FIELD = "retry_after"; - @JsonProperty(MIGRATETOCHATID_FIELD) /** * Optional. The group has been migrated to a supergroup with the specified identifier. * This number may be greater than 32 bits and some programming languages may have * difficulty/silent defects in interpreting it. But it is smaller than 52 bits, * so a signed 64 bit integer or double-precision float type are safe for storing this identifier. */ + @JsonProperty(MIGRATETOCHATID_FIELD) private Integer migrateToChatId; - @JsonProperty(RETRYAFTER_FIELD) /** * Optional. In case of exceeding flood control a number of seconds to * wait before the request can be repeated */ + @JsonProperty(RETRYAFTER_FIELD) private Integer retryAfter; - public ResponseParameters(JSONObject object) { - if (object != null) { - if (object.has(MIGRATETOCHATID_FIELD)) { - migrateToChatId = object.getInt(MIGRATETOCHATID_FIELD); - } - if (object.has(RETRYAFTER_FIELD)) { - retryAfter = object.getInt(RETRYAFTER_FIELD); - } - } + public ResponseParameters() { + super(); } public Integer getMigrateToChatId() { @@ -72,20 +59,10 @@ public class ResponseParameters implements IBotApiObject { } @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - if (migrateToChatId != null) { - gen.writeNumberField(MIGRATETOCHATID_FIELD, migrateToChatId); - } - if (retryAfter != null) { - gen.writeNumberField(RETRYAFTER_FIELD, retryAfter); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); + public String toString() { + return "ResponseParameters{" + + "migrateToChatId=" + migrateToChatId + + ", retryAfter=" + retryAfter + + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Sticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Sticker.java similarity index 51% rename from src/main/java/org/telegram/telegrambots/api/objects/Sticker.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Sticker.java index 4861edb8..1984dd90 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Sticker.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Sticker.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,7 +10,7 @@ import java.io.IOException; * @brief This object represents a sticker. * @date 20 of June of 2015 */ -public class Sticker implements IBotApiObject { +public class Sticker implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String WIDTH_FIELD = "width"; @@ -24,6 +18,7 @@ public class Sticker implements IBotApiObject { private static final String THUMB_FIELD = "thumb"; private static final String FILESIZE_FIELD = "file_size"; private static final String EMOJI_FIELD = "emoji"; + @JsonProperty(FILEID_FIELD) private String fileId; ///< Unique identifier for this file @JsonProperty(WIDTH_FIELD) @@ -41,22 +36,6 @@ public class Sticker implements IBotApiObject { super(); } - public Sticker(JSONObject jsonObject) { - super(); - this.fileId = jsonObject.getString(FILEID_FIELD); - this.width = jsonObject.getInt(WIDTH_FIELD); - this.height = jsonObject.getInt(HEIGHT_FIELD); - if (jsonObject.has(THUMB_FIELD)) { - this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD)); - } - if (jsonObject.has(FILESIZE_FIELD)) { - this.fileSize = jsonObject.getInt(FILESIZE_FIELD); - } - if (jsonObject.has(EMOJI_FIELD)) { - this.emoji = jsonObject.getString(EMOJI_FIELD); - } - } - public String getFileId() { return fileId; } @@ -81,30 +60,6 @@ public class Sticker implements IBotApiObject { return emoji; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(WIDTH_FIELD, width); - gen.writeNumberField(HEIGHT_FIELD, height); - if (thumb != null) { - gen.writeObjectField(THUMB_FIELD, thumb); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - if (emoji != null) { - gen.writeStringField(EMOJI_FIELD, emoji); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Sticker{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Update.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Update.java similarity index 57% rename from src/main/java/org/telegram/telegrambots/api/objects/Update.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Update.java index 876e023e..241974aa 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Update.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Update.java @@ -1,17 +1,11 @@ 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 org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.inlinequery.ChosenInlineQuery; import org.telegram.telegrambots.api.objects.inlinequery.InlineQuery; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -19,13 +13,14 @@ import java.io.IOException; * Only one of the optional parameters can be present in any given update. * @date 20 of June of 2015 */ -public class Update implements IBotApiObject { +public class Update implements BotApiObject { private static final String UPDATEID_FIELD = "update_id"; private static final String MESSAGE_FIELD = "message"; private static final String INLINEQUERY_FIELD = "inline_query"; private static final String CHOSENINLINEQUERY_FIELD = "chosen_inline_result"; private static final String CALLBACKQUERY_FIELD = "callback_query"; private static final String EDITEDMESSAGE_FIELD = "edited_message"; + @JsonProperty(UPDATEID_FIELD) private Integer updateId; @JsonProperty(MESSAGE_FIELD) @@ -43,26 +38,6 @@ public class Update implements IBotApiObject { super(); } - public Update(JSONObject jsonObject) { - super(); - this.updateId = jsonObject.getInt(UPDATEID_FIELD); - if (jsonObject.has(MESSAGE_FIELD)) { - this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD)); - } - if (jsonObject.has(INLINEQUERY_FIELD)) { - this.inlineQuery = new InlineQuery(jsonObject.getJSONObject(INLINEQUERY_FIELD)); - } - if (jsonObject.has(CHOSENINLINEQUERY_FIELD)) { - this.chosenInlineQuery = new ChosenInlineQuery(jsonObject.getJSONObject(CHOSENINLINEQUERY_FIELD)); - } - if (jsonObject.has(CALLBACKQUERY_FIELD)) { - callbackQuery = new CallbackQuery(jsonObject.getJSONObject(CALLBACKQUERY_FIELD)); - } - if (jsonObject.has(EDITEDMESSAGE_FIELD)){ - editedMessage = new Message(jsonObject.getJSONObject(EDITEDMESSAGE_FIELD)); - } - } - public Integer getUpdateId() { return updateId; } @@ -106,33 +81,6 @@ public class Update implements IBotApiObject { public boolean hasEditedMessage() { return editedMessage != null; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(UPDATEID_FIELD, updateId); - if (message != null) { - gen.writeObjectField(MESSAGE_FIELD, message); - } - if (inlineQuery != null) { - gen.writeObjectField(INLINEQUERY_FIELD, inlineQuery); - } - if (chosenInlineQuery != null) { - gen.writeObjectField(CHOSENINLINEQUERY_FIELD, chosenInlineQuery); - } - if (callbackQuery != null) { - gen.writeObjectField(CALLBACKQUERY_FIELD, callbackQuery); - } - if (editedMessage != null) { - gen.writeObjectField(EDITEDMESSAGE_FIELD, editedMessage); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } @Override public String toString() { diff --git a/src/main/java/org/telegram/telegrambots/api/objects/User.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/User.java similarity index 50% rename from src/main/java/org/telegram/telegrambots/api/objects/User.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/User.java index 701aea85..0ec03e51 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/User.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/User.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,12 +10,13 @@ import java.io.IOException; * @brief This object represents a Telegram user or bot. * @date 20 of June of 2015 */ -public class User implements IBotApiObject { +public class User implements BotApiObject { private static final String ID_FIELD = "id"; private static final String FIRSTNAME_FIELD = "first_name"; private static final String LASTNAME_FIELD = "last_name"; private static final String USERNAME_FIELD = "username"; + @JsonProperty(ID_FIELD) private Integer id; ///< Unique identifier for this user or bot @JsonProperty(FIRSTNAME_FIELD) @@ -35,18 +30,6 @@ public class User implements IBotApiObject { super(); } - public User(JSONObject jsonObject) { - super(); - this.id = jsonObject.getInt(ID_FIELD); - this.firstName = jsonObject.getString(FIRSTNAME_FIELD); - if (jsonObject.has(LASTNAME_FIELD)) { - this.lastName = jsonObject.getString(LASTNAME_FIELD); - } - if (jsonObject.has(USERNAME_FIELD)) { - this.userName = jsonObject.getString(USERNAME_FIELD); - } - } - public Integer getId() { return id; } @@ -63,26 +46,6 @@ public class User implements IBotApiObject { return userName; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(ID_FIELD, id); - gen.writeStringField(FIRSTNAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LASTNAME_FIELD, lastName); - } - if (userName != null) { - gen.writeStringField(USERNAME_FIELD, userName); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "User{" + diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/UserProfilePhotos.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/UserProfilePhotos.java new file mode 100644 index 00000000..bb3c8ab0 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/UserProfilePhotos.java @@ -0,0 +1,44 @@ +package org.telegram.telegrambots.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.telegram.telegrambots.api.interfaces.BotApiObject; + +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief This object represent a user's profile pictures. + * @date 22 of June of 2015 + */ +public class UserProfilePhotos implements BotApiObject { + + private static final String TOTALCOUNT_FIELD = "total_count"; + private static final String PHOTOS_FIELD = "photos"; + + @JsonProperty(TOTALCOUNT_FIELD) + private Integer totalCount; ///< Total number of profile pictures the target user has + @JsonProperty(PHOTOS_FIELD) + private List> photos; ///< Requested profile pictures (in up to 4 sizes each) + + public UserProfilePhotos() { + super(); + } + + public Integer getTotalCount() { + return totalCount; + } + + public List> getPhotos() { + return photos; + } + + @Override + public String toString() { + return "UserProfilePhotos{" + + "totalCount=" + totalCount + + ", photos=" + photos + + '}'; + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Venue.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Venue.java similarity index 50% rename from src/main/java/org/telegram/telegrambots/api/objects/Venue.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Venue.java index 7bfd6b4b..ba232b93 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Venue.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Venue.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,7 +10,7 @@ import java.io.IOException; * @brief This object represents a venue. * @date 10 of April of 2016 */ -public class Venue implements IBotApiObject { +public class Venue implements BotApiObject { private static final String LOCATION_FIELD = "location"; private static final String TITLE_FIELD = "title"; private static final String ADDRESS_FIELD = "address"; @@ -31,21 +25,10 @@ public class Venue implements IBotApiObject { @JsonProperty(FOURSQUARE_ID_FIELD) private String foursquareId; ///< Optional. Foursquare identifier of the venue - public Venue() { super(); } - public Venue(JSONObject jsonObject) { - super(); - location = new Location(jsonObject.getJSONObject(LOCATION_FIELD)); - title = jsonObject.getString(TITLE_FIELD); - address = jsonObject.getString(ADDRESS_FIELD); - if (jsonObject.has(FOURSQUARE_ID_FIELD)) { - foursquareId = jsonObject.getString(FOURSQUARE_ID_FIELD); - } - } - public Location getLocation() { return location; } @@ -62,24 +45,6 @@ public class Venue implements IBotApiObject { return foursquareId; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeObjectField(LOCATION_FIELD, location); - gen.writeStringField(TITLE_FIELD, title); - gen.writeStringField(ADDRESS_FIELD, address); - if (foursquareId != null) { - gen.writeStringField(FOURSQUARE_ID_FIELD, foursquareId); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Venue{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Video.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Video.java similarity index 54% rename from src/main/java/org/telegram/telegrambots/api/objects/Video.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Video.java index e62dde1c..9d7d64d4 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Video.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Video.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,7 +10,7 @@ import java.io.IOException; * @brief This object represents a video file. * @date 20 of June of 2015 */ -public class Video implements IBotApiObject { +public class Video implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String WIDTH_FIELD = "width"; @@ -25,6 +19,7 @@ public class Video implements IBotApiObject { private static final String THUMB_FIELD = "thumb"; private static final String MIMETYPE_FIELD = "mime_type"; private static final String FILESIZE_FIELD = "file_size"; + @JsonProperty(FILEID_FIELD) private String fileId; ///< Unique identifier for this file @JsonProperty(WIDTH_FIELD) @@ -44,22 +39,6 @@ public class Video implements IBotApiObject { super(); } - public Video(JSONObject jsonObject) { - this.fileId = jsonObject.getString(FILEID_FIELD); - this.width = jsonObject.getInt(WIDTH_FIELD); - this.height = jsonObject.getInt(HEIGHT_FIELD); - this.duration = jsonObject.getInt(DURATION_FIELD); - if (jsonObject.has(THUMB_FIELD)) { - this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD)); - } - if (jsonObject.has(MIMETYPE_FIELD)) { - this.mimeType = jsonObject.getString(MIMETYPE_FIELD); - } - if (jsonObject.has(FILESIZE_FIELD)) { - this.fileSize = jsonObject.getInt(FILESIZE_FIELD); - } - } - public String getFileId() { return fileId; } @@ -88,31 +67,6 @@ public class Video implements IBotApiObject { return fileSize; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(WIDTH_FIELD, width); - gen.writeNumberField(HEIGHT_FIELD, height); - gen.writeNumberField(DURATION_FIELD, duration); - if (thumb != null) { - gen.writeObjectField(THUMB_FIELD, thumb); - } - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Video{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Voice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Voice.java similarity index 50% rename from src/main/java/org/telegram/telegrambots/api/objects/Voice.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Voice.java index d2ab54c6..1d6c5046 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Voice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/Voice.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,11 +10,12 @@ import java.io.IOException; * @brief This object represents a voice note * @date 16 of July of 2015 */ -public class Voice implements IBotApiObject { +public class Voice implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String DURATION_FIELD = "duration"; private static final String MIMETYPE_FIELD = "mime_type"; private static final String FILESIZE_FIELD = "file_size"; + @JsonProperty(FILEID_FIELD) private String fileId; ///< Unique identifier for this file @JsonProperty(DURATION_FIELD) @@ -34,18 +29,6 @@ public class Voice implements IBotApiObject { super(); } - public Voice(JSONObject jsonObject) { - super(); - this.fileId = jsonObject.getString(FILEID_FIELD); - this.duration = jsonObject.getInt(DURATION_FIELD); - if (jsonObject.has(MIMETYPE_FIELD)) { - this.mimeType = jsonObject.getString(MIMETYPE_FIELD); - } - if (jsonObject.has(FILESIZE_FIELD)) { - this.fileSize = jsonObject.getInt(FILESIZE_FIELD); - } - } - public String getFileId() { return fileId; } @@ -62,26 +45,6 @@ public class Voice implements IBotApiObject { return fileSize; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - gen.writeNumberField(DURATION_FIELD, duration); - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, mimeType); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Voice{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java similarity index 52% rename from src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java index 91284e60..4d5a1bd1 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java @@ -1,14 +1,8 @@ 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; +import org.telegram.telegrambots.api.interfaces.BotApiObject; /** * @author Ruben Bermudez @@ -16,7 +10,7 @@ import java.io.IOException; * @brief Contains information about the current status of a webhook. * @date 12 of August of 2016 */ -public class WebhookInfo implements IBotApiObject { +public class WebhookInfo implements BotApiObject { private static final String URL_FIELD = "url"; private static final String HASCUSTOMCERTIFICATE_FIELD = "has_custom_certificate"; @@ -35,21 +29,8 @@ public class WebhookInfo implements IBotApiObject { @JsonProperty(LASTERRORMESSAGE_FIELD) private String lastErrorMessage; ///< Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook - 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); - } - + super(); } public String getUrl() { @@ -71,24 +52,4 @@ public class WebhookInfo implements IBotApiObject { 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/games/Animation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/Animation.java similarity index 59% rename from src/main/java/org/telegram/telegrambots/api/objects/games/Animation.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/Animation.java index 7da65acd..f5a2bfa1 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/games/Animation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/Animation.java @@ -17,23 +17,17 @@ package org.telegram.telegrambots.api.objects.games; 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 org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.PhotoSize; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 2.4 * @brief This object represents an animation file. * @date 27 of September of 2016 */ -public class Animation implements IBotApiObject { +public class Animation implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String THUMB_FIELD = "thumb"; private static final String FILENAME_FIELD = "file_name"; @@ -55,23 +49,6 @@ public class Animation implements IBotApiObject { super(); } - public Animation(JSONObject object) { - super(); - fileId = object.getString(FILEID_FIELD); - if (object.has(THUMB_FIELD)) { - thumb = new PhotoSize(object.getJSONObject(THUMB_FIELD)); - } - if (object.has(FILENAME_FIELD)) { - fileName = object.getString(FILENAME_FIELD); - } - if (object.has(MIMETYPE_FIELD)) { - mimetype = object.getString(MIMETYPE_FIELD); - } - if (object.has(FILESIZE_FIELD)) { - fileSize = object.getInt(FILESIZE_FIELD); - } - } - public String getFileId() { return fileId; } @@ -92,31 +69,6 @@ public class Animation implements IBotApiObject { return fileSize; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(FILEID_FIELD, fileId); - if (thumb != null) { - gen.writeObjectField(THUMB_FIELD, thumb); - } - if (fileName != null) { - gen.writeStringField(FILENAME_FIELD, fileName); - } - if (mimetype != null) { - gen.writeStringField(MIMETYPE_FIELD, mimetype); - } - if (fileSize != null) { - gen.writeNumberField(FILESIZE_FIELD, fileSize); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Animation{" + diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/CallbackGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/CallbackGame.java new file mode 100644 index 00000000..6458687d --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/CallbackGame.java @@ -0,0 +1,37 @@ +/* + * This file is part of TelegramBots. + * + * TelegramBots is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * TelegramBots is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with TelegramBots. If not, see . + */ + +package org.telegram.telegrambots.api.objects.games; + +import org.telegram.telegrambots.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 2.4 + * @brief A placeholder, currently holds no information. Use BotFather to set up your game. + * @date 16 of September of 2016 + */ +public class CallbackGame implements BotApiObject { + public CallbackGame() { + super(); + } + + @Override + public String toString() { + return "CallbackGame{}"; + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/games/Game.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/Game.java similarity index 57% rename from src/main/java/org/telegram/telegrambots/api/objects/games/Game.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/Game.java index a4ada5d4..35385f6e 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/games/Game.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/Game.java @@ -17,18 +17,11 @@ package org.telegram.telegrambots.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; -import org.json.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; +import org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.MessageEntity; import org.telegram.telegrambots.api.objects.PhotoSize; -import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -38,7 +31,8 @@ import java.util.List; * Use BotFather to create and edit games, their short names will act as unique identifiers. * @date 27 of September of 2016 */ -public class Game implements IBotApiObject { +public class Game implements BotApiObject { + private static final String TITLE_FIELD = "title"; private static final String DESCRIPTION_FIELD = "description"; private static final String PHOTO_FIELD = "photo"; @@ -52,19 +46,19 @@ public class Game implements IBotApiObject { private String description; ///< Description of the game @JsonProperty(PHOTO_FIELD) private List photo; ///< Photo - @JsonProperty(TEXT_FIELD) /** * Optional. Brief description of the game or high scores included in the game message. * Can be automatically edited to include current high scores for the game * when the bot calls setGameScore, or manually edited using editMessageText. * 0-4096 characters. */ + @JsonProperty(TEXT_FIELD) private String text; - @JsonProperty(TEXTENTITIES_FIELD) /** * Optional. Special entities that appear in text, such as usernames, * URLs, bot commands, etc. */ + @JsonProperty(TEXTENTITIES_FIELD) private List entities; @JsonProperty(ANIMATION_FIELD) private Animation animation; ///< Optional. Animation @@ -73,30 +67,6 @@ public class Game implements IBotApiObject { super(); } - public Game(JSONObject object) { - super(); - title = object.getString(TITLE_FIELD); - description = object.getString(DESCRIPTION_FIELD); - this.photo = new ArrayList<>(); - JSONArray photos = object.getJSONArray(PHOTO_FIELD); - for (int i = 0; i < photos.length(); i++) { - this.photo.add(new PhotoSize(photos.getJSONObject(i))); - } - if (object.has(TEXT_FIELD)) { - text = object.getString(TEXT_FIELD); - } - if (object.has(TEXTENTITIES_FIELD)) { - this.entities = new ArrayList<>(); - JSONArray entities = object.getJSONArray(TEXTENTITIES_FIELD); - for (int i = 0; i < entities.length(); i++) { - this.entities.add(new MessageEntity(entities.getJSONObject(i))); - } - } - if (object.has(ANIMATION_FIELD)) { - animation = new Animation(object.getJSONObject(ANIMATION_FIELD)); - } - } - public String getTitle() { return title; } @@ -125,38 +95,6 @@ public class Game implements IBotApiObject { return entities; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TITLE_FIELD, title); - gen.writeStringField(DESCRIPTION_FIELD, description); - gen.writeArrayFieldStart(PHOTO_FIELD); - for (PhotoSize photoSize : photo) { - gen.writeObject(photoSize); - } - gen.writeEndArray(); - if (animation != null) { - gen.writeObjectField(ANIMATION_FIELD, animation); - } - if (text != null) { - gen.writeStringField(TEXT_FIELD, text); - } - if (entities != null) { - gen.writeArrayFieldStart(TEXTENTITIES_FIELD); - for (MessageEntity entity : entities) { - gen.writeObject(entity); - } - gen.writeEndArray(); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "Game{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/games/GameHighScore.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/GameHighScore.java similarity index 62% rename from src/main/java/org/telegram/telegrambots/api/objects/games/GameHighScore.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/GameHighScore.java index b0546f86..1ac670fb 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/games/GameHighScore.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/games/GameHighScore.java @@ -18,23 +18,17 @@ package org.telegram.telegrambots.api.objects.games; 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 org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.User; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 * @brief This object represents one row of a game high scores table * @date 25 of September of 2016 */ -public class GameHighScore implements IBotApiObject { +public class GameHighScore implements BotApiObject { private static final String POSITION_FIELD = "position"; private static final String USER_FIELD = "user"; private static final String SCORE_FIELD = "score"; @@ -46,12 +40,6 @@ public class GameHighScore implements IBotApiObject { @JsonProperty(SCORE_FIELD) private Integer score; ///< Score - public GameHighScore(JSONObject object) { - position = object.getInt(POSITION_FIELD); - user = new User(object.getJSONObject(USER_FIELD)); - score = object.getInt(SCORE_FIELD); - } - public Integer getPosition() { return position; } @@ -64,21 +52,6 @@ public class GameHighScore implements IBotApiObject { return score; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(POSITION_FIELD, position); - gen.writeObjectField(USER_FIELD, user); - gen.writeNumberField(SCORE_FIELD, score); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "GameHighScore{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/ChosenInlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/ChosenInlineQuery.java similarity index 57% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/ChosenInlineQuery.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/ChosenInlineQuery.java index 6be335de..dbaee14f 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/ChosenInlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/ChosenInlineQuery.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery; 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 org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.Location; import org.telegram.telegrambots.api.objects.User; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -19,7 +13,7 @@ import java.io.IOException; * partner. * @date 01 of January of 2016 */ -public class ChosenInlineQuery implements IBotApiObject { +public class ChosenInlineQuery implements BotApiObject { private static final String RESULTID_FIELD = "result_id"; private static final String FROM_FIELD = "from"; private static final String LOCATION_FIELD = "location"; @@ -32,13 +26,13 @@ public class ChosenInlineQuery implements IBotApiObject { private User from; ///< The user that chose the result. @JsonProperty(LOCATION_FIELD) private Location location; ///< Optional. Sender location, only for bots that require user location - @JsonProperty(INLINE_MESSAGE_ID_FIELD) /** * Optional. * Identifier of the sent inline message. * Available only if there is an inline keyboard attached to the message. * Will be also received in callback queries and can be used to edit the message. */ + @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; @JsonProperty(QUERY_FIELD) private String query; ///< The query that was used to obtain the result. @@ -47,19 +41,6 @@ public class ChosenInlineQuery implements IBotApiObject { super(); } - public ChosenInlineQuery(JSONObject jsonObject) { - super(); - this.resultId = jsonObject.getString(RESULTID_FIELD); - this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); - if (jsonObject.has(LOCATION_FIELD)) { - location = new Location(jsonObject.getJSONObject(LOCATION_FIELD)); - } - if (jsonObject.has(INLINE_MESSAGE_ID_FIELD)) { - inlineMessageId = jsonObject.getString(INLINE_MESSAGE_ID_FIELD); - } - this.query = jsonObject.getString(QUERY_FIELD); - } - public String getResultId() { return resultId; } @@ -80,27 +61,6 @@ public class ChosenInlineQuery implements IBotApiObject { return query; } - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(RESULTID_FIELD, resultId); - gen.writeObjectField(FROM_FIELD, from); - if (location != null) { - gen.writeObjectField(LOCATION_FIELD, location); - } - if (inlineMessageId != null) { - gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId); - } - gen.writeStringField(QUERY_FIELD, query); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "ChosenInlineQuery{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/InlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/InlineQuery.java similarity index 58% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/InlineQuery.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/InlineQuery.java index ee5812b6..e55014d8 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/InlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/InlineQuery.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery; 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 org.telegram.telegrambots.api.interfaces.BotApiObject; import org.telegram.telegrambots.api.objects.Location; import org.telegram.telegrambots.api.objects.User; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -19,12 +13,13 @@ import java.io.IOException; * bot could return some default or trending results. * @date 01 of January of 2016 */ -public class InlineQuery implements IBotApiObject { +public class InlineQuery implements BotApiObject { private static final String ID_FIELD = "id"; private static final String FROM_FIELD = "from"; private static final String LOCATION_FIELD = "location"; private static final String QUERY_FIELD = "query"; private static final String OFFSET_FIELD = "offset"; + @JsonProperty(ID_FIELD) private String id; ///< Unique identifier for this query @JsonProperty(FROM_FIELD) @@ -40,31 +35,6 @@ public class InlineQuery implements IBotApiObject { super(); } - public InlineQuery(JSONObject jsonObject) { - super(); - this.id = jsonObject.getString(ID_FIELD); - this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); - if (jsonObject.has(LOCATION_FIELD)) { - location = new Location(jsonObject.getJSONObject(LOCATION_FIELD)); - } - this.query = jsonObject.getString(QUERY_FIELD); - this.offset = jsonObject.getString(OFFSET_FIELD); - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(ID_FIELD, id); - gen.writeObjectField(FROM_FIELD, from); - if (location != null) { - gen.writeObjectField(LOCATION_FIELD, location); - } - gen.writeStringField(QUERY_FIELD, query); - gen.writeStringField(OFFSET_FIELD, offset); - gen.writeEndObject(); - gen.flush(); - } - public String getId() { return id; } @@ -93,11 +63,6 @@ public class InlineQuery implements IBotApiObject { return location != null; } - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQuery{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java similarity index 67% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java index a2cf7714..c0dfc63b 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java @@ -1,15 +1,9 @@ package org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent; 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.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -23,6 +17,7 @@ public class InputContactMessageContent implements InputMessageContent { private static final String PHONE_NUMBER_FIELD = "phone_number"; private static final String FIRST_NAME_FIELD = "first_name"; private static final String LAST_NAME_FIELD = "last_name"; + @JsonProperty(PHONE_NUMBER_FIELD) private String phoneNumber; ///< Contact's phone number @JsonProperty(FIRST_NAME_FIELD) @@ -71,34 +66,6 @@ public class InputContactMessageContent implements InputMessageContent { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(PHONE_NUMBER_FIELD, phoneNumber); - jsonObject.put(FIRST_NAME_FIELD, firstName); - if (lastName != null) { - jsonObject.put(LAST_NAME_FIELD, lastName); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(PHONE_NUMBER_FIELD, phoneNumber); - gen.writeStringField(FIRST_NAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LAST_NAME_FIELD, lastName); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InputContactMessageContent{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java similarity index 67% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java index 7dfd57a4..cda61d2a 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java @@ -1,15 +1,9 @@ package org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent; 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.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,6 +16,7 @@ public class InputLocationMessageContent implements InputMessageContent { private static final String LATITUDE_FIELD = "latitude"; private static final String LONGITUDE_FIELD = "longitude"; + @JsonProperty(LATITUDE_FIELD) private Float latitude; ///< Latitude of the location in degrees @JsonProperty(LONGITUDE_FIELD) @@ -59,28 +54,6 @@ public class InputLocationMessageContent implements InputMessageContent { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(LATITUDE_FIELD, latitude); - jsonObject.put(LONGITUDE_FIELD, longitude); - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InputLocationMessageContent{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java similarity index 61% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java index 8575d4a0..5b80870d 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java @@ -1,7 +1,6 @@ package org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; -import org.telegram.telegrambots.api.interfaces.IToJson; +import org.telegram.telegrambots.api.interfaces.InputBotApiObject; import org.telegram.telegrambots.api.interfaces.Validable; /** @@ -11,5 +10,5 @@ import org.telegram.telegrambots.api.interfaces.Validable; * query. * @date 10 of April of 2016 */ -public interface InputMessageContent extends IBotApiObject, IToJson, Validable { +public interface InputMessageContent extends InputBotApiObject, Validable { } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java index e8d61b49..fafdae30 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java @@ -1,16 +1,10 @@ package org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent; 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.methods.ParseMode; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,6 +16,7 @@ public class InputTextMessageContent implements InputMessageContent { private static final String MESSAGETEXT_FIELD = "message_text"; private static final String PARSEMODE_FIELD = "parse_mode"; private static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + @JsonProperty(MESSAGETEXT_FIELD) private String messageText; ///< Text of a message to be sent, 1-4096 characters @JsonProperty(PARSEMODE_FIELD) @@ -95,39 +90,6 @@ public class InputTextMessageContent implements InputMessageContent { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(MESSAGETEXT_FIELD, this.messageText); - if (parseMode != null) { - jsonObject.put(PARSEMODE_FIELD, this.parseMode); - } - if (disableWebPagePreview != null) { - jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(MESSAGETEXT_FIELD, messageText); - if (parseMode != null) { - gen.writeStringField(PARSEMODE_FIELD, this.parseMode); - } - if (disableWebPagePreview != null) { - gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InputTextMessageContent{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java similarity index 71% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java index e02c9a6d..aa316281 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java @@ -1,15 +1,9 @@ package org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent; 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.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -25,6 +19,7 @@ public class InputVenueMessageContent implements InputMessageContent { private static final String TITLE_FIELD = "title"; private static final String ADDRESS_FIELD = "address"; private static final String FOURSQUARE_ID_FIELD = "foursquare_id"; + @JsonProperty(LATITUDE_FIELD) private Float latitude; ///< Latitude of the venue in degrees @JsonProperty(LONGITUDE_FIELD) @@ -101,38 +96,6 @@ public class InputVenueMessageContent implements InputMessageContent { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(LATITUDE_FIELD, latitude); - jsonObject.put(LONGITUDE_FIELD, longitude); - jsonObject.put(TITLE_FIELD, title); - jsonObject.put(ADDRESS_FIELD, address); - if (foursquareId != null) { - jsonObject.put(FOURSQUARE_ID_FIELD, foursquareId); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeStringField(TITLE_FIELD, title); - gen.writeStringField(ADDRESS_FIELD, address); - if (foursquareId != null) { - gen.writeStringField(FOURSQUARE_ID_FIELD, foursquareId); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InputVenueMessageContent{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResult.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResult.java similarity index 57% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResult.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResult.java index a744ca89..6789f287 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResult.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResult.java @@ -1,7 +1,6 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; -import org.telegram.telegrambots.api.interfaces.IToJson; +import org.telegram.telegrambots.api.interfaces.InputBotApiObject; import org.telegram.telegrambots.api.interfaces.Validable; /** @@ -10,5 +9,5 @@ import org.telegram.telegrambots.api.interfaces.Validable; * @brief This object represents one result of an inline query. * @date 01 of January of 2016 */ -public interface InlineQueryResult extends IBotApiObject, IToJson, Validable { +public interface InlineQueryResult extends InputBotApiObject, Validable { } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultArticle.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultArticle.java similarity index 69% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultArticle.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultArticle.java index 769e4832..9c8a3218 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultArticle.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultArticle.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -21,8 +15,6 @@ import java.io.IOException; public class InlineQueryResultArticle implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "article"; ///< Type of the result, must be “article” private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; @@ -33,6 +25,9 @@ public class InlineQueryResultArticle implements InlineQueryResult { private static final String THUMBURL_FIELD = "thumb_url"; private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "article"; ///< Type of the result, must be “article” @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) @@ -54,6 +49,10 @@ public class InlineQueryResultArticle implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height + public InlineQueryResultArticle() { + super(); + } + public static String getType() { return type; } @@ -165,77 +164,6 @@ public class InlineQueryResultArticle implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(TITLE_FIELD, this.title); - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (url != null) { - jsonObject.put(URL_FIELD, this.url); - } - if (hideUrl != null) { - jsonObject.put(HIDEURL_FIELD, this.hideUrl); - } - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth); - } - if (thumbHeight != null) { - jsonObject.put(THUMBHEIGHT_FIELD, this.thumbHeight); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(TITLE_FIELD, title); - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (url != null) { - gen.writeStringField(URL_FIELD, this.url); - } - if (hideUrl != null) { - gen.writeBooleanField(HIDEURL_FIELD, this.hideUrl); - } - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, this.description); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - gen.writeNumberField(THUMBWIDTH_FIELD, this.thumbWidth); - } - if (thumbHeight != null) { - gen.writeNumberField(THUMBHEIGHT_FIELD, this.thumbHeight); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultArticle{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultAudio.java similarity index 69% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultAudio.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultAudio.java index 5f24a607..fd3d70d9 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultAudio.java @@ -1,16 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,8 +19,6 @@ import java.io.IOException; public class InlineQueryResultAudio implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "audio"; ///< Type of the result, must be "audio" private static final String ID_FIELD = "id"; private static final String AUDIOURL_FIELD = "audio_url"; private static final String TITLE_FIELD = "title"; @@ -34,6 +27,9 @@ public class InlineQueryResultAudio implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "audio"; ///< Type of the result, must be "audio" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result @JsonProperty(AUDIOURL_FIELD) @@ -51,6 +47,10 @@ public class InlineQueryResultAudio implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Audio caption (may also be used when resending documents by file_id), 0-200 characters + public InlineQueryResultAudio() { + super(); + } + public static String getType() { return type; } @@ -143,68 +143,6 @@ public class InlineQueryResultAudio implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(AUDIOURL_FIELD, audioUrl); - if (title != null) { - jsonObject.put(TITLE_FIELD, title); - } - if (performer != null) { - jsonObject.put(PERFORMER_FIELD, performer); - } - if (audioDuration != null) { - jsonObject.put(AUDIO_DURATION_FIELD, audioDuration); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(AUDIOURL_FIELD, audioUrl); - if (title != null) { - gen.writeStringField(TITLE_FIELD, title); - } - if (performer != null) { - gen.writeStringField(PERFORMER_FIELD, performer); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (audioDuration != null) { - gen.writeNumberField(AUDIO_DURATION_FIELD, audioDuration); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultAudio{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultContact.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultContact.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultContact.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultContact.java index 26d7b0db..aa5aafe6 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultContact.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultContact.java @@ -1,16 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,8 +19,6 @@ import java.io.IOException; public class InlineQueryResultContact implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "contact"; ///< Type of the result, must be "contact" private static final String ID_FIELD = "id"; private static final String PHONE_NUMBER_FIELD = "phone_number"; private static final String FIRST_NAME_FIELD = "first_name"; @@ -35,6 +28,9 @@ public class InlineQueryResultContact implements InlineQueryResult { private static final String THUMBURL_FIELD = "thumb_url"; private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "contact"; ///< Type of the result, must be "contact" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(PHONE_NUMBER_FIELD) @@ -54,6 +50,10 @@ public class InlineQueryResultContact implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height + public InlineQueryResultContact() { + super(); + } + public static String getType() { return type; } @@ -158,69 +158,6 @@ public class InlineQueryResultContact implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(PHONE_NUMBER_FIELD, phoneNumber); - jsonObject.put(FIRST_NAME_FIELD, firstName); - if (lastName != null) { - jsonObject.put(LAST_NAME_FIELD, lastName); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth); - } - if (thumbHeight != null) { - jsonObject.put(THUMBHEIGHT_FIELD, thumbHeight); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(PHONE_NUMBER_FIELD, phoneNumber); - gen.writeStringField(FIRST_NAME_FIELD, firstName); - if (lastName != null) { - gen.writeStringField(LAST_NAME_FIELD, lastName); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - gen.writeNumberField(THUMBWIDTH_FIELD, thumbWidth); - } - if (thumbHeight != null) { - gen.writeNumberField(THUMBHEIGHT_FIELD, thumbHeight); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultContact{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultDocument.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultDocument.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultDocument.java index be381a47..f9b38a2c 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultDocument.java @@ -1,16 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -25,8 +20,6 @@ import java.io.IOException; public class InlineQueryResultDocument implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "document"; ///< Type of the result, must be "document" private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String DOCUMENTURL_FIELD = "document_url"; @@ -38,6 +31,9 @@ public class InlineQueryResultDocument implements InlineQueryResult { private static final String THUMBURL_FIELD = "thumb_url"; private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "document"; ///< Type of the result, must be "document" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) @@ -61,6 +57,10 @@ public class InlineQueryResultDocument implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height + public InlineQueryResultDocument() { + super(); + } + public static String getType() { return type; } @@ -186,77 +186,6 @@ public class InlineQueryResultDocument implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(MIMETYPE_FIELD, mimeType); - jsonObject.put(TITLE_FIELD, title); - jsonObject.put(DOCUMENTURL_FIELD, documentUrl); - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth); - } - if (thumbHeight != null) { - jsonObject.put(THUMBHEIGHT_FIELD, thumbHeight); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(MIMETYPE_FIELD, mimeType); - gen.writeStringField(TITLE_FIELD, title); - gen.writeStringField(DOCUMENTURL_FIELD, documentUrl); - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, description); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - gen.writeNumberField(THUMBWIDTH_FIELD, thumbWidth); - } - if (thumbHeight != null) { - gen.writeNumberField(THUMBHEIGHT_FIELD, thumbHeight); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultDocument{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGame.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGame.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGame.java index 0602a425..7b4cfbfa 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGame.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGame.java @@ -18,16 +18,10 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -38,12 +32,12 @@ import java.io.IOException; public class InlineQueryResultGame implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "game"; ///< Type of the result, must be "game" private static final String ID_FIELD = "id"; private static final String GAMESHORTNAME_FIELD = "game_short_name"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + @JsonProperty(TYPE_FIELD) + private static final String type = "game"; ///< Type of the result, must be "game" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GAMESHORTNAME_FIELD) @@ -51,6 +45,10 @@ public class InlineQueryResultGame implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultGame() { + super(); + } + public static String getType() { return type; } @@ -94,38 +92,6 @@ public class InlineQueryResultGame implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(GAMESHORTNAME_FIELD, gameShortName); - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(GAMESHORTNAME_FIELD, gameShortName); - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultGame{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGif.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGif.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGif.java index 29e51874..660b846e 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultGif.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -23,8 +17,6 @@ import java.io.IOException; public class InlineQueryResultGif implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "gif"; ///< Type of the result, must be "gif" private static final String ID_FIELD = "id"; private static final String GIFURL_FIELD = "gif_url"; private static final String GIFWIDTH_FIELD = "gif_width"; @@ -34,6 +26,9 @@ public class InlineQueryResultGif implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "gif"; ///< Type of the result, must be "gif" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GIFURL_FIELD) @@ -53,6 +48,10 @@ public class InlineQueryResultGif implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultGif() { + super(); + } + public static String getType() { return type; } @@ -154,72 +153,6 @@ public class InlineQueryResultGif implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(GIFURL_FIELD, this.gifUrl); - if (gifWidth != null) { - jsonObject.put(GIFWIDTH_FIELD, this.gifWidth); - } - if (gifHeight != null) { - jsonObject.put(GIFHEIGHT_FIELD, this.gifHeight); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(GIFURL_FIELD, this.gifUrl); - if (gifWidth != null) { - gen.writeNumberField(GIFWIDTH_FIELD, this.gifWidth); - } - if (gifHeight != null) { - gen.writeNumberField(GIFHEIGHT_FIELD, this.gifHeight); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultGif{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultLocation.java similarity index 71% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultLocation.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultLocation.java index 33d658a4..34085786 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultLocation.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -25,8 +19,6 @@ import java.io.IOException; public class InlineQueryResultLocation implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "location"; ///< Type of the result, must be "location" private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String LATITUDE_FIELD = "latitude"; @@ -36,6 +28,9 @@ public class InlineQueryResultLocation implements InlineQueryResult { private static final String THUMBURL_FIELD = "thumb_url"; private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "location"; ///< Type of the result, must be "location" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) @@ -55,6 +50,10 @@ public class InlineQueryResultLocation implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height + public InlineQueryResultLocation() { + super(); + } + public static String getType() { return type; } @@ -162,65 +161,6 @@ public class InlineQueryResultLocation implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(LATITUDE_FIELD, latitude); - jsonObject.put(TITLE_FIELD, title); - jsonObject.put(LONGITUDE_FIELD, longitude); - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth); - } - if (thumbHeight != null) { - jsonObject.put(THUMBHEIGHT_FIELD, thumbHeight); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeStringField(TITLE_FIELD, title); - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - gen.writeNumberField(THUMBWIDTH_FIELD, thumbWidth); - } - if (thumbHeight != null) { - gen.writeNumberField(THUMBHEIGHT_FIELD, thumbHeight); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultLocation{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java similarity index 69% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java index aba0aaa0..6e3e38ab 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -23,8 +17,6 @@ import java.io.IOException; public class InlineQueryResultMpeg4Gif implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" private static final String ID_FIELD = "id"; private static final String MPEG4URL_FIELD = "mpeg4_url"; private static final String MPEG4WIDTH_FIELD = "mpeg4_width"; @@ -34,6 +26,9 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(MPEG4URL_FIELD) @@ -53,6 +48,10 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultMpeg4Gif() { + super(); + } + public static String getType() { return type; } @@ -154,74 +153,6 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(MPEG4URL_FIELD, this.mpeg4Url); - if (mpeg4Width != null) { - jsonObject.put(MPEG4WIDTH_FIELD, this.mpeg4Width); - } - if (mpeg4Height != null) { - jsonObject.put(MPEG4HEIGHT_FIELD, this.mpeg4Height); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(MPEG4URL_FIELD, this.mpeg4Url); - if (mpeg4Width != null) { - gen.writeNumberField(MPEG4WIDTH_FIELD, this.mpeg4Width); - } - if (mpeg4Height != null) { - gen.writeNumberField(MPEG4HEIGHT_FIELD, this.mpeg4Height); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultMpeg4Gif{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultPhoto.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultPhoto.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultPhoto.java index e3bd28c2..ccfa2796 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultPhoto.java @@ -1,16 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,8 +17,6 @@ import java.io.IOException; public class InlineQueryResultPhoto implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "photo"; ///< Type of the result, must be “photo” private static final String ID_FIELD = "id"; private static final String PHOTOURL_FIELD = "photo_url"; private static final String MIMETYPE_FIELD = "mime_type"; @@ -35,6 +28,9 @@ public class InlineQueryResultPhoto implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "photo"; ///< Type of the result, must be “photo” @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(PHOTOURL_FIELD) @@ -58,6 +54,10 @@ public class InlineQueryResultPhoto implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultPhoto() { + super(); + } + public static String getType() { return type; } @@ -177,87 +177,6 @@ public class InlineQueryResultPhoto implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(PHOTOURL_FIELD, this.photoUrl); - if (mimeType != null) { - jsonObject.put(MIMETYPE_FIELD, this.mimeType); - } - if (photoWidth != null) { - jsonObject.put(PHOTOWIDTH_FIELD, this.photoWidth); - } - if (photoHeight != null) { - jsonObject.put(PHOTOHEIGHT_FIELD, this.photoHeight); - } - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(PHOTOURL_FIELD, this.photoUrl); - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, this.mimeType); - } - if (photoWidth != null) { - gen.writeNumberField(PHOTOWIDTH_FIELD, this.photoWidth); - } - if (photoHeight != null) { - gen.writeNumberField(PHOTOHEIGHT_FIELD, this.photoHeight); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, this.description); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultPhoto{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVenue.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVenue.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVenue.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVenue.java index df21d6bb..9b3f3cd1 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVenue.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVenue.java @@ -1,17 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,8 +18,6 @@ import java.io.IOException; public class InlineQueryResultVenue implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "venue"; ///< Type of the result, must be "venue" private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String LATITUDE_FIELD = "latitude"; @@ -37,6 +29,9 @@ public class InlineQueryResultVenue implements InlineQueryResult { private static final String THUMBURL_FIELD = "thumb_url"; private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "venue"; ///< Type of the result, must be "venue" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) @@ -60,6 +55,10 @@ public class InlineQueryResultVenue implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height + public InlineQueryResultVenue() { + super(); + } + public static String getType() { return type; } @@ -189,73 +188,6 @@ public class InlineQueryResultVenue implements InlineQueryResult { } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(LATITUDE_FIELD, latitude); - jsonObject.put(TITLE_FIELD, title); - jsonObject.put(LONGITUDE_FIELD, longitude); - jsonObject.put(ADDRESS_FIELD, address); - if (foursquareId != null) { - jsonObject.put(FOURSQUARE_ID_FIELD, foursquareId); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - jsonObject.put(THUMBWIDTH_FIELD, this.thumbWidth); - } - if (thumbHeight != null) { - jsonObject.put(THUMBHEIGHT_FIELD, thumbHeight); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeNumberField(LONGITUDE_FIELD, longitude); - gen.writeNumberField(LATITUDE_FIELD, latitude); - gen.writeStringField(TITLE_FIELD, title); - gen.writeStringField(ADDRESS_FIELD, address); - if (foursquareId != null) { - gen.writeStringField(FOURSQUARE_ID_FIELD, foursquareId); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (thumbWidth != null) { - gen.writeNumberField(THUMBWIDTH_FIELD, thumbWidth); - } - if (thumbHeight != null) { - gen.writeNumberField(THUMBHEIGHT_FIELD, thumbHeight); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultVenue{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVideo.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVideo.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVideo.java index 53839476..23aa4891 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVideo.java @@ -1,16 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,8 +17,6 @@ import java.io.IOException; public class InlineQueryResultVideo implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "video"; ///< Type of the result, must be "video" private static final String ID_FIELD = "id"; private static final String MIMETYPE_FIELD = "mime_type"; private static final String VIDEOURL_FIELD = "video_url"; @@ -36,6 +29,9 @@ public class InlineQueryResultVideo implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "video"; ///< Type of the result, must be "video" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result @JsonProperty(MIMETYPE_FIELD) @@ -61,6 +57,10 @@ public class InlineQueryResultVideo implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultVideo() { + super(); + } + public static String getType() { return type; } @@ -189,93 +189,6 @@ public class InlineQueryResultVideo implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(VIDEOURL_FIELD, this.videoUrl); - if (mimeType != null) { - jsonObject.put(MIMETYPE_FIELD, this.mimeType); - } - if (videoWidth != null) { - jsonObject.put(VIDEOWIDTH_FIELD, this.videoWidth); - } - if (videoHeight != null) { - jsonObject.put(VIDEOHEIGHT_FIELD, this.videoHeight); - } - if (videoDuration != null) { - jsonObject.put(VIDEODURATION_FIELD, this.videoDuration); - } - if (thumbUrl != null) { - jsonObject.put(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(VIDEOURL_FIELD, this.videoUrl); - if (mimeType != null) { - gen.writeStringField(MIMETYPE_FIELD, this.mimeType); - } - if (videoWidth != null) { - gen.writeNumberField(VIDEOWIDTH_FIELD, this.videoWidth); - } - if (videoHeight != null) { - gen.writeNumberField(VIDEOHEIGHT_FIELD, this.videoHeight); - } - if (videoDuration != null) { - gen.writeNumberField(VIDEODURATION_FIELD, this.videoDuration); - } - if (thumbUrl != null) { - gen.writeStringField(THUMBURL_FIELD, this.thumbUrl); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, this.description); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultVideo{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java index eacc7a2d..d72748b9 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java @@ -1,16 +1,11 @@ package org.telegram.telegrambots.api.objects.inlinequery.result; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,8 +19,6 @@ import java.io.IOException; public class InlineQueryResultVoice implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "voice"; ///< Type of the result, must be "voice" private static final String ID_FIELD = "id"; private static final String VOICEURL_FIELD = "voice_url"; private static final String TITLE_FIELD = "title"; @@ -34,6 +27,8 @@ public class InlineQueryResultVoice implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; + @JsonProperty(TYPE_FIELD) + private static final String type = "voice"; ///< Type of the result, must be "voice" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(VOICEURL_FIELD) @@ -49,6 +44,9 @@ public class InlineQueryResultVoice implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Voice caption (may also be used when resending documents by file_id), 0-200 characters + public InlineQueryResultVoice() { + super(); + } public static String getType() { return type; @@ -133,60 +131,6 @@ public class InlineQueryResultVoice implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(VOICEURL_FIELD, voiceUrl); - if (title != null) { - jsonObject.put(TITLE_FIELD, title); - } - if (voiceDuration != null) { - jsonObject.put(VOICE_DURATION_FIELD, voiceDuration); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson()); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(VOICEURL_FIELD, voiceUrl); - if (title != null) { - gen.writeStringField(TITLE_FIELD, title); - } - if (voiceDuration != null) { - gen.writeNumberField(VOICE_DURATION_FIELD, voiceDuration); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultVoice{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java similarity index 71% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java index 8c1a5747..3413e3de 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -26,14 +20,14 @@ import java.io.IOException; public class InlineQueryResultCachedAudio implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "audio"; ///< Type of the result, must be "audio" private static final String ID_FIELD = "id"; private static final String AUDIO_FILE_ID_FIELD = "audio_file_id"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; + @JsonProperty(TYPE_FIELD) + private static final String type = "audio"; ///< Type of the result, must be "audio" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result @JsonProperty(AUDIO_FILE_ID_FIELD) @@ -45,6 +39,9 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Audio caption (may also be used when resending documents by file_id), 0-200 characters + public InlineQueryResultCachedAudio() { + super(); + } public static String getType() { return type; @@ -111,49 +108,6 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(AUDIO_FILE_ID_FIELD, audioFileId); - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(AUDIO_FILE_ID_FIELD, audioFileId); - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedAudio{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java index e1ae2231..684b3e24 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -27,8 +21,6 @@ import java.io.IOException; public class InlineQueryResultCachedDocument implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "document"; ///< Type of the result, must be "document" private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String DOCUMENT_FILE_ID_FIELD = "document_file_id"; @@ -36,6 +28,9 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "document"; ///< Type of the result, must be "document" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) @@ -51,6 +46,10 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { @JsonProperty(INPUTMESSAGECONTENT_FIELD) private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent instead of the file + public InlineQueryResultCachedDocument() { + super(); + } + public static String getType() { return type; } @@ -137,56 +136,6 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, id); - jsonObject.put(DOCUMENT_FILE_ID_FIELD, documentFileId); - jsonObject.put(TITLE_FIELD, title); - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(DOCUMENT_FILE_ID_FIELD, documentFileId); - gen.writeStringField(TITLE_FIELD, title); - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, description); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedDocument{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java index 0f0cead8..4a3dbe74 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,14 +18,15 @@ import java.io.IOException; public class InlineQueryResultCachedGif implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "gif"; ///< Type of the result, must be "gif" private static final String ID_FIELD = "id"; private static final String GIF_FILE_ID_FIELD = "gif_file_id"; private static final String TITLE_FIELD = "title"; private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "gif"; ///< Type of the result, must be "gif" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GIF_FILE_ID_FIELD) @@ -45,6 +40,10 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultCachedGif() { + super(); + } + public static String getType() { return type; } @@ -119,54 +118,6 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(GIF_FILE_ID_FIELD, gifFileId); - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(GIF_FILE_ID_FIELD, gifFileId); - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedGif{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java index cd1f369a..635e1454 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,14 +18,15 @@ import java.io.IOException; public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" private static final String ID_FIELD = "id"; private static final String MPEG4_FILE_ID_FIELD = "mpeg4_file_id"; private static final String TITLE_FIELD = "title"; private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(MPEG4_FILE_ID_FIELD) @@ -45,6 +40,10 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultCachedMpeg4Gif() { + super(); + } + public static String getType() { return type; } @@ -119,55 +118,6 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(MPEG4_FILE_ID_FIELD, mpeg4FileId); - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(MPEG4_FILE_ID_FIELD, mpeg4FileId); - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedMpeg4Gif{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java similarity index 68% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java index 14f10bb5..388e1cd5 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,8 +18,6 @@ import java.io.IOException; public class InlineQueryResultCachedPhoto implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "photo"; ///< Type of the result, must be “photo” private static final String ID_FIELD = "id"; private static final String PHOTOFILEID_FIELD = "photo_file_id"; private static final String TITLE_FIELD = "title"; @@ -33,6 +25,9 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "photo"; ///< Type of the result, must be “photo” @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(PHOTOFILEID_FIELD) @@ -48,6 +43,10 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultCachedPhoto() { + super(); + } + public static String getType() { return type; } @@ -131,66 +130,6 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(PHOTOFILEID_FIELD, photoFileId); - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - - return jsonObject; - } - - /* - reply_markup InlineKeyboardMarkup Optional. Inline keyboard attached to the message -input_message_content InputMessageContent Optional. Content of the message to be sent instead of the photo - */ - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(PHOTOFILEID_FIELD, photoFileId); - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, this.description); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, this.caption); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedPhoto{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java index 624711a4..f23a9400 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -26,12 +20,13 @@ import java.io.IOException; public class InlineQueryResultCachedSticker implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "sticker"; ///< Type of the result, must be "sticker" private static final String ID_FIELD = "id"; private static final String STICKER_FILE_ID_FIELD = "sticker_file_id"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "sticker"; ///< Type of the result, must be "sticker" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(STICKER_FILE_ID_FIELD) @@ -41,6 +36,10 @@ public class InlineQueryResultCachedSticker implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultCachedSticker() { + super(); + } + public static String getType() { return type; } @@ -97,42 +96,6 @@ public class InlineQueryResultCachedSticker implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(STICKER_FILE_ID_FIELD, stickerFileId); - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(STICKER_FILE_ID_FIELD, stickerFileId); - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedSticker{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java index 05417b7d..7cb46bff 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -24,8 +18,6 @@ import java.io.IOException; public class InlineQueryResultCachedVideo implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "video"; ///< Type of the result, must be "video" private static final String ID_FIELD = "id"; private static final String VIDEO_FILE_ID_FIELD = "video_file_id"; private static final String TITLE_FIELD = "title"; @@ -33,6 +25,9 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { private static final String CAPTION_FIELD = "caption"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "video"; ///< Type of the result, must be "video" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result @JsonProperty(VIDEO_FILE_ID_FIELD) @@ -48,6 +43,10 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message + public InlineQueryResultCachedVideo() { + super(); + } + public static String getType() { return type; } @@ -131,60 +130,6 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(VIDEO_FILE_ID_FIELD, videoFileId); - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (description != null) { - jsonObject.put(DESCRIPTION_FIELD, this.description); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(VIDEO_FILE_ID_FIELD, videoFileId); - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (description != null) { - gen.writeStringField(DESCRIPTION_FIELD, this.description); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedVideo{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java similarity index 71% rename from src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java index 0c263fde..700f8f3b 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java @@ -1,18 +1,12 @@ package org.telegram.telegrambots.api.objects.inlinequery.result.chached; 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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -26,14 +20,15 @@ import java.io.IOException; public class InlineQueryResultCachedVoice implements InlineQueryResult { private static final String TYPE_FIELD = "type"; - @JsonProperty(TYPE_FIELD) - private static final String type = "voice"; ///< Type of the result, must be "voice" private static final String ID_FIELD = "id"; private static final String VOICE_FILE_ID_FIELD = "voice_file_id"; private static final String TITLE_FIELD = "title"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; + + @JsonProperty(TYPE_FIELD) + private static final String type = "voice"; ///< Type of the result, must be "voice" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(VOICE_FILE_ID_FIELD) @@ -47,6 +42,10 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Voice caption (may also be used when resending documents by file_id), 0-200 characters + public InlineQueryResultCachedVoice() { + super(); + } + public static String getType() { return type; } @@ -121,54 +120,6 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TYPE_FIELD, type); - jsonObject.put(ID_FIELD, this.id); - jsonObject.put(VOICE_FILE_ID_FIELD, voiceFileId); - if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); - } - if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); - } - if (inputMessageContent != null) { - jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - jsonObject.put(CAPTION_FIELD, caption); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TYPE_FIELD, type); - gen.writeStringField(ID_FIELD, id); - gen.writeStringField(VOICE_FILE_ID_FIELD, voiceFileId); - if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); - } - if (replyMarkup != null) { - gen.writeObjectField(REPLY_MARKUP_FIELD, replyMarkup); - } - if (inputMessageContent != null) { - gen.writeObjectField(INPUTMESSAGECONTENT_FIELD, inputMessageContent); - } - if (caption != null) { - gen.writeStringField(CAPTION_FIELD, caption); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineQueryResultCachedVoice{" + diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ApiResponse.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ApiResponse.java new file mode 100644 index 00000000..13ab9471 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ApiResponse.java @@ -0,0 +1,73 @@ +package org.telegram.telegrambots.api.objects.replykeyboard; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.telegram.telegrambots.api.objects.ResponseParameters; + +import java.io.Serializable; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 06 of November of 2016 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ApiResponse implements Serializable { + private static final String OK_FIELD = "ok"; + private static final String ERROR_CODE_FIELD = "error_code"; + private static final String DESCRIPTION_CODE_FIELD = "description"; + private static final String PARAMETERS_FIELD = "parameters"; + private static final String RESULT_FIELD = "result"; + + @JsonProperty(OK_FIELD) + private Boolean ok; + @JsonProperty(ERROR_CODE_FIELD) + private Integer errorCode; + @JsonProperty(DESCRIPTION_CODE_FIELD) + private String errorDescription; + @JsonProperty(PARAMETERS_FIELD) + private ResponseParameters parameters; + @JsonProperty(RESULT_FIELD) + private T result; + + public Boolean getOk() { + return ok; + } + + public Integer getErrorCode() { + return errorCode; + } + + public String getErrorDescription() { + return errorDescription; + } + + public T getResult() { + return result; + } + + public ResponseParameters getParameters() { + return parameters; + } + + @Override + public String toString() { + if (ok) { + return "ApiResponse{" + + "ok=" + ok + + ", result=" + result + + '}'; + } else { + return "ApiResponse{" + + "ok=" + ok + + ", errorCode=" + errorCode + + ", errorDescription='" + errorDescription + '\'' + + ", parameters='" + parameters + '\'' + + '}'; + } + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java similarity index 60% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java index 42a7ffd2..d34b5543 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java @@ -1,15 +1,9 @@ package org.telegram.telegrambots.api.objects.replykeyboard; 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.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,6 +16,7 @@ import java.io.IOException; public class ForceReplyKeyboard implements ReplyKeyboard { private static final String FORCEREPLY_FIELD = "force_reply"; private static final String SELECTIVE_FIELD = "selective"; + /** * Shows reply interface to the user, as if they manually selected the bot‘s message and tapped * ’Reply' @@ -41,16 +36,6 @@ public class ForceReplyKeyboard implements ReplyKeyboard { this.forceReply = true; } - public ForceReplyKeyboard(JSONObject jsonObject) { - super(); - if (jsonObject.has(FORCEREPLY_FIELD)) { - this.forceReply = jsonObject.getBoolean(FORCEREPLY_FIELD); - } - if (jsonObject.has(SELECTIVE_FIELD)) { - this.selective = jsonObject.getBoolean(SELECTIVE_FIELD); - } - } - public Boolean getForceReply() { return forceReply; } @@ -71,32 +56,6 @@ public class ForceReplyKeyboard implements ReplyKeyboard { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put(FORCEREPLY_FIELD, this.forceReply); - if (this.selective != null) { - jsonObject.put(SELECTIVE_FIELD, this.selective); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeBooleanField(FORCEREPLY_FIELD, forceReply); - gen.writeBooleanField(SELECTIVE_FIELD, selective); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "ForceReplyKeyboard{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/InlineKeyboardMarkup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/InlineKeyboardMarkup.java similarity index 55% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/InlineKeyboardMarkup.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/InlineKeyboardMarkup.java index 13712817..b3ae10bc 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/InlineKeyboardMarkup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/InlineKeyboardMarkup.java @@ -1,16 +1,10 @@ package org.telegram.telegrambots.api.objects.replykeyboard; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; -import org.json.JSONArray; -import org.json.JSONObject; import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -26,6 +20,7 @@ import java.util.List; public class InlineKeyboardMarkup implements ReplyKeyboard { private static final String KEYBOARD_FIELD = "inline_keyboard"; + @JsonProperty(KEYBOARD_FIELD) private List> keyboard; ///< Array of button rows, each represented by an Array of Strings @@ -55,44 +50,6 @@ public class InlineKeyboardMarkup implements ReplyKeyboard { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - JSONArray jsonkeyboard = new JSONArray(); - - for (List innerRow : this.keyboard) { - JSONArray innerJSONKeyboard = new JSONArray(); - for (InlineKeyboardButton element : innerRow) { - innerJSONKeyboard.put(element.toJson()); - } - jsonkeyboard.put(innerJSONKeyboard); - } - jsonObject.put(InlineKeyboardMarkup.KEYBOARD_FIELD, jsonkeyboard); - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeArrayFieldStart(KEYBOARD_FIELD); - for (List innerRow : keyboard) { - gen.writeStartArray(); - for (InlineKeyboardButton element : innerRow) { - gen.writeObject(element); - } - gen.writeEndArray(); - } - gen.writeEndArray(); - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineKeyboardMarkup{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboard.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboard.java similarity index 55% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboard.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboard.java index aa2d01c3..fba02c4a 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboard.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboard.java @@ -1,7 +1,6 @@ package org.telegram.telegrambots.api.objects.replykeyboard; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; -import org.telegram.telegrambots.api.interfaces.IToJson; +import org.telegram.telegrambots.api.interfaces.InputBotApiObject; import org.telegram.telegrambots.api.interfaces.Validable; /** @@ -10,5 +9,5 @@ import org.telegram.telegrambots.api.interfaces.Validable; * @brief Reply keyboard abstract type * @date 20 of June of 2015 */ -public interface ReplyKeyboard extends IBotApiObject, IToJson, Validable { +public interface ReplyKeyboard extends InputBotApiObject, Validable { } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java similarity index 59% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java index 04a9e7df..2de1247d 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java @@ -1,15 +1,9 @@ package org.telegram.telegrambots.api.objects.replykeyboard; 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.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,6 +16,7 @@ import java.io.IOException; public class ReplyKeyboardHide implements ReplyKeyboard { private static final String HIDEKEYBOARD_FIELD = "hide_keyboard"; private static final String SELECTIVE_FIELD = "selective"; + @JsonProperty(HIDEKEYBOARD_FIELD) private Boolean hideKeyboard; ///< Requests clients to hide the custom keyboard /** @@ -37,16 +32,6 @@ public class ReplyKeyboardHide implements ReplyKeyboard { this.hideKeyboard = true; } - public ReplyKeyboardHide(JSONObject jsonObject) { - super(); - if (jsonObject.has(HIDEKEYBOARD_FIELD)) { - this.hideKeyboard = jsonObject.getBoolean(HIDEKEYBOARD_FIELD); - } - if (jsonObject.has(SELECTIVE_FIELD)) { - this.selective = jsonObject.getBoolean(SELECTIVE_FIELD); - } - } - public Boolean getHideKeyboard() { return hideKeyboard; } @@ -67,32 +52,6 @@ public class ReplyKeyboardHide implements ReplyKeyboard { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(HIDEKEYBOARD_FIELD, this.hideKeyboard); - if (selective != null) { - jsonObject.put(SELECTIVE_FIELD, this.selective); - } - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeBooleanField(HIDEKEYBOARD_FIELD, hideKeyboard); - if (selective != null) { - gen.writeBooleanField(SELECTIVE_FIELD, selective); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "ReplyKeyboardHide{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardMarkup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardMarkup.java similarity index 58% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardMarkup.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardMarkup.java index 1fa59062..7484323a 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardMarkup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardMarkup.java @@ -1,17 +1,10 @@ package org.telegram.telegrambots.api.objects.replykeyboard; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.jsontype.TypeSerializer; -import org.json.JSONArray; -import org.json.JSONObject; -import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardButton; import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -27,19 +20,20 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard { private static final String RESIZEKEYBOARD_FIELD = "resize_keyboard"; private static final String ONETIMEKEYBOARD_FIELD = "one_time_keyboard"; private static final String SELECTIVE_FIELD = "selective"; + @JsonProperty(KEYBOARD_FIELD) private List keyboard; ///< Array of button rows, each represented by an Array of Strings @JsonProperty(RESIZEKEYBOARD_FIELD) private Boolean resizeKeyboard; ///< Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false. @JsonProperty(ONETIMEKEYBOARD_FIELD) private Boolean oneTimeKeyboad; ///< Optional. Requests clients to hide the keyboard as soon as it's been used. Defaults to false. - @JsonProperty(SELECTIVE_FIELD) /** * Optional. Use this parameter if you want to show the keyboard to specific users only. * Targets: * 1) users that are @mentioned in the text of the Message object; * 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. */ + @JsonProperty(SELECTIVE_FIELD) private Boolean selective; public ReplyKeyboardMarkup() { @@ -93,63 +87,6 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - JSONArray jsonkeyboard = new JSONArray(); - - for (KeyboardRow innerRow : this.keyboard) { - JSONArray innerJSONKeyboard = new JSONArray(); - for (KeyboardButton button : innerRow) { - innerJSONKeyboard.put(button.toJson()); - } - jsonkeyboard.put(innerJSONKeyboard); - } - jsonObject.put(ReplyKeyboardMarkup.KEYBOARD_FIELD, jsonkeyboard); - - if (this.oneTimeKeyboad != null) { - jsonObject.put(ReplyKeyboardMarkup.ONETIMEKEYBOARD_FIELD, this.oneTimeKeyboad); - } - if (this.resizeKeyboard != null) { - jsonObject.put(ReplyKeyboardMarkup.RESIZEKEYBOARD_FIELD, this.resizeKeyboard); - } - if (this.selective != null) { - jsonObject.put(ReplyKeyboardMarkup.SELECTIVE_FIELD, this.selective); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeArrayFieldStart(KEYBOARD_FIELD); - for (KeyboardRow innerRow : keyboard) { - gen.writeStartArray(); - for (KeyboardButton button : innerRow) { - gen.writeObject(button); - } - gen.writeEndArray(); - } - gen.writeEndArray(); - if (this.oneTimeKeyboad != null) { - gen.writeBooleanField(ONETIMEKEYBOARD_FIELD, oneTimeKeyboad); - } - if (this.resizeKeyboard != null) { - gen.writeBooleanField(RESIZEKEYBOARD_FIELD, resizeKeyboard); - } - if (this.selective != null) { - gen.writeBooleanField(SELECTIVE_FIELD, selective); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "ReplyKeyboardMarkup{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/InlineKeyboardButton.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/InlineKeyboardButton.java similarity index 61% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/InlineKeyboardButton.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/InlineKeyboardButton.java index 0931cc35..093b7449 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/InlineKeyboardButton.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/InlineKeyboardButton.java @@ -1,19 +1,12 @@ package org.telegram.telegrambots.api.objects.replykeyboard.buttons; 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 org.telegram.telegrambots.api.interfaces.IToJson; +import org.telegram.telegrambots.api.interfaces.InputBotApiObject; import org.telegram.telegrambots.api.interfaces.Validable; import org.telegram.telegrambots.api.objects.games.CallbackGame; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -23,7 +16,7 @@ import java.io.IOException; * display unsupported message. * @date 10 of April of 2016 */ -public class InlineKeyboardButton implements IBotApiObject, IToJson, Validable { +public class InlineKeyboardButton implements InputBotApiObject, Validable { private static final String TEXT_FIELD = "text"; private static final String URL_FIELD = "url"; @@ -31,20 +24,20 @@ public class InlineKeyboardButton implements IBotApiObject, IToJson, Validable { private static final String CALLBACK_GAME_FIELD = "callback_game"; private static final String SWITCH_INLINE_QUERY_FIELD = "switch_inline_query"; private static final String SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD = "switch_inline_query_current_chat"; + @JsonProperty(TEXT_FIELD) private String text; ///< Label text on the button @JsonProperty(URL_FIELD) private String url; ///< Optional. HTTP url to be opened when button is pressed @JsonProperty(CALLBACK_DATA_FIELD) private String callbackData; ///< Optional. Data to be sent in a callback query to the bot when button is pressed - @JsonProperty(CALLBACK_GAME_FIELD) /** * Optional. Description of the game that will be launched when the user presses the button. * * @note This type of button must always be the first button in the first row. */ + @JsonProperty(CALLBACK_GAME_FIELD) private CallbackGame callbackGame; - @JsonProperty(SWITCH_INLINE_QUERY_FIELD) /** * Optional. * If set, pressing the button will prompt the user to select one of their chats, @@ -55,39 +48,20 @@ public class InlineKeyboardButton implements IBotApiObject, IToJson, Validable { * Especially useful when combined with switch_pm… actions – in this case the user will * be automatically returned to the chat they switched from, skipping the chat selection screen. */ + @JsonProperty(SWITCH_INLINE_QUERY_FIELD) private String switchInlineQuery; - @JsonProperty(SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD) /** * Optional. If set, pressing the button will insert the bot‘s username and the specified * inline query in the current chat's input field. Can be empty, * in which case only the bot’s username will be inserted. */ + @JsonProperty(SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD) private String switchInlineQueryCurrentChat; public InlineKeyboardButton() { super(); } - public InlineKeyboardButton(JSONObject jsonObject) { - super(); - text = jsonObject.getString(TEXT_FIELD); - if (jsonObject.has(URL_FIELD)) { - url = jsonObject.getString(URL_FIELD); - } - if (jsonObject.has(CALLBACK_DATA_FIELD)) { - callbackData = jsonObject.getString(CALLBACK_DATA_FIELD); - } - if (jsonObject.has(CALLBACK_GAME_FIELD)) { - callbackGame = new CallbackGame(jsonObject.getJSONObject(CALLBACK_GAME_FIELD)); - } - if (jsonObject.has(SWITCH_INLINE_QUERY_FIELD)) { - switchInlineQuery = jsonObject.getString(SWITCH_INLINE_QUERY_FIELD); - } - if (jsonObject.has(SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD)) { - switchInlineQueryCurrentChat = jsonObject.getString(SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD); - } - } - public String getText() { return text; } @@ -149,57 +123,6 @@ public class InlineKeyboardButton implements IBotApiObject, IToJson, Validable { } } - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TEXT_FIELD, text); - if (url != null) { - jsonObject.put(URL_FIELD, url); - } - if (callbackData != null) { - jsonObject.put(CALLBACK_DATA_FIELD, callbackData); - } - if (switchInlineQuery != null) { - jsonObject.put(SWITCH_INLINE_QUERY_FIELD, switchInlineQuery); - } - if (switchInlineQueryCurrentChat != null) { - jsonObject.put(SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD, switchInlineQueryCurrentChat); - } - if (callbackGame != null) { - jsonObject.put(CALLBACK_GAME_FIELD, callbackGame); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TEXT_FIELD, text); - if (url != null) { - gen.writeStringField(URL_FIELD, url); - } - if (callbackData != null) { - gen.writeStringField(CALLBACK_DATA_FIELD, callbackData); - } - if (switchInlineQuery != null) { - gen.writeStringField(SWITCH_INLINE_QUERY_FIELD, switchInlineQuery); - } - if (switchInlineQueryCurrentChat != null) { - gen.writeStringField(SWITCH_INLINE_QUERY_CURRENT_CHAT_FIELD, switchInlineQueryCurrentChat); - } - if (callbackGame != null) { - gen.writeObjectField(CALLBACK_GAME_FIELD, callbackGame); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); - } - @Override public String toString() { return "InlineKeyboardButton{" + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardButton.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardButton.java similarity index 60% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardButton.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardButton.java index 644677a2..db313c59 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardButton.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardButton.java @@ -1,18 +1,11 @@ package org.telegram.telegrambots.api.objects.replykeyboard.buttons; 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 org.telegram.telegrambots.api.interfaces.IToJson; +import org.telegram.telegrambots.api.interfaces.InputBotApiObject; import org.telegram.telegrambots.api.interfaces.Validable; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; -import java.io.IOException; - /** * @author Ruben Bermudez * @version 1.0 @@ -23,30 +16,30 @@ import java.io.IOException; * after 9 April, 2016. Older clients will ignore them. * @date 10 of April of 2016 */ -public class KeyboardButton implements IBotApiObject, IToJson, Validable { +public class KeyboardButton implements InputBotApiObject, Validable { private static final String TEXT_FIELD = "text"; private static final String REQUEST_CONTACT_FIELD = "request_contact"; private static final String REQUEST_LOCATION_FIELD = "request_location"; - @JsonProperty(TEXT_FIELD) /** * Text of the button. * If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed */ + @JsonProperty(TEXT_FIELD) private String text; - @JsonProperty(REQUEST_CONTACT_FIELD) /** * Optional. * If True, the user's phone number will be sent as a contact when the button is pressed. * Available in private chats only */ + @JsonProperty(REQUEST_CONTACT_FIELD) private Boolean requestContact; - @JsonProperty(REQUEST_LOCATION_FIELD) /** * Optional. * If True, the user's current location will be sent when the button is pressed. * Available in private chats only */ + @JsonProperty(REQUEST_LOCATION_FIELD) private Boolean requestLocation; public KeyboardButton() { @@ -58,17 +51,6 @@ public class KeyboardButton implements IBotApiObject, IToJson, Validable { this.text = text; } - public KeyboardButton(JSONObject jsonObject) { - super(); - text = jsonObject.getString(TEXT_FIELD); - if (jsonObject.has(REQUEST_CONTACT_FIELD)) { - requestContact = jsonObject.getBoolean(REQUEST_CONTACT_FIELD); - } - if (jsonObject.has(REQUEST_LOCATION_FIELD)) { - requestLocation = jsonObject.getBoolean(REQUEST_LOCATION_FIELD); - } - } - public String getText() { return text; } @@ -101,39 +83,9 @@ public class KeyboardButton implements IBotApiObject, IToJson, Validable { if (text == null || text.isEmpty()) { throw new TelegramApiValidationException("Text parameter can't be empty", this); } - } - - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(TEXT_FIELD, text); - if (requestContact != null) { - jsonObject.put(REQUEST_CONTACT_FIELD, requestContact); + if (requestContact != null && requestLocation != null && requestContact && requestLocation) { + throw new TelegramApiValidationException("Cant request contact and location at the same time", this); } - if (requestLocation != null) { - jsonObject.put(REQUEST_LOCATION_FIELD, requestLocation); - } - - return jsonObject; - } - - @Override - public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeStringField(TEXT_FIELD, text); - if (requestContact != null) { - gen.writeBooleanField(REQUEST_CONTACT_FIELD, requestContact); - } - if (requestLocation != null) { - gen.writeBooleanField(REQUEST_LOCATION_FIELD, requestLocation); - } - gen.writeEndObject(); - gen.flush(); - } - - @Override - public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - serialize(gen, serializers); } @Override diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardRow.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardRow.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardRow.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/buttons/KeyboardRow.java diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/bots/AbsSender.java new file mode 100644 index 00000000..cba8c75a --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -0,0 +1,546 @@ +package org.telegram.telegrambots.bots; + +import org.telegram.telegrambots.api.methods.AnswerCallbackQuery; +import org.telegram.telegrambots.api.methods.AnswerInlineQuery; +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.methods.ForwardMessage; +import org.telegram.telegrambots.api.methods.GetFile; +import org.telegram.telegrambots.api.methods.GetMe; +import org.telegram.telegrambots.api.methods.GetUserProfilePhotos; +import org.telegram.telegrambots.api.methods.games.GetGameHighScores; +import org.telegram.telegrambots.api.methods.games.SetGameScore; +import org.telegram.telegrambots.api.methods.groupadministration.GetChat; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatAdministrators; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatMember; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatMemberCount; +import org.telegram.telegrambots.api.methods.groupadministration.KickChatMember; +import org.telegram.telegrambots.api.methods.groupadministration.LeaveChat; +import org.telegram.telegrambots.api.methods.groupadministration.UnbanChatMember; +import org.telegram.telegrambots.api.methods.send.SendAudio; +import org.telegram.telegrambots.api.methods.send.SendChatAction; +import org.telegram.telegrambots.api.methods.send.SendContact; +import org.telegram.telegrambots.api.methods.send.SendDocument; +import org.telegram.telegrambots.api.methods.send.SendGame; +import org.telegram.telegrambots.api.methods.send.SendLocation; +import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.api.methods.send.SendPhoto; +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; +import org.telegram.telegrambots.api.objects.Chat; +import org.telegram.telegrambots.api.objects.ChatMember; +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.api.objects.games.GameHighScore; +import org.telegram.telegrambots.exceptions.TelegramApiException; +import org.telegram.telegrambots.updateshandlers.SentCallback; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + */ +@SuppressWarnings("unused") +public abstract class AbsSender { + protected AbsSender() { + } + + // Send Requests + + public final Message sendMessage(SendMessage sendMessage) throws TelegramApiException { + if (sendMessage == null) { + throw new TelegramApiException("Parameter sendMessage can not be null"); + } + + return sendApiMethod(sendMessage); + } + + public final Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { + if (answerInlineQuery == null) { + throw new TelegramApiException("Parameter answerInlineQuery can not be null"); + } + + return sendApiMethod(answerInlineQuery); + } + + public final Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { + if (sendChatAction == null) { + throw new TelegramApiException("Parameter sendChatAction can not be null"); + } + + return sendApiMethod(sendChatAction); + } + + public final Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { + if (forwardMessage == null) { + throw new TelegramApiException("Parameter forwardMessage can not be null"); + } + + return sendApiMethod(forwardMessage); + } + + public final Message sendLocation(SendLocation sendLocation) throws TelegramApiException { + if (sendLocation == null) { + throw new TelegramApiException("Parameter sendLocation can not be null"); + } + + return sendApiMethod(sendLocation); + } + + public final Message sendVenue(SendVenue sendVenue) throws TelegramApiException { + if (sendVenue == null) { + throw new TelegramApiException("Parameter sendVenue can not be null"); + } + + return sendApiMethod(sendVenue); + } + + public final Message sendContact(SendContact sendContact) throws TelegramApiException { + if (sendContact == null) { + throw new TelegramApiException("Parameter sendContact can not be null"); + } + + return sendApiMethod(sendContact); + } + + public final Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { + if (kickChatMember == null) { + throw new TelegramApiException("Parameter kickChatMember can not be null"); + } + return sendApiMethod(kickChatMember); + } + + public final Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { + if (unbanChatMember == null) { + throw new TelegramApiException("Parameter unbanChatMember can not be null"); + } + return sendApiMethod(unbanChatMember); + } + + public final Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { + if (leaveChat == null) { + throw new TelegramApiException("Parameter leaveChat can not be null"); + } + return sendApiMethod(leaveChat); + } + + public final Chat getChat(GetChat getChat) throws TelegramApiException { + if (getChat == null) { + throw new TelegramApiException("Parameter getChat can not be null"); + } + return sendApiMethod(getChat); + } + + public final List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { + if (getChatAdministrators == null) { + throw new TelegramApiException("Parameter getChatAdministrators can not be null"); + } + return sendApiMethod(getChatAdministrators); + } + + public final ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { + if (getChatMember == null) { + throw new TelegramApiException("Parameter getChatMember can not be null"); + } + return sendApiMethod(getChatMember); + } + + public final Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { + if (getChatMemberCount == null) { + throw new TelegramApiException("Parameter getChatMemberCount can not be null"); + } + return sendApiMethod(getChatMemberCount); + } + + public final Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { + if (editMessageText == null) { + throw new TelegramApiException("Parameter editMessageText can not be null"); + } + return sendApiMethod(editMessageText); + } + + public final Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { + if (editMessageCaption == null) { + throw new TelegramApiException("Parameter editMessageCaption can not be null"); + } + return sendApiMethod(editMessageCaption); + } + + public final Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { + if (editMessageReplyMarkup == null) { + throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); + } + return sendApiMethod(editMessageReplyMarkup); + } + + public final Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { + if (answerCallbackQuery == null) { + throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); + } + return sendApiMethod(answerCallbackQuery); + } + + public final UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { + if (getUserProfilePhotos == null) { + throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); + } + + return sendApiMethod(getUserProfilePhotos); + } + + 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 sendApiMethod(getFile); + } + + public final User getMe() throws TelegramApiException { + GetMe getMe = new GetMe(); + + return sendApiMethod(getMe); + } + + public final WebhookInfo getWebhookInfo() throws TelegramApiException { + GetWebhookInfo getWebhookInfo = new GetWebhookInfo(); + return sendApiMethod(getWebhookInfo); + } + + public final Serializable setGameScore(SetGameScore setGameScore) throws TelegramApiException { + if(setGameScore == null){ + throw new TelegramApiException("Parameter setGameScore can not be null"); + } + return sendApiMethod(setGameScore); + } + + public final Serializable getGameHighScores(GetGameHighScores getGameHighScores) throws TelegramApiException { + if(getGameHighScores == null){ + throw new TelegramApiException("Parameter getGameHighScores can not be null"); + } + return sendApiMethod(getGameHighScores); + } + + public final Message sendGame(SendGame sendGame) throws TelegramApiException { + if(sendGame == null){ + throw new TelegramApiException("Parameter sendGame can not be null"); + } + return sendApiMethod(sendGame); + } + + // Send Requests Async + + public final void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { + if (sendMessage == null) { + throw new TelegramApiException("Parameter sendMessage can not be null"); + } + + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(sendMessage, sentCallback); + } + + public final void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback sentCallback) throws TelegramApiException { + if (answerInlineQuery == null) { + throw new TelegramApiException("Parameter answerInlineQuery can not be null"); + } + + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(answerInlineQuery, sentCallback); + } + + public final void sendChatActionAsync(SendChatAction sendChatAction, SentCallback sentCallback) throws TelegramApiException { + if (sendChatAction == null) { + throw new TelegramApiException("Parameter sendChatAction can not be null"); + } + + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(sendChatAction, sentCallback); + } + + public final void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback sentCallback) throws TelegramApiException { + if (forwardMessage == null) { + throw new TelegramApiException("Parameter forwardMessage can not be null"); + } + + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(forwardMessage, sentCallback); + } + + public final void sendLocationAsync(SendLocation sendLocation, SentCallback sentCallback) throws TelegramApiException { + if (sendLocation == null) { + throw new TelegramApiException("Parameter sendLocation can not be null"); + } + + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(sendLocation, sentCallback); + } + + public final void sendVenueAsync(SendVenue sendVenue, SentCallback sentCallback) throws TelegramApiException { + if (sendVenue == null) { + throw new TelegramApiException("Parameter sendVenue can not be null"); + } + + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(sendVenue, sentCallback); + } + + public final void sendContactAsync(SendContact sendContact, SentCallback sentCallback) throws TelegramApiException { + if (sendContact == null) { + throw new TelegramApiException("Parameter sendContact can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(sendContact, sentCallback); + } + + public final void kickMemberAsync(KickChatMember kickChatMember, SentCallback sentCallback) throws TelegramApiException { + if (kickChatMember == null) { + throw new TelegramApiException("Parameter kickChatMember can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(kickChatMember, sentCallback); + } + + public final void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback sentCallback) throws TelegramApiException { + if (unbanChatMember == null) { + throw new TelegramApiException("Parameter unbanChatMember can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(unbanChatMember, sentCallback); + } + + public final void leaveChatAsync(LeaveChat leaveChat, SentCallback sentCallback) throws TelegramApiException { + if (leaveChat == null) { + throw new TelegramApiException("Parameter leaveChat can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(leaveChat, sentCallback); + } + + public final void getChatAsync(GetChat getChat, SentCallback sentCallback) throws TelegramApiException { + if (getChat == null) { + throw new TelegramApiException("Parameter getChat can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(getChat, sentCallback); + } + + public final void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback> sentCallback) throws TelegramApiException { + if (getChatAdministrators == null) { + throw new TelegramApiException("Parameter getChatAdministrators can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(getChatAdministrators, sentCallback); + } + + public final void getChatMemberAsync(GetChatMember getChatMember, SentCallback sentCallback) throws TelegramApiException { + if (getChatMember == null) { + throw new TelegramApiException("Parameter getChatMember can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(getChatMember, sentCallback); + } + + public final void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback sentCallback) throws TelegramApiException { + if (getChatMemberCount == null) { + throw new TelegramApiException("Parameter getChatMemberCount can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(getChatMemberCount, sentCallback); + } + + public final void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { + if (editMessageText == null) { + throw new TelegramApiException("Parameter editMessageText can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(editMessageText, sentCallback); + } + + public final void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback sentCallback) throws TelegramApiException { + if (editMessageCaption == null) { + throw new TelegramApiException("Parameter editMessageCaption can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(editMessageCaption, sentCallback); + } + + public final void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback sentCallback) throws TelegramApiException { + if (editMessageReplyMarkup == null) { + throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(editMessageReplyMarkup, sentCallback); + } + + public final void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback sentCallback) throws TelegramApiException { + if (answerCallbackQuery == null) { + throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(answerCallbackQuery, sentCallback); + } + + public final void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback sentCallback) throws TelegramApiException { + if (getUserProfilePhotos == null) { + throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(getUserProfilePhotos, sentCallback); + } + + public final void getFileAsync(GetFile getFile, SentCallback sentCallback) throws TelegramApiException { + if (getFile == null) { + throw new TelegramApiException("Parameter getFile can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + sendApiMethodAsync(getFile, sentCallback); + } + + public final void getMeAsync(SentCallback sentCallback) throws TelegramApiException { + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + GetMe getMe = new GetMe(); + 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); + } + + public final void setGameScoreAsync(SetGameScore setGameScore, SentCallback sentCallback) throws TelegramApiException { + if (setGameScore == null) { + throw new TelegramApiException("Parameter setGameScore can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(setGameScore, sentCallback); + } + + public final void getGameHighScoresAsync(GetGameHighScores getGameHighScores, SentCallback> sentCallback) throws TelegramApiException { + if (getGameHighScores == null) { + throw new TelegramApiException("Parameter getGameHighScores can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(getGameHighScores, sentCallback); + } + + public final void sendGameAsync(SendGame sendGame, SentCallback sentCallback) throws TelegramApiException { + if (sendGame == null) { + throw new TelegramApiException("Parameter sendGame can not be null"); + } + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + sendApiMethodAsync(sendGame, sentCallback); + } + + // Specific Send Requests + public abstract Message sendDocument(SendDocument sendDocument) throws TelegramApiException; + + public abstract Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException; + + public abstract Message sendVideo(SendVideo sendVideo) throws TelegramApiException; + + public abstract Message sendSticker(SendSticker sendSticker) throws TelegramApiException; + + /** + * Sends a file using Send Audio method (https://core.telegram.org/bots/api#sendaudio) + * @param sendAudio Information to send + * @return If success, the sent Message is returned + * @throws TelegramApiException If there is any error sending the audio + */ + public abstract Message sendAudio(SendAudio sendAudio) throws TelegramApiException; + + /** + * 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 abstract Message sendVoice(SendVoice sendVoice) throws TelegramApiException; + + // Simplified methods + + protected abstract , Callback extends SentCallback> void sendApiMethodAsync(Method method, Callback callback); + + protected abstract > T sendApiMethod(Method method) throws TelegramApiException; +} diff --git a/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiException.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiException.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/exceptions/TelegramApiException.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiException.java diff --git a/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiRequestException.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiRequestException.java similarity index 75% rename from src/main/java/org/telegram/telegrambots/exceptions/TelegramApiRequestException.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiRequestException.java index 45d9ba12..6f40a135 100644 --- a/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiRequestException.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiRequestException.java @@ -17,8 +17,14 @@ package org.telegram.telegrambots.exceptions; +import com.fasterxml.jackson.databind.ObjectMapper; + import org.json.JSONObject; import org.telegram.telegrambots.api.objects.ResponseParameters; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; +import org.telegram.telegrambots.logging.BotLogger; + +import java.io.IOException; /** @@ -28,6 +34,7 @@ import org.telegram.telegrambots.api.objects.ResponseParameters; * @date 14 of January of 2016 */ public class TelegramApiRequestException extends TelegramApiException { + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String ERRORDESCRIPTIONFIELD = "description"; private static final String ERRORCODEFIELD = "error_code"; private static final String PARAMETERSFIELD = "parameters"; @@ -45,10 +52,21 @@ public class TelegramApiRequestException extends TelegramApiException { apiResponse = object.getString(ERRORDESCRIPTIONFIELD); errorCode = object.getInt(ERRORCODEFIELD); if (object.has(PARAMETERSFIELD)) { - parameters = new ResponseParameters(object.getJSONObject(PARAMETERSFIELD)); + try { + parameters = OBJECT_MAPPER.readValue(object.getJSONObject(PARAMETERSFIELD).toString(), ResponseParameters.class); + } catch (IOException e) { + BotLogger.severe("APIEXCEPTION", e); + } } } + public TelegramApiRequestException(String message, ApiResponse response) { + super(message); + apiResponse = response.getErrorDescription(); + errorCode = response.getErrorCode(); + parameters = response.getParameters(); + } + public TelegramApiRequestException(String message, Throwable cause) { super(message, cause); } diff --git a/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiValidationException.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiValidationException.java similarity index 72% rename from src/main/java/org/telegram/telegrambots/exceptions/TelegramApiValidationException.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiValidationException.java index 880ffae2..719d9cf8 100644 --- a/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiValidationException.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/exceptions/TelegramApiValidationException.java @@ -17,8 +17,8 @@ package org.telegram.telegrambots.exceptions; -import org.telegram.telegrambots.api.interfaces.IBotApiObject; -import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.api.methods.PartialBotApiMethod; /** * @author Ruben Bermudez @@ -27,19 +27,27 @@ import org.telegram.telegrambots.api.methods.BotApiMethod; * @date 16 of September of 2016 */ public class TelegramApiValidationException extends TelegramApiException { - private BotApiMethod method; - private IBotApiObject object; + private PartialBotApiMethod method; + private InputBotApiObject object; - public TelegramApiValidationException(String message, BotApiMethod method) { + public TelegramApiValidationException(String message, PartialBotApiMethod method) { super(message); this.method = method; } - public TelegramApiValidationException(String message, IBotApiObject object) { + public TelegramApiValidationException(String message, InputBotApiObject object) { super(message); this.object = object; } + public PartialBotApiMethod getMethod() { + return method; + } + + public InputBotApiObject getObject() { + return object; + } + @Override public String toString() { if (method != null) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/BotOptions.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/BotOptions.java new file mode 100644 index 00000000..3c77724c --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/BotOptions.java @@ -0,0 +1,10 @@ +package org.telegram.telegrambots.generics; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public interface BotOptions { +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/BotSession.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/BotSession.java new file mode 100644 index 00000000..c02a3e62 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/BotSession.java @@ -0,0 +1,16 @@ +package org.telegram.telegrambots.generics; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public interface BotSession { + void setOptions(BotOptions options); + void setToken(String token); + void setCallback(LongPollingBot callback); + void start(); + void close(); + boolean isRunning(); +} diff --git a/src/main/java/org/telegram/telegrambots/bots/ITelegramLongPollingBot.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/LongPollingBot.java similarity index 57% rename from src/main/java/org/telegram/telegrambots/bots/ITelegramLongPollingBot.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/LongPollingBot.java index 39894fda..ce9bda79 100644 --- a/src/main/java/org/telegram/telegrambots/bots/ITelegramLongPollingBot.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/LongPollingBot.java @@ -1,6 +1,7 @@ -package org.telegram.telegrambots.bots; +package org.telegram.telegrambots.generics; import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; /** * @author Ruben Bermudez @@ -8,7 +9,7 @@ import org.telegram.telegrambots.api.objects.Update; * @brief Callback to handle updates. * @date 20 of June of 2015 */ -public interface ITelegramLongPollingBot { +public interface LongPollingBot { /** * This method is called when receiving updates via GetUpdates method * @param update Update received @@ -25,6 +26,17 @@ public interface ITelegramLongPollingBot { */ String getBotToken(); + /** + * Gets options for current bot + * @return BotOptions object with options information + */ + BotOptions getOptions(); + + /** + * Clear current webhook (if present) calling setWebhook method with empty url. + */ + void clearWebhook() throws TelegramApiRequestException; + /** * Called when the BotSession is being closed */ diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/UpdatesHandler.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/UpdatesHandler.java new file mode 100644 index 00000000..05da1e38 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/UpdatesHandler.java @@ -0,0 +1,10 @@ +package org.telegram.telegrambots.generics; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public interface UpdatesHandler { +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/UpdatesReader.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/UpdatesReader.java new file mode 100644 index 00000000..36f90329 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/UpdatesReader.java @@ -0,0 +1,11 @@ +package org.telegram.telegrambots.generics; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public interface UpdatesReader { + void start(); +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/Webhook.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/Webhook.java new file mode 100644 index 00000000..004b6f11 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/Webhook.java @@ -0,0 +1,16 @@ +package org.telegram.telegrambots.generics; + +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public interface Webhook { + void startServer() throws TelegramApiRequestException; + void registerWebhook(WebhookBot callback); + void setInternalUrl(String internalUrl); + void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiRequestException; +} diff --git a/src/main/java/org/telegram/telegrambots/bots/ITelegramWebhookBot.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/WebhookBot.java similarity index 58% rename from src/main/java/org/telegram/telegrambots/bots/ITelegramWebhookBot.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/WebhookBot.java index 33987096..18043aa5 100644 --- a/src/main/java/org/telegram/telegrambots/bots/ITelegramWebhookBot.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/generics/WebhookBot.java @@ -1,7 +1,8 @@ -package org.telegram.telegrambots.bots; +package org.telegram.telegrambots.generics; import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; /** * @author Ruben Bermudez @@ -9,7 +10,7 @@ import org.telegram.telegrambots.api.objects.Update; * @brief Callback to handle updates. * @date 20 of June of 2015 */ -public interface ITelegramWebhookBot { +public interface WebhookBot { /** * This method is called when receiving updates via webhook * @param update Update received @@ -28,6 +29,14 @@ public interface ITelegramWebhookBot { */ String getBotToken(); + /** + * Execute setWebhook method to set up the url of the webhook + * @param url Url for the webhook + * @param publicCertificatePath Path to the public key certificate of the webhook + * @throws TelegramApiRequestException In case of error executing the request + */ + void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException; + /** * Gets in the url for the webhook * @return path in the url diff --git a/src/main/java/org/telegram/telegrambots/logging/BotLogger.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/logging/BotLogger.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/logging/BotLogger.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/logging/BotLogger.java diff --git a/src/main/java/org/telegram/telegrambots/logging/BotsFileHandler.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/logging/BotsFileHandler.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/logging/BotsFileHandler.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/logging/BotsFileHandler.java diff --git a/src/main/java/org/telegram/telegrambots/logging/FileFormatter.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/logging/FileFormatter.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/logging/FileFormatter.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/logging/FileFormatter.java diff --git a/src/main/java/org/telegram/telegrambots/updateshandlers/DownloadFileCallback.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/updateshandlers/DownloadFileCallback.java similarity index 57% rename from src/main/java/org/telegram/telegrambots/updateshandlers/DownloadFileCallback.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/updateshandlers/DownloadFileCallback.java index 70c2f155..2ba7e1aa 100644 --- a/src/main/java/org/telegram/telegrambots/updateshandlers/DownloadFileCallback.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/updateshandlers/DownloadFileCallback.java @@ -17,26 +17,12 @@ package org.telegram.telegrambots.updateshandlers; -import org.telegram.telegrambots.api.objects.File; - /** * @author Ruben Bermudez * @version 1.0 - * @brief Callback to execute api method asynchronously - * @date 10 of September of 2015 + * Callback to download files async */ -public interface DownloadFileCallback { - /** - * Called when the request is successful - * @param method Method executed - * @param jsonObject Answer from Telegram server - */ - void onResult(File file, java.io.File output); - - /** - * Called when the http request throw an exception - * @param method Method executed - * @param exception Excepction thrown - */ - void onException(File file, Exception exception); +public interface DownloadFileCallback { + void onResult(T file, java.io.File output); + void onException(T file, Exception exception); } diff --git a/src/main/java/org/telegram/telegrambots/updateshandlers/SentCallback.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/updateshandlers/SentCallback.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/updateshandlers/SentCallback.java rename to telegrambots-meta/src/main/java/org/telegram/telegrambots/updateshandlers/SentCallback.java diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/TelegramBotsHelper.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/TelegramBotsHelper.java new file mode 100644 index 00000000..07d3e3be --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/TelegramBotsHelper.java @@ -0,0 +1,32 @@ +package org.telegram.telegrambots; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 04 of November of 2016 + */ +public final class TelegramBotsHelper { + private TelegramBotsHelper() { + } + + public static String GetUpdate() { + return "{\"update_id\": 10000,\"message\": {\"date\": 1441645532,\"chat\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"type\": \"private\",\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"message_id\": 1365,\"from\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"forward_from\": {\"last_name\": \"ForwardLastname\",\"id\": 222222,\"first_name\": \"ForwardFirstname\"},\"forward_date\": 1441645550,\"reply_to_message\": {\"date\": 1441645000,\"chat\": {\"last_name\": \"ReplyLastname\",\"type\": \"private\",\"id\": 1111112,\"first_name\": \"ReplyFirstname\",\"username\": \"Testusername\"},\"message_id\": 1334,\"text\": \"Original\"},\"text\": \"Bold and italics\",\"entities\": [{\"type\": \"italic\",\"offset\": 9,\"length\": 7},{\"type\": \"bold\",\"offset\": 0,\"length\": 4}],\"audio\": {\"file_id\": \"AwADBAADbXXXXXXXXXXXGBdhD2l6_XX\",\"duration\": 243,\"mime_type\": \"audio/mpeg\",\"file_size\": 3897500,\"title\": \"Testmusicfile\"},\"voice\": {\"file_id\": \"AwADBAADbXXXXXXXXXXXGBdhD2l6_XX\",\"duration\": 5,\"mime_type\": \"audio/ogg\",\"file_size\": 23000},\"document\": {\"file_id\": \"AwADBAADbXXXXXXXXXXXGBdhD2l6_XX\",\"file_name\": \"Testfile.pdf\",\"mime_type\": \"application/pdf\",\"file_size\": 536392}},\"edited_message\": {\"date\": 1441645532,\"chat\": {\"id\": -10000000000,\"type\": \"channel\",\"title\": \"Test channel\"},\"message_id\": 1365,\"from\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"text\": \"Edited text\",\"edit_date\": 1441646600},\"inline_query\": {\"id\": \"134567890097\",\"from\": {\"last_name\": \"Test Lastname\",\"type\": \"private\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"query\": \"inline query\",\"offset\": \"offset\",\"location\": {\"longitude\": 0.234242534,\"latitude\": 0.234242534}},\"chosen_inline_result\": {\"result_id\": \"12\",\"from\": {\"last_name\": \"Test Lastname\",\"type\": \"private\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"query\": \"inline query\",\"inline_message_id\": \"1234csdbsk4839\"},\"callback_query\": {\"id\": \"4382bfdwdsb323b2d9\",\"from\": {\"last_name\": \"Test Lastname\",\"type\": \"private\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"data\": \"Data from button callback\",\"inline_message_id\": \"1234csdbsk4839\"}\n}"; + } + + public static String GetResponseWithoutError() { + return "{\"ok\": true,\"result\": [{\"update_id\": 10000,\"message\": {\"date\": 1441645532,\"chat\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"type\": \"private\",\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"message_id\": 1365,\"from\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"forward_from\": {\"last_name\": \"ForwardLastname\",\"id\": 222222,\"first_name\": \"ForwardFirstname\"},\"forward_date\": 1441645550,\"reply_to_message\": {\"date\": 1441645000,\"chat\": {\"last_name\": \"ReplyLastname\",\"type\": \"private\",\"id\": 1111112,\"first_name\": \"ReplyFirstname\",\"username\": \"Testusername\"},\"message_id\": 1334,\"text\": \"Original\"},\"text\": \"Bold and italics\",\"entities\": [{\"type\": \"italic\",\"offset\": 9,\"length\": 7},{\"type\": \"bold\",\"offset\": 0,\"length\": 4}],\"audio\": {\"file_id\": \"AwADBAADbXXXXXXXXXXXGBdhD2l6_XX\",\"duration\": 243,\"mime_type\": \"audio/mpeg\",\"file_size\": 3897500,\"title\": \"Testmusicfile\"},\"voice\": {\"file_id\": \"AwADBAADbXXXXXXXXXXXGBdhD2l6_XX\",\"duration\": 5,\"mime_type\": \"audio/ogg\",\"file_size\": 23000},\"document\": {\"file_id\": \"AwADBAADbXXXXXXXXXXXGBdhD2l6_XX\",\"file_name\": \"Testfile.pdf\",\"mime_type\": \"application/pdf\",\"file_size\": 536392}},\"edited_message\": {\"date\": 1441645532,\"chat\": {\"id\": -10000000000,\"type\": \"channel\",\"title\": \"Test channel\"},\"message_id\": 1365,\"from\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"text\": \"Edited text\",\"edit_date\": 1441646600},\"inline_query\": {\"id\": \"134567890097\",\"from\": {\"last_name\": \"Test Lastname\",\"type\": \"private\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"query\": \"inline query\",\"offset\": \"offset\",\"location\": {\"longitude\": 0.234242534,\"latitude\": 0.234242534}},\"chosen_inline_result\": {\"result_id\": \"12\",\"from\": {\"last_name\": \"Test Lastname\",\"type\": \"private\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"query\": \"inline query\",\"inline_message_id\": \"1234csdbsk4839\"},\"callback_query\": {\"id\": \"4382bfdwdsb323b2d9\",\"from\": {\"last_name\": \"Test Lastname\",\"type\": \"private\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"data\": \"Data from button callback\",\"inline_message_id\": \"1234csdbsk4839\"}}]\n}"; + } + + public static String GetResponseWithError() { + return "{\"ok\": false,\"error_code\": 400,\"description\": \"Error descriptions\",\"parameters\": {\"migrate_to_chat_id\": 12345,\"retry_after\": 12}}"; + } + + public static String GetSetGameScoreBooleanResponse() { + return "{\"ok\": true,\"result\": true}"; + } + + public static String GetSetGameScoreMessageResponse() { + return "{\"ok\": true,\"result\": {\"date\": 1441645532,\"chat\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"type\": \"private\",\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"message_id\": 1365,\"from\": {\"last_name\": \"Test Lastname\",\"id\": 1111111,\"first_name\": \"Test Firstname\",\"username\": \"Testusername\"},\"text\": \"Original\"}}"; + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/TestDeserialization.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/TestDeserialization.java new file mode 100644 index 00000000..3c21414c --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/TestDeserialization.java @@ -0,0 +1,210 @@ +package org.telegram.telegrambots; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.telegram.telegrambots.api.objects.Audio; +import org.telegram.telegrambots.api.objects.CallbackQuery; +import org.telegram.telegrambots.api.objects.Chat; +import org.telegram.telegrambots.api.objects.Document; +import org.telegram.telegrambots.api.objects.EntityType; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.MessageEntity; +import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.api.objects.User; +import org.telegram.telegrambots.api.objects.Voice; +import org.telegram.telegrambots.api.objects.inlinequery.ChosenInlineQuery; +import org.telegram.telegrambots.api.objects.inlinequery.InlineQuery; +import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 04 of November of 2016 + */ +public class TestDeserialization { + private ObjectMapper mapper; + + @Before + public void setUp() throws Exception { + mapper = new ObjectMapper(); + } + + @Test + public void TestUpdateDeserialization() throws Exception { + Update update = mapper.readValue(TelegramBotsHelper.GetUpdate(), Update.class); + assertUpdate(update); + } + + @Test + public void TestResponseWithoutErrorDeserialization() throws IOException { + ApiResponse> result = mapper.readValue(TelegramBotsHelper.GetResponseWithoutError(), new TypeReference>>(){}); + Assert.assertNotNull(result); + Assert.assertTrue(result.getOk()); + Assert.assertEquals(1, result.getResult().size()); + assertUpdate(result.getResult().get(0)); + } + + @Test + public void TestResponseWithErrorDeserialization() throws IOException { + ApiResponse> result = mapper.readValue(TelegramBotsHelper.GetResponseWithError(), new TypeReference>>(){}); + Assert.assertNotNull(result); + Assert.assertFalse(result.getOk()); + Assert.assertEquals(Integer.valueOf(400), result.getErrorCode()); + Assert.assertEquals("Error descriptions", result.getErrorDescription()); + Assert.assertNotNull(result.getParameters()); + Assert.assertEquals(Integer.valueOf(12345), result.getParameters().getMigrateToChatId()); + Assert.assertEquals(Integer.valueOf(12), result.getParameters().getRetryAfter()); + } + + private void assertUpdate(Update update) { + Assert.assertNotNull(update); + Assert.assertEquals((Integer) 10000, update.getUpdateId()); + assertEditedMessage(update.getEditedMessage()); + assertCallbackQuery(update.getCallbackQuery()); + assertInlineQuery(update.getInlineQuery()); + assertChosenInlineQuery(update.getChosenInlineQuery()); + assertMessage(update.getMessage()); + } + + private void assertMessage(Message message) { + Assert.assertNotNull(message); + Assert.assertEquals(Integer.valueOf(1441645532), message.getDate()); + Assert.assertEquals(Integer.valueOf(1365), message.getMessageId()); + Assert.assertEquals(Integer.valueOf(1441645550), message.getForwardDate()); + Assert.assertEquals("Bold and italics", message.getText()); + assertPrivateChat(message.getChat()); + assertFromUser(message.getFrom()); + assertForwardFrom(message.getForwardFrom()); + assertReplyToMessage(message.getReplyToMessage()); + assertEntities(message.getEntities()); + assertAudio(message.getAudio()); + assertVoice(message.getVoice()); + assertDocument(message.getDocument()); + } + + private void assertDocument(Document document) { + Assert.assertNotNull(document); + Assert.assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", document.getFileId()); + Assert.assertEquals("Testfile.pdf", document.getFileName()); + Assert.assertEquals("application/pdf", document.getMimeType()); + Assert.assertEquals(Integer.valueOf(536392), document.getFileSize()); + } + + private void assertVoice(Voice voice) { + Assert.assertNotNull(voice); + Assert.assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", voice.getFileId()); + Assert.assertEquals(Integer.valueOf(5), voice.getDuration()); + Assert.assertEquals("audio/ogg", voice.getMimeType()); + Assert.assertEquals(Integer.valueOf(23000), voice.getFileSize()); + } + + private void assertAudio(Audio audio) { + Assert.assertNotNull(audio); + Assert.assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", audio.getFileId()); + Assert.assertEquals(Integer.valueOf(243), audio.getDuration()); + Assert.assertEquals("audio/mpeg", audio.getMimeType()); + Assert.assertEquals(Integer.valueOf(3897500), audio.getFileSize()); + Assert.assertEquals("Testmusicfile", audio.getTitle()); + } + + private void assertEntities(List entities) { + Assert.assertNotNull(entities); + Assert.assertEquals(2, entities.size()); + Assert.assertEquals(EntityType.ITALIC, entities.get(0).getType()); + Assert.assertEquals(Integer.valueOf(9), entities.get(0).getOffset()); + Assert.assertEquals(Integer.valueOf(7), entities.get(0).getLength()); + Assert.assertEquals("italics", entities.get(0).getText()); + Assert.assertEquals(EntityType.BOLD, entities.get(1).getType()); + Assert.assertEquals(Integer.valueOf(0), entities.get(1).getOffset()); + Assert.assertEquals(Integer.valueOf(4), entities.get(1).getLength()); + Assert.assertEquals("Bold", entities.get(1).getText()); + } + + private void assertReplyToMessage(Message replyToMessage) { + Assert.assertNotNull(replyToMessage); + Assert.assertEquals(Integer.valueOf(1441645000), replyToMessage.getDate()); + Assert.assertEquals(Integer.valueOf(1334), replyToMessage.getMessageId()); + Assert.assertEquals("Original", replyToMessage.getText()); + Assert.assertNotNull(replyToMessage.getChat()); + Assert.assertEquals("ReplyLastname", replyToMessage.getChat().getLastName()); + Assert.assertEquals("ReplyFirstname", replyToMessage.getChat().getFirstName()); + Assert.assertEquals("Testusername", replyToMessage.getChat().getUserName()); + Assert.assertEquals(Long.valueOf(1111112), replyToMessage.getChat().getId()); + } + + private void assertForwardFrom(User forwardFrom) { + Assert.assertNotNull(forwardFrom); + Assert.assertEquals("ForwardLastname", forwardFrom.getLastName()); + Assert.assertEquals("ForwardFirstname", forwardFrom.getFirstName()); + Assert.assertEquals(Integer.valueOf(222222), forwardFrom.getId()); + } + + private void assertPrivateChat(Chat chat) { + Assert.assertNotNull(chat); + Assert.assertEquals(Long.valueOf(1111111), chat.getId()); + Assert.assertTrue(chat.isUserChat()); + Assert.assertEquals("Test Lastname", chat.getLastName()); + Assert.assertEquals("Test Firstname", chat.getFirstName()); + Assert.assertEquals("Testusername", chat.getUserName()); + } + + private void assertChosenInlineQuery(ChosenInlineQuery chosenInlineQuery) { + Assert.assertNotNull(chosenInlineQuery); + Assert.assertEquals("12", chosenInlineQuery.getResultId()); + Assert.assertEquals("inline query", chosenInlineQuery.getQuery()); + Assert.assertEquals("1234csdbsk4839", chosenInlineQuery.getInlineMessageId()); + assertFromUser(chosenInlineQuery.getFrom()); + } + + private void assertInlineQuery(InlineQuery inlineQuery) { + Assert.assertNotNull(inlineQuery); + Assert.assertEquals("134567890097", inlineQuery.getId()); + Assert.assertEquals("inline query", inlineQuery.getQuery()); + Assert.assertEquals("offset", inlineQuery.getOffset()); + assertFromUser(inlineQuery.getFrom()); + Assert.assertNotNull(inlineQuery.getLocation()); + Assert.assertEquals(Double.valueOf("0.234242534"), inlineQuery.getLocation().getLatitude()); + Assert.assertEquals(Double.valueOf("0.234242534"), inlineQuery.getLocation().getLongitude()); + } + + private void assertCallbackQuery(CallbackQuery callbackQuery) { + Assert.assertNotNull(callbackQuery); + Assert.assertEquals("4382bfdwdsb323b2d9", callbackQuery.getId()); + Assert.assertEquals("Data from button callback", callbackQuery.getData()); + Assert.assertEquals("1234csdbsk4839", callbackQuery.getInlineMessageId()); + assertFromUser(callbackQuery.getFrom()); + } + + private void assertEditedMessage(Message message) { + Assert.assertEquals((Integer) 1441645532, message.getDate()); + Assert.assertEquals((Integer) 1441646600, message.getEditDate()); + Assert.assertEquals((Integer) 1365, message.getMessageId()); + Assert.assertEquals("Edited text", message.getText()); + assertChannelChat(message.getChat()); + assertFromUser(message.getFrom()); + } + + private void assertFromUser(User from) { + Assert.assertNotNull(from); + Assert.assertEquals((Integer) 1111111, from.getId()); + Assert.assertEquals("Test Lastname", from.getLastName()); + Assert.assertEquals("Test Firstname", from.getFirstName()); + Assert.assertEquals("Testusername", from.getUserName()); + } + + private void assertChannelChat(Chat chat) { + Assert.assertNotNull(chat); + Assert.assertEquals(Long.valueOf(-10000000000L), chat.getId()); + Assert.assertTrue(chat.isChannelChat()); + Assert.assertEquals("Test channel", chat.getTitle()); + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/TestTelegramApi.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/TestTelegramApi.java new file mode 100644 index 00000000..76426b74 --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/TestTelegramApi.java @@ -0,0 +1,29 @@ +package org.telegram.telegrambots; + +import org.junit.Assert; +import org.junit.Test; +import org.telegram.telegrambots.base.TestBase; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public class TestTelegramApi extends TestBase { + + @Test + public void TestTelegramApiMustBeInitializableForLongPolling() { + new TelegramBotsApi(); + } + + @Test + public void TestTelegramApiMustBeInitializableForWebhook() { + try { + new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl"); + } catch (TelegramApiRequestException e) { + Assert.fail(); + } + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/apimethods/TestGetUpdates.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/apimethods/TestGetUpdates.java new file mode 100644 index 00000000..ec88fc93 --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/apimethods/TestGetUpdates.java @@ -0,0 +1,57 @@ +package org.telegram.telegrambots.apimethods; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.telegram.telegrambots.TelegramBotsHelper; +import org.telegram.telegrambots.api.methods.updates.GetUpdates; +import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; + +import java.util.ArrayList; + +/** + * @author Ruben Bermudez + * @version 1.0 + */ +public class TestGetUpdates { + + private GetUpdates getUpdates; + private ObjectMapper mapper = new ObjectMapper(); + + @Before + public void setUp() throws Exception { + getUpdates = new GetUpdates(); + getUpdates.setOffset(15); + getUpdates.setTimeout(50); + getUpdates.setLimit(100); + } + + @Test + public void TestGetUpdatesMustBeSerializable() throws Exception { + String json = mapper.writeValueAsString(getUpdates); + Assert.assertNotNull(json); + Assert.assertEquals("{\"offset\":15,\"limit\":100,\"timeout\":50,\"method\":\"getupdates\"}", json); + } + + @Test + public void TestGetUpdatesMustDeserializeCorrectResponse() throws Exception { + ArrayList result = + getUpdates.deserializeResponse(TelegramBotsHelper.GetResponseWithoutError()); + Assert.assertNotNull(result); + Assert.assertEquals(1, result.size()); + } + + @Test + public void TestGetUpdatesMustThrowAnExceptionForInCorrectResponse() { + try { + getUpdates.deserializeResponse(TelegramBotsHelper.GetResponseWithError()); + } catch (TelegramApiRequestException e) { + Assert.assertNotNull(e.getParameters()); + Assert.assertEquals(Integer.valueOf(400), e.getErrorCode()); + Assert.assertEquals("Error descriptions", e.getApiResponse()); + } + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/apimethods/TestSetGameScore.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/apimethods/TestSetGameScore.java new file mode 100644 index 00000000..3e82014d --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/apimethods/TestSetGameScore.java @@ -0,0 +1,55 @@ +package org.telegram.telegrambots.apimethods; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.telegram.telegrambots.TelegramBotsHelper; +import org.telegram.telegrambots.api.methods.games.SetGameScore; +import org.telegram.telegrambots.api.objects.Message; + +import java.io.Serializable; + +/** + * @author Ruben Bermudez + * @version 1.0 + */ +public class TestSetGameScore { + + private SetGameScore setGameScore; + private ObjectMapper mapper = new ObjectMapper(); + + @Before + public void setUp() throws Exception { + setGameScore = new SetGameScore(); + setGameScore.setChatId("12345"); + setGameScore.setEditMessage(true); + setGameScore.setMessageId(54321); + setGameScore.setScore(12); + setGameScore.setUserId(98765); + } + + @Test + public void TestGetUpdatesMustBeSerializable() throws Exception { + String json = mapper.writeValueAsString(setGameScore); + Assert.assertNotNull(json); + Assert.assertEquals("{\"chat_id\":\"12345\",\"message_id\":54321,\"edit_message\":true,\"user_id\":98765,\"score\":12,\"method\":\"setGameScore\"}", json); + } + + @Test + public void TestGetUpdatesMustDeserializeCorrectResponse() throws Exception { + Serializable result = + setGameScore.deserializeResponse(TelegramBotsHelper.GetSetGameScoreBooleanResponse()); + Assert.assertNotNull(result); + Assert.assertTrue(result instanceof Boolean); + Assert.assertTrue((Boolean) result); + } + + @Test + public void TestGetUpdatesMustThrowAnExceptionForInCorrectResponse() throws Exception { + Serializable result = setGameScore.deserializeResponse(TelegramBotsHelper.GetSetGameScoreMessageResponse()); + Assert.assertNotNull(result); + Assert.assertTrue(result instanceof Message); + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/asserts/ApiAssert.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/asserts/ApiAssert.java new file mode 100644 index 00000000..e4598f78 --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/asserts/ApiAssert.java @@ -0,0 +1,11 @@ +package org.telegram.telegrambots.asserts; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 04 of November of 2016 + */ +public final class ApiAssert { + private ApiAssert() {} +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/base/TestBase.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/base/TestBase.java new file mode 100644 index 00000000..2795a709 --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/base/TestBase.java @@ -0,0 +1,23 @@ +package org.telegram.telegrambots.base; + +import org.junit.BeforeClass; +import org.telegram.telegrambots.ApiContext; +import org.telegram.telegrambots.fakes.FakeBotSession; +import org.telegram.telegrambots.fakes.FakeWebhook; +import org.telegram.telegrambots.generics.BotSession; +import org.telegram.telegrambots.generics.Webhook; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public abstract class TestBase { + + @BeforeClass + public static void beforeClass() { + ApiContext.register(BotSession.class, FakeBotSession.class); + ApiContext.register(Webhook.class, FakeWebhook.class); + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/fakes/FakeBotSession.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/fakes/FakeBotSession.java new file mode 100644 index 00000000..2965b0f4 --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/fakes/FakeBotSession.java @@ -0,0 +1,43 @@ +package org.telegram.telegrambots.fakes; + +import org.telegram.telegrambots.generics.BotOptions; +import org.telegram.telegrambots.generics.BotSession; +import org.telegram.telegrambots.generics.LongPollingBot; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public class FakeBotSession implements BotSession { + @Override + public void setToken(String token) { + + } + + @Override + public void setCallback(LongPollingBot callback) { + + } + + @Override + public void start() { + + } + + @Override + public void close() { + + } + + @Override + public void setOptions(BotOptions options) { + + } + + @Override + public boolean isRunning() { + return false; + } +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/fakes/FakeWebhook.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/fakes/FakeWebhook.java new file mode 100644 index 00000000..b54298d4 --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/fakes/FakeWebhook.java @@ -0,0 +1,51 @@ +package org.telegram.telegrambots.fakes; + +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.generics.Webhook; +import org.telegram.telegrambots.generics.WebhookBot; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public class FakeWebhook implements Webhook { + private String internalUrl; + private String keyStore; + private String keyStorePassword; + + + @Override + public void startServer() throws TelegramApiRequestException { + + } + + @Override + public void registerWebhook(WebhookBot callback) { + + } + + @Override + public void setInternalUrl(String internalUrl) { + this.internalUrl = internalUrl; + } + + @Override + public void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiRequestException { + this.keyStore = keyStore; + this.keyStorePassword = keyStorePassword; + } + + public String getInternalUrl() { + return internalUrl; + } + + public String getKeyStore() { + return keyStore; + } + + public String getKeyStorePassword() { + return keyStorePassword; + } +} diff --git a/telegrambots-meta/src/test/resources/ResponseWithError.json b/telegrambots-meta/src/test/resources/ResponseWithError.json new file mode 100644 index 00000000..e4b31831 --- /dev/null +++ b/telegrambots-meta/src/test/resources/ResponseWithError.json @@ -0,0 +1,9 @@ +{ + "ok": false, + "error_code": 400, + "description": "Error descriptions", + "parameters": { + "migrate_to_chat_id": 12345, + "retry_after": 12 + } +} \ No newline at end of file diff --git a/telegrambots-meta/src/test/resources/ResponseWithoutError.json b/telegrambots-meta/src/test/resources/ResponseWithoutError.json new file mode 100644 index 00000000..9cd798af --- /dev/null +++ b/telegrambots-meta/src/test/resources/ResponseWithoutError.json @@ -0,0 +1,130 @@ +{ + "ok": true, + "result": [{ + "update_id": 10000, + "message": { + "date": 1441645532, + "chat": { + "last_name": "Test Lastname", + "id": 1111111, + "type": "private", + "first_name": "Test Firstname", + "username": "Testusername" + }, + "message_id": 1365, + "from": { + "last_name": "Test Lastname", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "forward_from": { + "last_name": "ForwardLastname", + "id": 222222, + "first_name": "ForwardFirstname" + }, + "forward_date": 1441645550, + "reply_to_message": { + "date": 1441645000, + "chat": { + "last_name": "ReplyLastname", + "type": "private", + "id": 1111112, + "first_name": "ReplyFirstname", + "username": "Testusername" + }, + "message_id": 1334, + "text": "Original" + }, + "text": "Bold and italics", + "entities": [ + { + "type": "italic", + "offset": 9, + "length": 7 + }, + { + "type": "bold", + "offset": 0, + "length": 4 + } + ], + "audio": { + "file_id": "AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", + "duration": 243, + "mime_type": "audio/mpeg", + "file_size": 3897500, + "title": "Testmusicfile" + }, + "voice": { + "file_id": "AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", + "duration": 5, + "mime_type": "audio/ogg", + "file_size": 23000 + }, + "document": { + "file_id": "AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", + "file_name": "Testfile.pdf", + "mime_type": "application/pdf", + "file_size": 536392 + } + }, + "edited_message": { + "date": 1441645532, + "chat": { + "id": -10000000000, + "type": "channel", + "title": "Test channel" + }, + "message_id": 1365, + "from": { + "last_name": "Test Lastname", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "text": "Edited text", + "edit_date": 1441646600 + }, + "inline_query": { + "id": "134567890097", + "from": { + "last_name": "Test Lastname", + "type": "private", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "query": "inline query", + "offset": "offset", + "location": { + "longitude": 0.234242534, + "latitude": 0.234242534 + } + }, + "chosen_inline_result": { + "result_id": "12", + "from": { + "last_name": "Test Lastname", + "type": "private", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "query": "inline query", + "inline_message_id": "1234csdbsk4839" + }, + "callback_query": { + "id": "4382bfdwdsb323b2d9", + "from": { + "last_name": "Test Lastname", + "type": "private", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "data": "Data from button callback", + "inline_message_id": "1234csdbsk4839" + } + }] +} \ No newline at end of file diff --git a/telegrambots-meta/src/test/resources/ResponsesSetGameScore.json b/telegrambots-meta/src/test/resources/ResponsesSetGameScore.json new file mode 100644 index 00000000..18169cdc --- /dev/null +++ b/telegrambots-meta/src/test/resources/ResponsesSetGameScore.json @@ -0,0 +1,26 @@ +{ + "ok": true, + "result": { + "date": 1441645532, + "chat": { + "last_name": "Test Lastname", + "id": 1111111, + "type": "private", + "first_name": "Test Firstname", + "username": "Testusername" + }, + "message_id": 1365, + "from": { + "last_name": "Test Lastname", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "text": "Original" + } +} + +{ + "ok": true, + "result": true +} \ No newline at end of file diff --git a/telegrambots-meta/src/test/resources/Update.json b/telegrambots-meta/src/test/resources/Update.json new file mode 100644 index 00000000..0b9f36c3 --- /dev/null +++ b/telegrambots-meta/src/test/resources/Update.json @@ -0,0 +1,127 @@ +{ + "update_id": 10000, + "message": { + "date": 1441645532, + "chat": { + "last_name": "Test Lastname", + "id": 1111111, + "type": "private", + "first_name": "Test Firstname", + "username": "Testusername" + }, + "message_id": 1365, + "from": { + "last_name": "Test Lastname", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "forward_from": { + "last_name": "ForwardLastname", + "id": 222222, + "first_name": "ForwardFirstname" + }, + "forward_date": 1441645550, + "reply_to_message": { + "date": 1441645000, + "chat": { + "last_name": "ReplyLastname", + "type": "private", + "id": 1111112, + "first_name": "ReplyFirstname", + "username": "Testusername" + }, + "message_id": 1334, + "text": "Original" + }, + "text": "Bold and italics", + "entities": [ + { + "type": "italic", + "offset": 9, + "length": 7 + }, + { + "type": "bold", + "offset": 0, + "length": 4 + } + ], + "audio": { + "file_id": "AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", + "duration": 243, + "mime_type": "audio/mpeg", + "file_size": 3897500, + "title": "Testmusicfile" + }, + "voice": { + "file_id": "AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", + "duration": 5, + "mime_type": "audio/ogg", + "file_size": 23000 + }, + "document": { + "file_id": "AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", + "file_name": "Testfile.pdf", + "mime_type": "application/pdf", + "file_size": 536392 + } + }, + "edited_message": { + "date": 1441645532, + "chat": { + "id": -10000000000, + "type": "channel", + "title": "Test channel" + }, + "message_id": 1365, + "from": { + "last_name": "Test Lastname", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "text": "Edited text", + "edit_date": 1441646600 + }, + "inline_query": { + "id": "134567890097", + "from": { + "last_name": "Test Lastname", + "type": "private", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "query": "inline query", + "offset": "offset", + "location": { + "longitude": 0.234242534, + "latitude": 0.234242534 + } + }, + "chosen_inline_result": { + "result_id": "12", + "from": { + "last_name": "Test Lastname", + "type": "private", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "query": "inline query", + "inline_message_id": "1234csdbsk4839" + }, + "callback_query": { + "id": "4382bfdwdsb323b2d9", + "from": { + "last_name": "Test Lastname", + "type": "private", + "id": 1111111, + "first_name": "Test Firstname", + "username": "Testusername" + }, + "data": "Data from button callback", + "inline_message_id": "1234csdbsk4839" + } +} \ No newline at end of file diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml new file mode 100644 index 00000000..d788ff77 --- /dev/null +++ b/telegrambots/pom.xml @@ -0,0 +1,250 @@ + + + 4.0.0 + org.telegram + telegrambots + 2.4.1 + jar + + Telegram Bots + https://github.com/rubenlagus/TelegramBots + Easy to use library to create Telegram Bots + + + https://github.com/rubenlagus/TelegramBots/issues + GitHub Issues + + + + https://github.com/rubenlagus/TelegramBots + scm:git:git://github.com/rubenlagus/TelegramBots.git + scm:git:git@github.com:rubenlagus/TelegramBots.git + + + + + rberlopez@gmail.com + Ruben Bermudez + https://github.com/rubenlagus + rubenlagus + + + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + repo + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + UTF-8 + UTF-8 + 2.24 + 1.19.3 + 4.5.2 + 20160810 + 2.8.5 + 2.5 + 2.4.1 + + + + + + org.glassfish.jersey + jersey-bom + ${glassfish.version} + pom + import + + + + + + + org.telegram + telegrambots-meta + ${bots.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${glassfish.version} + + + org.glassfish.jersey.containers + jersey-container-grizzly2-http + ${glassfish.version} + + + org.glassfish.jersey.core + jersey-server + ${glassfish.version} + + + org.json + json + ${json.version} + + + org.apache.httpcomponents + httpclient + ${httpcompontents.version} + + + org.apache.httpcomponents + httpmime + ${httpcompontents.version} + + + commons-io + commons-io + ${commonio.version} + + + + org.glassfish.jersey.test-framework + jersey-test-framework-core + 2.24 + test + + + org.glassfish.jersey.test-framework.providers + jersey-test-framework-provider-grizzly2 + 2.24 + test + + + + + + ${project.basedir}/target + ${project.build.directory}/classes + ${project.artifactId}-${project.version} + ${project.build.directory}/test-classes + ${project.basedir}/src/main/java + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + true + + + + 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 + + + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + + jar + + + -Xdoclint:none + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + UTF-8 + + + + + + \ No newline at end of file diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java b/telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java new file mode 100644 index 00000000..8de501b2 --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java @@ -0,0 +1,22 @@ +package org.telegram.telegrambots; + +import org.telegram.telegrambots.generics.BotSession; +import org.telegram.telegrambots.generics.Webhook; +import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; +import org.telegram.telegrambots.updatesreceivers.DefaultWebhook; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 29 of October of 2016 + */ +public final class ApiContextInitializer { + private ApiContextInitializer() { + } + + public static void init() { + ApiContext.register(BotSession.class, DefaultBotSession.class); + ApiContext.register(Webhook.class, DefaultWebhook.class); + } +} diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java b/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java new file mode 100644 index 00000000..b6d13af7 --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java @@ -0,0 +1,11 @@ +package org.telegram.telegrambots; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Constants needed for Telegram Bots API + * @date 20 of June of 2015 + */ +public class Constants { + public static final int SOCKET_TIMEOUT = 75 * 1000; +} diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/BotOptions.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/BotOptions.java new file mode 100644 index 00000000..73822506 --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/BotOptions.java @@ -0,0 +1,61 @@ +package org.telegram.telegrambots.bots; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.telegram.telegrambots.Constants; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @deprecated Use {@link DefaultBotOptions} instead + */ +@Deprecated +public class BotOptions extends DefaultBotOptions { + private String proxyHost; + private int proxyPort; + + public boolean hasProxy() { + return proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0; + } + + /** + * @deprecated Use {@link #setRequestConfig(RequestConfig)} instead to configure custom request config + * @param proxyHost Host for the proxy + * + * @apiNote This method will be removed in the future + */ + public void setProxyHost(String proxyHost) { + this.proxyHost = proxyHost; + } + + /** + * @deprecated Use {@link #setRequestConfig(RequestConfig)} instead to configure custom request config + * @param proxyPort Port for the proxy + * + * @apiNote This method will be removed in the future + */ + public void setProxyPort(int proxyPort) { + this.proxyPort = proxyPort; + } + + @Override + public RequestConfig getRequestConfig() { + if (super.getRequestConfig() == null) { + if (hasProxy()) { // For backward compatibility + return RequestConfig.copy(RequestConfig.custom().build()) + .setProxy(new HttpHost(proxyHost, proxyPort)) + .setSocketTimeout(Constants.SOCKET_TIMEOUT) + .setConnectTimeout(Constants.SOCKET_TIMEOUT) + .setConnectionRequestTimeout(Constants.SOCKET_TIMEOUT) + .build(); + } + return RequestConfig.copy(RequestConfig.custom().build()) + .setSocketTimeout(Constants.SOCKET_TIMEOUT) + .setConnectTimeout(Constants.SOCKET_TIMEOUT) + .setConnectionRequestTimeout(Constants.SOCKET_TIMEOUT) + .build(); + } + + return super.getRequestConfig(); + } +} diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java similarity index 54% rename from src/main/java/org/telegram/telegrambots/bots/AbsSender.java rename to telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java index 1421eeff..40eef66d 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java @@ -1,8 +1,9 @@ package org.telegram.telegrambots.bots; +import com.fasterxml.jackson.databind.ObjectMapper; + import org.apache.commons.io.FileUtils; 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; @@ -18,47 +19,16 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONObject; -import org.telegram.telegrambots.Constants; -import org.telegram.telegrambots.api.methods.AnswerCallbackQuery; -import org.telegram.telegrambots.api.methods.AnswerInlineQuery; +import org.telegram.telegrambots.ApiConstants; import org.telegram.telegrambots.api.methods.BotApiMethod; -import org.telegram.telegrambots.api.methods.ForwardMessage; -import org.telegram.telegrambots.api.methods.GetFile; -import org.telegram.telegrambots.api.methods.GetMe; -import org.telegram.telegrambots.api.methods.GetUserProfilePhotos; -import org.telegram.telegrambots.api.methods.games.GetGameHighScores; -import org.telegram.telegrambots.api.methods.games.SetGameScore; -import org.telegram.telegrambots.api.methods.groupadministration.GetChat; -import org.telegram.telegrambots.api.methods.groupadministration.GetChatAdministrators; -import org.telegram.telegrambots.api.methods.groupadministration.GetChatMember; -import org.telegram.telegrambots.api.methods.groupadministration.GetChatMemberCount; -import org.telegram.telegrambots.api.methods.groupadministration.KickChatMember; -import org.telegram.telegrambots.api.methods.groupadministration.LeaveChat; -import org.telegram.telegrambots.api.methods.groupadministration.UnbanChatMember; import org.telegram.telegrambots.api.methods.send.SendAudio; -import org.telegram.telegrambots.api.methods.send.SendChatAction; -import org.telegram.telegrambots.api.methods.send.SendContact; import org.telegram.telegrambots.api.methods.send.SendDocument; -import org.telegram.telegrambots.api.methods.send.SendGame; -import org.telegram.telegrambots.api.methods.send.SendLocation; -import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.methods.send.SendPhoto; 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; -import org.telegram.telegrambots.api.objects.Chat; -import org.telegram.telegrambots.api.objects.ChatMember; 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.api.objects.games.GameHighScore; import org.telegram.telegrambots.exceptions.TelegramApiException; import org.telegram.telegrambots.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.exceptions.TelegramApiValidationException; @@ -70,7 +40,6 @@ import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; @@ -84,16 +53,18 @@ import java.util.concurrent.TimeUnit; * @date 14 of January of 2016 */ @SuppressWarnings("unused") -public abstract class AbsSender { +public abstract class DefaultAbsSender extends 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 final ExecutorService exe; + private final ObjectMapper objectMapper = new ObjectMapper(); + private final DefaultBotOptions options; private volatile CloseableHttpClient httpclient; private volatile RequestConfig requestConfig; - private static final int SOCKET_TIMEOUT = 75 * 1000; - AbsSender(BotOptions options) { + protected DefaultAbsSender(DefaultBotOptions options) { + super(); + this.exe = Executors.newFixedThreadPool(options.getMaxThreads()); this.options = options; httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) @@ -101,14 +72,7 @@ public abstract class AbsSender { .setMaxConnTotal(100) .build(); - 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(); + requestConfig = options.getRequestConfig(); } /** @@ -117,179 +81,35 @@ public abstract class AbsSender { */ public abstract String getBotToken(); - public final BotOptions getOptions() { + public final DefaultBotOptions getOptions() { return options; } // Send Requests - public final Message sendMessage(SendMessage sendMessage) throws TelegramApiException { - if (sendMessage == null) { - throw new TelegramApiException("Parameter sendMessage can not be null"); + public final java.io.File downloadFile(String filePath) throws TelegramApiException { + if(filePath == null || filePath.isEmpty()){ + throw new TelegramApiException("Parameter file can not be null"); + } + String url = File.getFileUrl(getBotToken(), filePath); + java.io.File output; + try { + output = java.io.File.createTempFile(Long.toString(System.currentTimeMillis()), ".tmp"); + FileUtils.copyURLToFile(new URL(url), output); + } catch (MalformedURLException e) { + throw new TelegramApiException("Wrong url for file: " + url); + } catch (IOException e) { + throw new TelegramApiRequestException("Error downloading the file", e); } - return sendApiMethod(sendMessage); - } - - public final Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { - if (answerInlineQuery == null) { - throw new TelegramApiException("Parameter answerInlineQuery can not be null"); - } - - return sendApiMethod(answerInlineQuery); - } - - public final Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { - if (sendChatAction == null) { - throw new TelegramApiException("Parameter sendChatAction can not be null"); - } - - return sendApiMethod(sendChatAction); - } - - public final Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { - if (forwardMessage == null) { - throw new TelegramApiException("Parameter forwardMessage can not be null"); - } - - return sendApiMethod(forwardMessage); - } - - public final Message sendLocation(SendLocation sendLocation) throws TelegramApiException { - if (sendLocation == null) { - throw new TelegramApiException("Parameter sendLocation can not be null"); - } - - return sendApiMethod(sendLocation); - } - - public final Message sendVenue(SendVenue sendVenue) throws TelegramApiException { - if (sendVenue == null) { - throw new TelegramApiException("Parameter sendVenue can not be null"); - } - - return sendApiMethod(sendVenue); - } - - public final Message sendContact(SendContact sendContact) throws TelegramApiException { - if (sendContact == null) { - throw new TelegramApiException("Parameter sendContact can not be null"); - } - - return sendApiMethod(sendContact); - } - - public final Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { - if (kickChatMember == null) { - throw new TelegramApiException("Parameter kickChatMember can not be null"); - } - return sendApiMethod(kickChatMember); - } - - public final Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { - if (unbanChatMember == null) { - throw new TelegramApiException("Parameter unbanChatMember can not be null"); - } - return sendApiMethod(unbanChatMember); - } - - public final Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { - if (leaveChat == null) { - throw new TelegramApiException("Parameter leaveChat can not be null"); - } - return sendApiMethod(leaveChat); - } - - public final Chat getChat(GetChat getChat) throws TelegramApiException { - if (getChat == null) { - throw new TelegramApiException("Parameter getChat can not be null"); - } - return sendApiMethod(getChat); - } - - public final List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { - if (getChatAdministrators == null) { - throw new TelegramApiException("Parameter getChatAdministrators can not be null"); - } - return sendApiMethod(getChatAdministrators); - } - - public final ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { - if (getChatMember == null) { - throw new TelegramApiException("Parameter getChatMember can not be null"); - } - return sendApiMethod(getChatMember); - } - - public final Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { - if (getChatMemberCount == null) { - throw new TelegramApiException("Parameter getChatMemberCount can not be null"); - } - return sendApiMethod(getChatMemberCount); - } - - public final Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { - if (editMessageText == null) { - throw new TelegramApiException("Parameter editMessageText can not be null"); - } - return sendApiMethod(editMessageText); - } - - public final Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { - if (editMessageCaption == null) { - throw new TelegramApiException("Parameter editMessageCaption can not be null"); - } - return sendApiMethod(editMessageCaption); - } - - public final Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { - if (editMessageReplyMarkup == null) { - throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); - } - return sendApiMethod(editMessageReplyMarkup); - } - - public final Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { - if (answerCallbackQuery == null) { - throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); - } - return sendApiMethod(answerCallbackQuery); - } - - public final UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { - if (getUserProfilePhotos == null) { - throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); - } - - return sendApiMethod(getUserProfilePhotos); - } - - 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 sendApiMethod(getFile); - } - - public final User getMe() throws TelegramApiException { - GetMe getMe = new GetMe(); - - return sendApiMethod(getMe); - } - - public final WebhookInfo getWebhookInfo() throws TelegramApiException { - GetWebhookInfo getWebhookInfo = new GetWebhookInfo(); - return sendApiMethod(getWebhookInfo); + return output; } public final java.io.File downloadFile(File file) throws TelegramApiException { if(file == null){ throw new TelegramApiException("Parameter file can not be null"); } - String url = MessageFormat.format(File.FILEBASEURL, getBotToken(), file.getFilePath()); + String url = file.getFileUrl(getBotToken()); java.io.File output; try { output = java.io.File.createTempFile(file.getFileId(), ".tmp"); @@ -303,299 +123,32 @@ public abstract class AbsSender { return output; } - public final Serializable setGameScore(SetGameScore setGameScore) throws TelegramApiException { - if(setGameScore == null){ - throw new TelegramApiException("Parameter setGameScore can not be null"); + public final void downloadFileAsync(String filePath, DownloadFileCallback callback) throws TelegramApiException { + if(filePath == null || filePath.isEmpty()){ + throw new TelegramApiException("Parameter filePath can not be null"); } - return sendApiMethod(setGameScore); + if (callback == null) { + throw new TelegramApiException("Parameter callback can not be null"); + } + + exe.submit(new Runnable() { + @Override + public void run() { + String url = File.getFileUrl(getBotToken(), filePath); + try { + java.io.File output = java.io.File.createTempFile(Long.toString(System.currentTimeMillis()), ".tmp"); + FileUtils.copyURLToFile(new URL(url), output); + callback.onResult(filePath, output); + } catch (MalformedURLException e) { + callback.onException(filePath, new TelegramApiException("Wrong url for file: " + url)); + } catch (IOException e) { + callback.onException(filePath, new TelegramApiRequestException("Error downloading the file", e)); + } + } + }); } - public final Serializable getGameHighScores(GetGameHighScores getGameHighScores) throws TelegramApiException { - if(getGameHighScores == null){ - throw new TelegramApiException("Parameter getGameHighScores can not be null"); - } - return sendApiMethod(getGameHighScores); - } - - public final Message sendGame(SendGame sendGame) throws TelegramApiException { - if(sendGame == null){ - throw new TelegramApiException("Parameter sendGame can not be null"); - } - return sendApiMethod(sendGame); - } - - // Send Requests Async - - public final void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { - if (sendMessage == null) { - throw new TelegramApiException("Parameter sendMessage can not be null"); - } - - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(sendMessage, sentCallback); - } - - public final void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback sentCallback) throws TelegramApiException { - if (answerInlineQuery == null) { - throw new TelegramApiException("Parameter answerInlineQuery can not be null"); - } - - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(answerInlineQuery, sentCallback); - } - - public final void sendChatActionAsync(SendChatAction sendChatAction, SentCallback sentCallback) throws TelegramApiException { - if (sendChatAction == null) { - throw new TelegramApiException("Parameter sendChatAction can not be null"); - } - - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(sendChatAction, sentCallback); - } - - public final void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback sentCallback) throws TelegramApiException { - if (forwardMessage == null) { - throw new TelegramApiException("Parameter forwardMessage can not be null"); - } - - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(forwardMessage, sentCallback); - } - - public final void sendLocationAsync(SendLocation sendLocation, SentCallback sentCallback) throws TelegramApiException { - if (sendLocation == null) { - throw new TelegramApiException("Parameter sendLocation can not be null"); - } - - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(sendLocation, sentCallback); - } - - public final void sendVenueAsync(SendVenue sendVenue, SentCallback sentCallback) throws TelegramApiException { - if (sendVenue == null) { - throw new TelegramApiException("Parameter sendVenue can not be null"); - } - - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(sendVenue, sentCallback); - } - - public final void sendContactAsync(SendContact sendContact, SentCallback sentCallback) throws TelegramApiException { - if (sendContact == null) { - throw new TelegramApiException("Parameter sendContact can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(sendContact, sentCallback); - } - - public final void kickMemberAsync(KickChatMember kickChatMember, SentCallback sentCallback) throws TelegramApiException { - if (kickChatMember == null) { - throw new TelegramApiException("Parameter kickChatMember can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(kickChatMember, sentCallback); - } - - public final void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback sentCallback) throws TelegramApiException { - if (unbanChatMember == null) { - throw new TelegramApiException("Parameter unbanChatMember can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(unbanChatMember, sentCallback); - } - - public final void leaveChatAsync(LeaveChat leaveChat, SentCallback sentCallback) throws TelegramApiException { - if (leaveChat == null) { - throw new TelegramApiException("Parameter leaveChat can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(leaveChat, sentCallback); - } - - public final void getChatAsync(GetChat getChat, SentCallback sentCallback) throws TelegramApiException { - if (getChat == null) { - throw new TelegramApiException("Parameter getChat can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(getChat, sentCallback); - } - - public final void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback> sentCallback) throws TelegramApiException { - if (getChatAdministrators == null) { - throw new TelegramApiException("Parameter getChatAdministrators can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(getChatAdministrators, sentCallback); - } - - public final void getChatMemberAsync(GetChatMember getChatMember, SentCallback sentCallback) throws TelegramApiException { - if (getChatMember == null) { - throw new TelegramApiException("Parameter getChatMember can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(getChatMember, sentCallback); - } - - public final void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback sentCallback) throws TelegramApiException { - if (getChatMemberCount == null) { - throw new TelegramApiException("Parameter getChatMemberCount can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(getChatMemberCount, sentCallback); - } - - public final void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { - if (editMessageText == null) { - throw new TelegramApiException("Parameter editMessageText can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(editMessageText, sentCallback); - } - - public final void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback sentCallback) throws TelegramApiException { - if (editMessageCaption == null) { - throw new TelegramApiException("Parameter editMessageCaption can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(editMessageCaption, sentCallback); - } - - public final void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback sentCallback) throws TelegramApiException { - if (editMessageReplyMarkup == null) { - throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(editMessageReplyMarkup, sentCallback); - } - - public final void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback sentCallback) throws TelegramApiException { - if (answerCallbackQuery == null) { - throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(answerCallbackQuery, sentCallback); - } - - public final void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback sentCallback) throws TelegramApiException { - if (getUserProfilePhotos == null) { - throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(getUserProfilePhotos, sentCallback); - } - - public final void getFileAsync(GetFile getFile, SentCallback sentCallback) throws TelegramApiException { - if (getFile == null) { - throw new TelegramApiException("Parameter getFile can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - - sendApiMethodAsync(getFile, sentCallback); - } - - public final void getMeAsync(SentCallback sentCallback) throws TelegramApiException { - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - GetMe getMe = new GetMe(); - 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); - } - - public final void setGameScoreAsync(SetGameScore setGameScore, SentCallback sentCallback) throws TelegramApiException { - if (setGameScore == null) { - throw new TelegramApiException("Parameter setGameScore can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(setGameScore, sentCallback); - } - - public final void getGameHighScoresAsync(GetGameHighScores getGameHighScores, SentCallback> sentCallback) throws TelegramApiException { - if (getGameHighScores == null) { - throw new TelegramApiException("Parameter getGameHighScores can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(getGameHighScores, sentCallback); - } - - public final void sendGameAsync(SendGame sendGame, SentCallback sentCallback) throws TelegramApiException { - if (sendGame == null) { - throw new TelegramApiException("Parameter sendGame can not be null"); - } - if (sentCallback == null) { - throw new TelegramApiException("Parameter sentCallback can not be null"); - } - sendApiMethodAsync(sendGame, sentCallback); - } - - public final void downloadFileAsync(File file, DownloadFileCallback callback) throws TelegramApiException { + public final void downloadFileAsync(File file, DownloadFileCallback callback) throws TelegramApiException { if(file == null){ throw new TelegramApiException("Parameter file can not be null"); } @@ -606,7 +159,7 @@ public abstract class AbsSender { exe.submit(new Runnable() { @Override public void run() { - String url = MessageFormat.format(File.FILEBASEURL, getBotToken(), file.getFilePath()); + String url = file.getFileUrl(getBotToken()); try { java.io.File output = java.io.File.createTempFile(file.getFileId(), ".tmp"); FileUtils.copyURLToFile(new URL(url), output); @@ -622,7 +175,13 @@ public abstract class AbsSender { // Specific Send Requests + @Override public final Message sendDocument(SendDocument sendDocument) throws TelegramApiException { + if(sendDocument == null){ + throw new TelegramApiException("Parameter sendDocument can not be null"); + } + + sendDocument.validate(); String responseContent; try { @@ -640,7 +199,7 @@ public abstract class AbsSender { builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); } if (sendDocument.getReplyMarkup() != null) { - builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendDocument.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE); } if (sendDocument.getReplyToMessageId() != null) { builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString()); @@ -658,7 +217,7 @@ public abstract class AbsSender { nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendDocument.DOCUMENT_FIELD, sendDocument.getDocument())); if (sendDocument.getReplyMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplyMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendDocument.getReplyMarkup()))); } if (sendDocument.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString())); @@ -681,15 +240,16 @@ public abstract class AbsSender { throw new TelegramApiException("Unable to send document", e); } - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at sendDocument", jsonObject); - } - - return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); + return sendDocument.deserializeResponse(responseContent); } + @Override public final Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException { + if(sendPhoto == null){ + throw new TelegramApiException("Parameter sendPhoto can not be null"); + } + + sendPhoto.validate(); String responseContent; try { String url = getBaseUrl() + SendPhoto.PATH; @@ -706,7 +266,7 @@ public abstract class AbsSender { builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); } if (sendPhoto.getReplyMarkup() != null) { - builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendPhoto.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE); } if (sendPhoto.getReplyToMessageId() != null) { builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString()); @@ -724,7 +284,7 @@ public abstract class AbsSender { nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendPhoto.PHOTO_FIELD, sendPhoto.getPhoto())); if (sendPhoto.getReplyMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplyMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendPhoto.getReplyMarkup()))); } if (sendPhoto.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString())); @@ -747,15 +307,16 @@ public abstract class AbsSender { throw new TelegramApiException("Unable to send photo", e); } - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at sendPhoto", jsonObject); - } - - return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); + return sendPhoto.deserializeResponse(responseContent); } + @Override public final Message sendVideo(SendVideo sendVideo) throws TelegramApiException { + if(sendVideo == null){ + throw new TelegramApiException("Parameter sendVideo can not be null"); + } + + sendVideo.validate(); String responseContent; try { String url = getBaseUrl() + SendVideo.PATH; @@ -772,7 +333,7 @@ public abstract class AbsSender { builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); } if (sendVideo.getReplyMarkup() != null) { - builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendVideo.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE); } if (sendVideo.getReplyToMessageId() != null) { builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplyToMessageId().toString()); @@ -799,7 +360,7 @@ public abstract class AbsSender { nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendVideo.VIDEO_FIELD, sendVideo.getVideo())); if (sendVideo.getReplyMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplyMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendVideo.getReplyMarkup()))); } if (sendVideo.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplyToMessageId().toString())); @@ -831,17 +392,17 @@ public abstract class AbsSender { throw new TelegramApiException("Unable to send video", e); } - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at sendVideo", jsonObject); - } - - return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); + return sendVideo.deserializeResponse(responseContent); } + @Override public final Message sendSticker(SendSticker sendSticker) throws TelegramApiException { - String responseContent; + if(sendSticker == null){ + throw new TelegramApiException("Parameter sendSticker can not be null"); + } + sendSticker.validate(); + String responseContent; try { String url = getBaseUrl() + SendSticker.PATH; HttpPost httppost = new HttpPost(url); @@ -857,7 +418,7 @@ public abstract class AbsSender { builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); } if (sendSticker.getReplyMarkup() != null) { - builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendSticker.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE); } if (sendSticker.getReplyToMessageId() != null) { builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString()); @@ -872,7 +433,7 @@ public abstract class AbsSender { nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendSticker.STICKER_FIELD, sendSticker.getSticker())); if (sendSticker.getReplyMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplyMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendSticker.getReplyMarkup()))); } if (sendSticker.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString())); @@ -892,12 +453,7 @@ public abstract class AbsSender { throw new TelegramApiException("Unable to send sticker", e); } - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at sendSticker", jsonObject); - } - - return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); + return sendSticker.deserializeResponse(responseContent); } /** @@ -906,10 +462,14 @@ public abstract class AbsSender { * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio */ + @Override public final Message sendAudio(SendAudio sendAudio) throws TelegramApiException { + if(sendAudio == null){ + throw new TelegramApiException("Parameter sendAudio can not be null"); + } + sendAudio.validate(); String responseContent; - try { String url = getBaseUrl() + SendAudio.PATH; HttpPost httppost = new HttpPost(url); @@ -925,7 +485,7 @@ public abstract class AbsSender { builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); } if (sendAudio.getReplyMarkup() != null) { - builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendAudio.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE); } if (sendAudio.getReplyToMessageId() != null) { builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString()); @@ -952,7 +512,7 @@ public abstract class AbsSender { nameValuePairs.add(new BasicNameValuePair(SendAudio.CHATID_FIELD, sendAudio.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendAudio.AUDIO_FIELD, sendAudio.getAudio())); if (sendAudio.getReplyMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplyMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendAudio.getReplyMarkup()))); } if (sendAudio.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString())); @@ -981,18 +541,7 @@ public abstract class AbsSender { throw new TelegramApiException("Unable to send sticker", e); } - JSONObject jsonObject = new JSONObject(responseContent); - - /* if we got not an "ok" with false, we have a response like that - * - * {"description":"[Error]: Bad Request: chat not found","error_code":400,"ok":false} - */ - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at sendAudio", jsonObject); - } - - // and if not, we can expect a "result" section. and out of this can a new Message object be built - return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); + return sendAudio.deserializeResponse(responseContent); } /** @@ -1002,7 +551,12 @@ public abstract class AbsSender { * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio */ + @Override public final Message sendVoice(SendVoice sendVoice) throws TelegramApiException { + if(sendVoice == null){ + throw new TelegramApiException("Parameter sendVoice can not be null"); + } + sendVoice.validate(); String responseContent; try { @@ -1020,7 +574,7 @@ public abstract class AbsSender { builder.addBinaryBody(SendVoice.VOICE_FIELD, new java.io.File(sendVoice.getVoice()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); } if (sendVoice.getReplyMarkup() != null) { - builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendVoice.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE); } if (sendVoice.getReplyToMessageId() != null) { builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString()); @@ -1041,7 +595,7 @@ public abstract class AbsSender { nameValuePairs.add(new BasicNameValuePair(SendVoice.CHATID_FIELD, sendVoice.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendVoice.VOICE_FIELD, sendVoice.getVoice())); if (sendVoice.getReplyMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplyMarkup().toJson().toString())); + nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendVoice.getReplyMarkup()))); } if (sendVoice.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString())); @@ -1067,35 +621,31 @@ public abstract class AbsSender { throw new TelegramApiException("Unable to send sticker", e); } - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at sendVoice", jsonObject); - } - - return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); + return sendVoice.deserializeResponse(responseContent); } // Simplified methods - private , Callback extends SentCallback> void sendApiMethodAsync(Method method, Callback callback) { + @Override + protected final , Callback extends SentCallback> void sendApiMethodAsync(Method method, Callback callback) { //noinspection Convert2Lambda exe.submit(new Runnable() { @Override public void run() { try { method.validate(); - String url = getBaseUrl() + method.getPath(); + String url = getBaseUrl() + method.getMethod(); HttpPost httppost = new HttpPost(url); httppost.setConfig(requestConfig); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); - httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON)); + httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httppost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { + if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) { callback.onError(method, jsonObject); } callback.onResult(method, jsonObject); @@ -1108,33 +658,29 @@ public abstract class AbsSender { }); } - private T sendApiMethod(BotApiMethod method) throws TelegramApiException { + @Override + protected final > T sendApiMethod(Method method) throws TelegramApiException { method.validate(); String responseContent; try { - String url = getBaseUrl() + method.getPath(); + String url = getBaseUrl() + method.getMethod(); HttpPost httppost = new HttpPost(url); httppost.setConfig(requestConfig); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); - httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON)); + httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httppost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); } } catch (IOException e) { - throw new TelegramApiException("Unable to execute " + method.getPath() + " method", e); + throw new TelegramApiException("Unable to execute " + method.getMethod() + " method", e); } - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error at " + method.getPath(), jsonObject); - } - - return method.deserializeResponse(jsonObject); + return method.deserializeResponse(responseContent); } private String getBaseUrl() { - return Constants.BASEURL + getBotToken() + "/"; + return ApiConstants.BASE_URL + getBotToken() + "/"; } } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java new file mode 100644 index 00000000..86b98363 --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java @@ -0,0 +1,39 @@ +package org.telegram.telegrambots.bots; + +import org.apache.http.client.config.RequestConfig; +import org.telegram.telegrambots.generics.BotOptions; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Configurations for the Bot + * @date 21 of July of 2016 + */ +public class DefaultBotOptions implements BotOptions { + private int maxThreads; ///< Max number of threads used for async methods executions (default 1) + private RequestConfig requestConfig; + + public DefaultBotOptions() { + maxThreads = 1; + } + + public void setMaxThreads(int maxThreads) { + this.maxThreads = maxThreads; + } + + public int getMaxThreads() { + return maxThreads; + } + + public RequestConfig getRequestConfig() { + return requestConfig; + } + + /** + * @implSpec Default implementation assumes no proxy is needed and sets a 75secs timoute + * @param requestConfig Request config to be used in all Http requests + */ + public void setRequestConfig(RequestConfig requestConfig) { + this.requestConfig = requestConfig; + } +} diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java new file mode 100644 index 00000000..7e73790a --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -0,0 +1,59 @@ +package org.telegram.telegrambots.bots; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.entity.BufferedHttpEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.telegram.telegrambots.ApiConstants; +import org.telegram.telegrambots.ApiContext; +import org.telegram.telegrambots.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.generics.LongPollingBot; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Base abstract class for a bot that will get updates using + * long-polling method + * @date 14 of January of 2016 + */ +public abstract class TelegramLongPollingBot extends DefaultAbsSender implements LongPollingBot { + public TelegramLongPollingBot() { + this(ApiContext.getInstance(DefaultBotOptions.class)); + } + + public TelegramLongPollingBot(DefaultBotOptions options) { + super(options); + } + + @Override + public void clearWebhook() throws TelegramApiRequestException { + try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) { + String url = ApiConstants.BASE_URL + getBotToken() + "/" + SetWebhook.PATH; + HttpGet httpGet = new HttpGet(url); + httpGet.setConfig(getOptions().getRequestConfig()); + try (CloseableHttpResponse response = httpclient.execute(httpGet)) { + HttpEntity ht = response.getEntity(); + BufferedHttpEntity buf = new BufferedHttpEntity(ht); + String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); + JSONObject jsonObject = new JSONObject(responseContent); + if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) { + throw new TelegramApiRequestException("Error removing old webhook", jsonObject); + } + } + } catch (JSONException e) { + throw new TelegramApiRequestException("Error deserializing setWebhook method response", e); + } catch (IOException e) { + throw new TelegramApiRequestException("Error executing setWebook method", e); + } + } +} diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java similarity index 93% rename from src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java rename to telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index b3b31cef..3cf4edea 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -1,11 +1,12 @@ package org.telegram.telegrambots.bots; +import org.telegram.telegrambots.ApiContext; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.Update; 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; @@ -24,7 +25,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * Use ICommandRegistry's methods on this bot to register commands */ public TelegramLongPollingCommandBot() { - this(new BotOptions()); + this(ApiContext.getInstance(DefaultBotOptions.class)); } /** @@ -33,7 +34,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * Use ICommandRegistry's methods on this bot to register commands * @param options Bot options */ - public TelegramLongPollingCommandBot(BotOptions options) { + public TelegramLongPollingCommandBot(DefaultBotOptions options) { this(options, true); } @@ -44,7 +45,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * @param allowCommandsWithUsername true to allow commands with parameters (default), * false otherwise */ - public TelegramLongPollingCommandBot(BotOptions options, boolean allowCommandsWithUsername) { + public TelegramLongPollingCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername) { super(options); this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, getBotUsername()); } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java new file mode 100644 index 00000000..2bec6770 --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java @@ -0,0 +1,77 @@ +package org.telegram.telegrambots.bots; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.entity.BufferedHttpEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.telegram.telegrambots.ApiConstants; +import org.telegram.telegrambots.ApiContext; +import org.telegram.telegrambots.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.generics.WebhookBot; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Base abstract class for a bot that will receive updates using a + * webhook + * @date 14 of January of 2016 + */ +public abstract class TelegramWebhookBot extends AbsSender implements WebhookBot { + private final DefaultBotOptions botOptions; + + public TelegramWebhookBot() { + this(ApiContext.getInstance(DefaultBotOptions.class)); + } + + public TelegramWebhookBot(DefaultBotOptions options) { + super(); + this.botOptions = options; + } + + @Override + public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { + try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) { + String requestUrl = ApiConstants.BASE_URL + getBotToken() + "/" + SetWebhook.PATH; + + HttpPost httppost = new HttpPost(requestUrl); + httppost.setConfig(botOptions.getRequestConfig()); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.addTextBody(SetWebhook.URL_FIELD, url); + if (publicCertificatePath != null) { + 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); + try (CloseableHttpResponse response = httpclient.execute(httppost)) { + HttpEntity ht = response.getEntity(); + BufferedHttpEntity buf = new BufferedHttpEntity(ht); + String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); + JSONObject jsonObject = new JSONObject(responseContent); + if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) { + throw new TelegramApiRequestException("Error setting webhook", jsonObject); + } + } + } catch (JSONException e) { + throw new TelegramApiRequestException("Error deserializing setWebhook method response", e); + } catch (IOException e) { + throw new TelegramApiRequestException("Error executing setWebook method", e); + } + + } +} diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java rename to telegrambots/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java rename to telegrambots/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java similarity index 100% rename from src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java rename to telegrambots/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java similarity index 53% rename from src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java rename to telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java index 7c32661a..d33fd24c 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java @@ -1,7 +1,10 @@ package org.telegram.telegrambots.updatesreceivers; +import com.google.inject.Inject; + +import com.fasterxml.jackson.databind.ObjectMapper; + 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; @@ -12,20 +15,24 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; -import org.json.JSONArray; import org.json.JSONException; -import org.json.JSONObject; -import org.telegram.telegrambots.Constants; +import org.telegram.telegrambots.ApiConstants; 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.bots.DefaultBotOptions; import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.generics.BotOptions; +import org.telegram.telegrambots.generics.BotSession; +import org.telegram.telegrambots.generics.LongPollingBot; +import org.telegram.telegrambots.generics.UpdatesHandler; +import org.telegram.telegrambots.generics.UpdatesReader; import org.telegram.telegrambots.logging.BotLogger; import java.io.IOException; import java.io.InvalidObjectException; import java.nio.charset.StandardCharsets; +import java.security.InvalidParameterException; +import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.TimeUnit; @@ -35,48 +42,46 @@ import java.util.concurrent.TimeUnit; * @brief Thread to request updates with active wait * @date 20 of June of 2015 */ -public class BotSession { - private static final String LOGTAG = "BOTSESSION"; - private static final int SOCKET_TIMEOUT = 75 * 1000; +public class DefaultBotSession implements BotSession { + protected static final String LOGTAG = "BOTSESSION"; + + private volatile boolean running = false; - private final ITelegramLongPollingBot callback; - private final ReaderThread readerThread; - private final HandlerThread handlerThread; private final ConcurrentLinkedDeque receivedUpdates = new ConcurrentLinkedDeque<>(); - private final String token; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private ReaderThread readerThread; + private HandlerThread handlerThread; + private LongPollingBot callback; + private String token; private int lastReceivedUpdate = 0; - private volatile boolean running = true; - private volatile CloseableHttpClient httpclient; - private volatile RequestConfig requestConfig; + private DefaultBotOptions options; - public BotSession(String token, ITelegramLongPollingBot callback, BotOptions options) { - this.token = token; - this.callback = callback; + @Inject + public DefaultBotSession() { + } - httpclient = HttpClientBuilder.create() - .setSSLHostnameVerifier(new NoopHostnameVerifier()) - .setConnectionTimeToLive(70, TimeUnit.SECONDS) - .setMaxConnTotal(100) - .build(); - - RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()); - if (options.hasProxy()) { - configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + @Override + public void start() { + if (running) { + throw new IllegalStateException("Session already running"); } - requestConfig = configBuilder.setSocketTimeout(SOCKET_TIMEOUT) - .setConnectTimeout(SOCKET_TIMEOUT) - .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); - - readerThread = new ReaderThread(); - readerThread.setName(callback.getBotUsername() + " Telegram Connection"); + running = true; + if (readerThread == null || readerThread.isInterrupted()) { + readerThread = new ReaderThread(); + readerThread.setName(callback.getBotUsername() + " Telegram Connection"); + } readerThread.start(); - handlerThread = new HandlerThread(); - handlerThread.setName(callback.getBotUsername() + " Telegram Executor"); + if (handlerThread == null || handlerThread.isInterrupted()) { + handlerThread = new HandlerThread(); + handlerThread.setName(callback.getBotUsername() + " Telegram Executor"); + } handlerThread.start(); } + @Override public void close() { running = false; if (readerThread != null) { @@ -85,20 +90,68 @@ public class BotSession { if (handlerThread != null) { handlerThread.interrupt(); } - if (httpclient != null) { - try { - httpclient.close(); - httpclient = null; - } catch (IOException e) { - BotLogger.severe(LOGTAG, e); - } - } if (callback != null) { callback.onClosing(); } } - private class ReaderThread extends Thread { + @Override + public void setOptions(BotOptions options) { + if (this.options != null) { + throw new InvalidParameterException("BotOptions has already been set"); + } + this.options = (DefaultBotOptions) options; + } + + @Override + public void setToken(String token) { + if (this.token != null) { + throw new InvalidParameterException("Token has already been set"); + } + this.token = token; + } + + @Override + public void setCallback(LongPollingBot callback) { + if (this.callback != null) { + throw new InvalidParameterException("Callback has already been set"); + } + this.callback = callback; + } + + @Override + public boolean isRunning() { + return running; + } + + private class ReaderThread extends Thread implements UpdatesReader { + private CloseableHttpClient httpclient; + private RequestConfig requestConfig; + + @Override + public synchronized void start() { + super.start(); + + httpclient = HttpClientBuilder.create() + .setSSLHostnameVerifier(new NoopHostnameVerifier()) + .setConnectionTimeToLive(70, TimeUnit.SECONDS) + .setMaxConnTotal(100) + .build(); + + requestConfig = options.getRequestConfig(); + } + + @Override + public void interrupt() { + if (httpclient != null) { + try { + httpclient.close(); + } catch (IOException e) { + BotLogger.warn(LOGTAG, e); + } + } + super.interrupt(); + } @Override public void run() { @@ -107,42 +160,40 @@ public class BotSession { try { GetUpdates request = new GetUpdates(); request.setLimit(100); - request.setTimeout(Constants.GETUPDATESTIMEOUT); + request.setTimeout(ApiConstants.GETUPDATES_TIMEOUT); request.setOffset(lastReceivedUpdate + 1); - String url = Constants.BASEURL + token + "/" + GetUpdates.PATH; + String url = ApiConstants.BASE_URL + token + "/" + GetUpdates.PATH; //http client HttpPost httpPost = new HttpPost(url); httpPost.addHeader("charset", StandardCharsets.UTF_8.name()); httpPost.setConfig(requestConfig); - httpPost.setEntity(new StringEntity(request.toJson().toString(), ContentType.APPLICATION_JSON)); + httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(request), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httpPost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); try { - JSONObject jsonObject = new JSONObject(responseContent); - if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiRequestException("Error getting updates", jsonObject); - } - JSONArray jsonArray = jsonObject.getJSONArray(Constants.RESPONSEFIELDRESULT); - if (jsonArray.length() != 0) { - for (int i = 0; i < jsonArray.length(); i++) { - Update update = new Update(jsonArray.getJSONObject(i)); - if (update.getUpdateId() > lastReceivedUpdate) { - lastReceivedUpdate = update.getUpdateId(); - receivedUpdates.addFirst(update); - } + List updates = request.deserializeResponse(responseContent); + + if (updates.isEmpty()) { + synchronized (this) { + this.wait(500); } + } else { + updates.removeIf(x -> x.getUpdateId() < lastReceivedUpdate); + lastReceivedUpdate = updates.parallelStream() + .map( + Update::getUpdateId) + .max(Integer::compareTo) + .orElse(0); + receivedUpdates.addAll(updates); + synchronized (receivedUpdates) { receivedUpdates.notifyAll(); } - } else { - synchronized (this) { - this.wait(500); - } } - } catch (JSONException e) { + }catch (JSONException e) { BotLogger.severe(responseContent, LOGTAG, e); } } catch (InvalidObjectException | TelegramApiRequestException e) { @@ -171,7 +222,7 @@ public class BotSession { } } - private class HandlerThread extends Thread { + private class HandlerThread extends Thread implements UpdatesHandler { @Override public void run() { setPriority(Thread.MIN_PRIORITY); diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java similarity index 70% rename from src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java rename to telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java index 464a4c13..0b9a26f4 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.updatesreceivers; -import com.sun.jersey.api.json.JSONConfiguration; +import com.google.inject.Inject; + import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.ssl.SSLContextConfigurator; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; @@ -8,7 +9,8 @@ import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.telegram.telegrambots.exceptions.TelegramApiRequestException; -import org.telegram.telegrambots.bots.ITelegramWebhookBot; +import org.telegram.telegrambots.generics.Webhook; +import org.telegram.telegrambots.generics.WebhookBot; import java.io.File; import java.io.IOException; @@ -20,22 +22,29 @@ import java.net.URI; * @brief Webhook to receive updates * @date 20 of June of 2015 */ -public class Webhook { - private final String KEYSTORE_SERVER_FILE; - private final String KEYSTORE_SERVER_PWD; +public class DefaultWebhook implements Webhook { + private String keystoreServerFile; + private String keystoreServerPwd; + private String internalUrl; private final RestApi restApi; - private final String internalUrl; - public Webhook(String keyStore, String keyStorePassword, String internalUrl) throws TelegramApiRequestException { - this.KEYSTORE_SERVER_FILE = keyStore; - this.KEYSTORE_SERVER_PWD = keyStorePassword; - validateServerKeystoreFile(keyStore); - this.internalUrl = internalUrl; + @Inject + public DefaultWebhook() throws TelegramApiRequestException { this.restApi = new RestApi(); } - public void registerWebhook(ITelegramWebhookBot callback) { + public void setInternalUrl(String internalUrl) { + this.internalUrl = internalUrl; + } + + public void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiRequestException { + this.keystoreServerFile = keyStore; + this.keystoreServerPwd = keyStorePassword; + validateServerKeystoreFile(keyStore); + } + + public void registerWebhook(WebhookBot callback) { restApi.registerCallback(callback); } @@ -43,13 +52,12 @@ public class Webhook { SSLContextConfigurator sslContext = new SSLContextConfigurator(); // set up security context - sslContext.setKeyStoreFile(KEYSTORE_SERVER_FILE); // contains server keypair - sslContext.setKeyStorePass(KEYSTORE_SERVER_PWD); + sslContext.setKeyStoreFile(keystoreServerFile); // contains server keypair + sslContext.setKeyStorePass(keystoreServerPwd); ResourceConfig rc = new ResourceConfig(); rc.register(restApi); rc.register(JacksonFeature.class); - rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true); final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer( getBaseURI(), rc, diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java similarity index 59% rename from src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java rename to telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java index 07748e4a..0bea565b 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java @@ -1,7 +1,10 @@ package org.telegram.telegrambots.updatesreceivers; +import org.telegram.telegrambots.api.methods.BotApiMethod; import org.telegram.telegrambots.api.objects.Update; -import org.telegram.telegrambots.bots.ITelegramWebhookBot; +import org.telegram.telegrambots.exceptions.TelegramApiValidationException; +import org.telegram.telegrambots.generics.WebhookBot; +import org.telegram.telegrambots.logging.BotLogger; import java.util.concurrent.ConcurrentHashMap; @@ -23,12 +26,12 @@ import javax.ws.rs.core.Response; @Path("callback") public class RestApi { - private final ConcurrentHashMap callbacks = new ConcurrentHashMap<>(); + private final ConcurrentHashMap callbacks = new ConcurrentHashMap<>(); public RestApi() { } - public void registerCallback(ITelegramWebhookBot callback) { + public void registerCallback(WebhookBot callback) { if (!callbacks.containsKey(callback.getBotPath())) { callbacks.put(callback.getBotPath(), callback); } @@ -40,9 +43,19 @@ public class RestApi { @Produces(MediaType.APPLICATION_JSON) public Response updateReceived(@PathParam("botPath") String botPath, Update update) { if (callbacks.containsKey(botPath)) { - return Response.ok(this.callbacks.get(botPath).onWebhookUpdateReceived(update)).build(); + try { + BotApiMethod response = callbacks.get(botPath).onWebhookUpdateReceived(update); + if (response != null) { + response.validate(); + } + return Response.ok(response).build(); + } catch (TelegramApiValidationException e) { + BotLogger.severe("RESTAPI", e); + return Response.serverError().build(); + } } - return Response.ok().build(); + + return Response.status(Response.Status.NOT_FOUND).build(); } @GET diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/BotApiMethodHelperFactory.java b/telegrambots/src/test/java/org/telegram/telegrambots/BotApiMethodHelperFactory.java new file mode 100644 index 00000000..19a2aadc --- /dev/null +++ b/telegrambots/src/test/java/org/telegram/telegrambots/BotApiMethodHelperFactory.java @@ -0,0 +1,292 @@ +package org.telegram.telegrambots; + +import org.telegram.telegrambots.api.methods.ActionType; +import org.telegram.telegrambots.api.methods.AnswerCallbackQuery; +import org.telegram.telegrambots.api.methods.AnswerInlineQuery; +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.methods.ForwardMessage; +import org.telegram.telegrambots.api.methods.GetFile; +import org.telegram.telegrambots.api.methods.GetMe; +import org.telegram.telegrambots.api.methods.GetUserProfilePhotos; +import org.telegram.telegrambots.api.methods.ParseMode; +import org.telegram.telegrambots.api.methods.games.GetGameHighScores; +import org.telegram.telegrambots.api.methods.games.SetGameScore; +import org.telegram.telegrambots.api.methods.groupadministration.GetChat; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatAdministrators; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatMember; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatMemberCount; +import org.telegram.telegrambots.api.methods.groupadministration.KickChatMember; +import org.telegram.telegrambots.api.methods.groupadministration.LeaveChat; +import org.telegram.telegrambots.api.methods.groupadministration.UnbanChatMember; +import org.telegram.telegrambots.api.methods.send.SendChatAction; +import org.telegram.telegrambots.api.methods.send.SendContact; +import org.telegram.telegrambots.api.methods.send.SendGame; +import org.telegram.telegrambots.api.methods.send.SendLocation; +import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.api.methods.send.SendVenue; +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; +import org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent.InputMessageContent; +import org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent.InputTextMessageContent; +import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult; +import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResultArticle; +import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResultPhoto; +import org.telegram.telegrambots.api.objects.replykeyboard.ForceReplyKeyboard; +import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup; +import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton; +import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardButton; +import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 02 of November of 2016 + */ +public final class BotApiMethodHelperFactory { + private BotApiMethodHelperFactory() { + } + + public static BotApiMethod getSendMessage() { + return new SendMessage() + .setChatId("@test") + .setText("Hithere") + .setReplyToMessageId(12) + .setParseMode(ParseMode.HTML) + .setReplyMarkup(new ForceReplyKeyboard()); + } + + public static BotApiMethod getAnswerCallbackQuery() { + return new AnswerCallbackQuery() + .setCallbackQueryId("id") + .setText("text") + .setShowAlert(true); + } + + public static BotApiMethod getAnswerInlineQuery() { + return new AnswerInlineQuery() + .setInlineQueryId("id") + .setPersonal(true) + .setResults(getInlineQueryResultArticle(), getInlineQueryResultPhoto()) + .setCacheTime(100) + .setNextOffset("3") + .setSwitchPmParameter("PmParameter") + .setSwitchPmText("pmText"); + } + + public static BotApiMethod getEditMessageCaption() { + return new EditMessageCaption() + .setChatId("ChatId") + .setMessageId(1) + .setCaption("Caption") + .setReplyMarkup(getInlineKeyboardMarkup()); + } + + + public static BotApiMethod getEditMessageText() { + return new EditMessageText() + .setChatId("ChatId") + .setMessageId(1) + .setText("Text") + .setParseMode(ParseMode.MARKDOWN) + .setReplyMarkup(getInlineKeyboardMarkup()); + } + + public static BotApiMethod getEditMessageReplyMarkup() { + return new EditMessageReplyMarkup() + .setInlineMessageId("12345") + .setReplyMarkup(getInlineKeyboardMarkup()); + } + + public static BotApiMethod getForwardMessage() { + return new ForwardMessage() + .setFromChatId("From") + .setChatId("To") + .setMessageId(15) + .disableNotification(); + } + + public static BotApiMethod getGetChat() { + return new GetChat() + .setChatId("12345"); + } + + public static BotApiMethod getChatAdministrators() { + return new GetChatAdministrators() + .setChatId("12345"); + } + + public static BotApiMethod getChatMember() { + return new GetChatMember() + .setChatId("12345") + .setUserId(98765); + } + + public static BotApiMethod getChatMemberCount() { + return new GetChatMemberCount() + .setChatId("12345"); + } + + public static BotApiMethod getGetFile() { + return new GetFile() + .setFileId("FileId"); + } + + public static BotApiMethod getGetGameHighScores() { + return new GetGameHighScores() + .setChatId("12345") + .setMessageId(67890) + .setUserId(98765); + } + + public static BotApiMethod getGetMe() { + return new GetMe(); + } + + public static BotApiMethod getGetUserProfilePhotos() { + return new GetUserProfilePhotos() + .setUserId(98765) + .setLimit(10) + .setOffset(3); + } + + public static BotApiMethod getGetWebhookInfo() { + return new GetWebhookInfo(); + } + + public static BotApiMethod getKickChatMember() { + return new KickChatMember() + .setChatId("12345") + .setUserId(98765); + } + + public static BotApiMethod getLeaveChat() { + return new LeaveChat() + .setChatId("12345"); + } + + public static BotApiMethod getSendChatAction() { + return new SendChatAction() + .setChatId("12345") + .setAction(ActionType.RECORDVIDEO); + } + + public static BotApiMethod getSendContact() { + return new SendContact() + .setChatId("12345") + .setFirstName("First Name") + .setLastName("Last Name") + .setPhoneNumber("123456789") + .setReplyMarkup(getKeyboardMarkup()) + .setReplyToMessageId(54); + } + + private static ReplyKeyboard getKeyboardMarkup() { + ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); + keyboardMarkup.setResizeKeyboard(true); + keyboardMarkup.setOneTimeKeyboad(true); + keyboardMarkup.setSelective(true); + List keyboard = new ArrayList<>(); + KeyboardRow row = new KeyboardRow(); + KeyboardButton button = new KeyboardButton(); + button.setText("Button1"); + button.setRequestContact(true); + row.add(button); + keyboard.add(row); + keyboardMarkup.setKeyboard(keyboard); + return keyboardMarkup; + } + + private static InlineQueryResult getInlineQueryResultArticle() { + return new InlineQueryResultArticle() + .setId("0") + .setTitle("Title") + .setUrl("Url") + .setHideUrl(false) + .setDescription("Description") + .setThumbUrl("ThumbUrl") + .setThumbWidth(10) + .setThumbHeight(20) + .setInputMessageContent(getInputMessageContent()) + .setReplyMarkup(getInlineKeyboardMarkup()); + } + + private static InlineQueryResult getInlineQueryResultPhoto() { + return new InlineQueryResultPhoto() + .setId("1") + .setPhotoUrl("PhotoUrl") + .setPhotoWidth(10) + .setPhotoHeight(20) + .setMimeType("image/jpg") + .setThumbUrl("ThumbUrl") + .setTitle("Title") + .setDescription("Description") + .setCaption("Caption") + .setInputMessageContent(getInputMessageContent()) + .setReplyMarkup(getInlineKeyboardMarkup()); + } + + private static InputMessageContent getInputMessageContent() { + return new InputTextMessageContent() + .setMessageText("Text") + .setParseMode(ParseMode.MARKDOWN); + } + + private static InlineKeyboardMarkup getInlineKeyboardMarkup() { + InlineKeyboardButton button = new InlineKeyboardButton() + .setText("Button1") + .setCallbackData("Callback"); + List row = new ArrayList<>(); + row.add(button); + List> keyboard = new ArrayList<>(); + keyboard.add(row); + return new InlineKeyboardMarkup() + .setKeyboard(keyboard); + } + + public static BotApiMethod getSendGame() { + return new SendGame() + .setChatId("12345") + .setGameShortName("MyGame"); + } + + public static BotApiMethod getSendLocation() { + return new SendLocation() + .setChatId("12345") + .setLatitude(12.5F) + .setLongitude(21.5F) + .setReplyToMessageId(53); + } + + public static BotApiMethod getSendVenue() { + return new SendVenue() + .setChatId("12345") + .setLatitude(12.5F) + .setLongitude(21.5F) + .setReplyToMessageId(53) + .setTitle("Venue Title") + .setAddress("Address") + .setFoursquareId("FourId"); + } + + public static BotApiMethod getSetGameScore() { + return new SetGameScore() + .setInlineMessageId("12345") + .setEditMessage(true) + .setScore(12) + .setUserId(98765); + } + + public static BotApiMethod getUnbanChatMember() { + return new UnbanChatMember() + .setChatId("12345") + .setUserId(98765); + } +} diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/Fakes/FakeWebhook.java b/telegrambots/src/test/java/org/telegram/telegrambots/Fakes/FakeWebhook.java new file mode 100644 index 00000000..cade79fc --- /dev/null +++ b/telegrambots/src/test/java/org/telegram/telegrambots/Fakes/FakeWebhook.java @@ -0,0 +1,45 @@ +package org.telegram.telegrambots.Fakes; + +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.generics.WebhookBot; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 01 of November of 2016 + */ +public class FakeWebhook implements WebhookBot { + private BotApiMethod returnValue; + + public void setReturnValue(BotApiMethod returnValue) { + this.returnValue = returnValue; + } + + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + return returnValue; + } + + @Override + public String getBotUsername() { + return null; + } + + @Override + public String getBotToken() { + return ""; + } + + @Override + public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { + + } + + @Override + public String getBotPath() { + return "testbot"; + } +} diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/TestDefaultBotSession.java b/telegrambots/src/test/java/org/telegram/telegrambots/TestDefaultBotSession.java new file mode 100644 index 00000000..fbaf53dc --- /dev/null +++ b/telegrambots/src/test/java/org/telegram/telegrambots/TestDefaultBotSession.java @@ -0,0 +1,18 @@ +package org.telegram.telegrambots; + +import org.junit.Assert; +import org.junit.Test; +import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 07 of November of 2016 + */ +public class TestDefaultBotSession { + @Test + public void TestDefaultBotSessionIsNotRunninWhenCreated() throws Exception { + Assert.assertFalse(new DefaultBotSession().isRunning()); + } +} diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/TestRestApi.java b/telegrambots/src/test/java/org/telegram/telegrambots/TestRestApi.java new file mode 100644 index 00000000..24e9e8b1 --- /dev/null +++ b/telegrambots/src/test/java/org/telegram/telegrambots/TestRestApi.java @@ -0,0 +1,454 @@ +package org.telegram.telegrambots; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; +import org.junit.Test; +import org.telegram.telegrambots.Fakes.FakeWebhook; +import org.telegram.telegrambots.api.methods.AnswerCallbackQuery; +import org.telegram.telegrambots.api.methods.AnswerInlineQuery; +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.methods.ForwardMessage; +import org.telegram.telegrambots.api.methods.GetFile; +import org.telegram.telegrambots.api.methods.GetMe; +import org.telegram.telegrambots.api.methods.GetUserProfilePhotos; +import org.telegram.telegrambots.api.methods.games.GetGameHighScores; +import org.telegram.telegrambots.api.methods.games.SetGameScore; +import org.telegram.telegrambots.api.methods.groupadministration.GetChat; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatAdministrators; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatMember; +import org.telegram.telegrambots.api.methods.groupadministration.GetChatMemberCount; +import org.telegram.telegrambots.api.methods.groupadministration.KickChatMember; +import org.telegram.telegrambots.api.methods.groupadministration.LeaveChat; +import org.telegram.telegrambots.api.methods.groupadministration.UnbanChatMember; +import org.telegram.telegrambots.api.methods.send.SendChatAction; +import org.telegram.telegrambots.api.methods.send.SendContact; +import org.telegram.telegrambots.api.methods.send.SendGame; +import org.telegram.telegrambots.api.methods.send.SendLocation; +import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.api.methods.send.SendVenue; +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; +import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.updatesreceivers.RestApi; + +import java.io.IOException; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief TODO + * @date 01 of November of 2016 + */ +public class TestRestApi extends JerseyTest { + + private FakeWebhook webhookBot = new FakeWebhook(); + private RestApi restApi; + + @Override + protected Application configure() { + restApi = new RestApi(); + return new ResourceConfig().register(restApi).register(JacksonFeature.class); + } + + @Override + @Before + public void setUp() throws Exception { + restApi.registerCallback(webhookBot); + super.setUp(); + } + + @Test + public void TestSendMessage() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendMessage()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SendMessage.class); + assertEquals("{\"chat_id\":\"@test\",\"text\":\"Hithere\",\"parse_mode\":\"html\",\"reply_to_message_id\":12,\"reply_markup\":{\"@class\":\"org.telegram.telegrambots.api.objects.replykeyboard.ForceReplyKeyboard\",\"force_reply\":true},\"method\":\"sendmessage\"}", map(result)); + } + + @Test + public void TestAnswerCallbackQuery() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getAnswerCallbackQuery()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, AnswerCallbackQuery.class); + + assertEquals("{\"callback_query_id\":\"id\",\"text\":\"text\",\"show_alert\":true,\"method\":\"answercallbackquery\"}", map(result)); + } + + @Test + public void TestAnswerInlineQuery() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getAnswerInlineQuery()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, AnswerInlineQuery.class); + + assertEquals("{\"inline_query_id\":\"id\",\"results\":[{\"@class\":\"org." + + "telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResultArticle\"," + + "\"id\":\"0\",\"title\":\"Title\",\"input_message_content\":{\"@class\":\"org." + + "telegram.telegrambots.api.objects.inlinequery.inputmessagecontent." + + "InputTextMessageContent\",\"message_text\":\"Text\",\"parse_mode\":\"Markdown\"}," + + "\"reply_markup\":{\"@class\":\"org.telegram.telegrambots.api.objects.replykeyboard" + + ".InlineKeyboardMarkup\",\"inline_keyboard\":[[{\"@class\":\"org.telegram." + + "telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton\",\"text\":" + + "\"Button1\",\"callback_data\":\"Callback\"}]]},\"url\":\"Url\",\"hide_url\":false," + + "\"description\":\"Description\",\"thumb_url\":\"ThumbUrl\",\"thumb_width\":10," + + "\"thumb_height\":20},{\"@class\":\"org.telegram.telegrambots.api.objects." + + "inlinequery.result.InlineQueryResultPhoto\",\"id\":\"1\",\"photo_url\":\"PhotoUrl" + + "\",\"mime_type\":\"image/jpg\",\"photo_width\":10,\"photo_height\":20,\"thumb_url" + + "\":\"ThumbUrl\",\"title\":\"Title\",\"description\":\"Description\",\"caption\":" + + "\"Caption\",\"input_message_content\":{\"@class\":\"org.telegram.telegrambots." + + "api.objects.inlinequery.inputmessagecontent.InputTextMessageContent\",\"" + + "message_text\":\"Text\",\"parse_mode\":\"Markdown\"},\"reply_markup\":{\"@class\":" + + "\"org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup\"," + + "\"inline_keyboard\":[[{\"@class\":\"org.telegram.telegrambots.api.objects." + + "replykeyboard.buttons.InlineKeyboardButton\",\"text\":\"Button1\"," + + "\"callback_data\":\"Callback\"}]]}}],\"cache_time\":100,\"is_personal\":true," + + "\"next_offset\":\"3\",\"switch_pm_text\":\"pmText\",\"switch_pm_parameter\":" + + "\"PmParameter\",\"method\":\"answerInlineQuery\"}", map(result)); + } + + @Test + public void TestEditMessageCaption() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getEditMessageCaption()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, EditMessageCaption.class); + + assertEquals("{\"chat_id\":\"ChatId\",\"message_id\":1,\"caption\":\"Caption\"," + + "\"reply_markup\":{\"@class\":\"org.telegram.telegrambots.api.objects.replykeyboard" + + ".InlineKeyboardMarkup\",\"inline_keyboard\":[[{\"@class\":\"org.telegram." + + "telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton\"," + + "\"text\":\"Button1\",\"callback_data\":\"Callback\"}]]},\"method\":" + + "\"editmessagecaption\"}", map(result)); + } + + @Test + public void TestEditMessageReplyMarkup() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getEditMessageReplyMarkup()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, EditMessageReplyMarkup.class); + + assertEquals("{\"inline_message_id\":\"12345\",\"reply_markup\":{\"@class\":\"org" + + ".telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup\"," + + "\"inline_keyboard\":[[{\"@class\":\"org.telegram.telegrambots.api.objects." + + "replykeyboard.buttons.InlineKeyboardButton\",\"text\":\"Button1\"," + + "\"callback_data\":\"Callback\"}]]},\"method\":\"editmessagereplymarkup\"}", + map(result)); + } + + @Test + public void TestEditMessageText() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getEditMessageText()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, EditMessageText.class); + + assertEquals("{\"chat_id\":\"ChatId\",\"message_id\":1,\"text\":\"Text\"," + + "\"parse_mode\":\"Markdown\",\"reply_markup\":{\"@class\":\"org.telegram." + + "telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup\",\"" + + "inline_keyboard\":[[{\"@class\":\"org.telegram.telegrambots.api.objects." + + "replykeyboard.buttons.InlineKeyboardButton\",\"text\":\"Button1\",\"callback_data\"" + + ":\"Callback\"}]]},\"method\":\"editmessagetext\"}", map(result)); + } + + @Test + public void TestForwardMessage() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getForwardMessage()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, ForwardMessage.class); + + assertEquals("{\"chat_id\":\"To\",\"from_chat_id\":\"From\",\"message_id\":15," + + "\"disable_notification\":true,\"method\":\"forwardmessage\"}", map(result)); + } + + @Test + public void TestGetChat() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetChat()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetChat.class); + + assertEquals("{\"chat_id\":\"12345\",\"method\":\"getChat\"}", map(result)); + } + + @Test + public void TestGetChatAdministrators() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatAdministrators()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetChatAdministrators.class); + + assertEquals("{\"chat_id\":\"12345\",\"method\":\"getChatAdministrators\"}", map(result)); + } + + @Test + public void TestGetChatMember() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatMember()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetChatMember.class); + + assertEquals("{\"chat_id\":\"12345\",\"user_id\":98765,\"method\":\"getChatMember\"}", map(result)); + } + + @Test + public void TestGetChatMemberCount() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatMemberCount()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetChatMemberCount.class); + + assertEquals("{\"chat_id\":\"12345\",\"method\":\"getChatMembersCount\"}", map(result)); + } + + @Test + public void TestGetFile() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetFile()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetFile.class); + + assertEquals("{\"file_id\":\"FileId\",\"method\":\"getFile\"}", map(result)); + } + + @Test + public void TestGetGameHighScores() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetGameHighScores()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetGameHighScores.class); + + assertEquals("{\"chat_id\":\"12345\",\"message_id\":67890,\"user_id\":98765,\"method\":\"getGameHighScores\"}", map(result)); + } + + @Test + public void TestGetMe() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetMe()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetMe.class); + + assertEquals("{\"method\":\"getme\"}", map(result)); + } + + @Test + public void TestGetUserProfilePhotos() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetUserProfilePhotos()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetUserProfilePhotos.class); + + assertEquals("{\"user_id\":98765,\"offset\":3,\"limit\":10,\"method\":\"getuserprofilephotos\"}", map(result)); + } + + @Test + public void TestGetWebhookInfo() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetWebhookInfo()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, GetWebhookInfo.class); + + assertEquals("{\"method\":\"getwebhookinfo\"}", map(result)); + } + + @Test + public void TestKickChatMember() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getKickChatMember()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, KickChatMember.class); + + assertEquals("{\"chat_id\":\"12345\",\"user_id\":98765,\"method\":\"kickchatmember\"}", map(result)); + } + + @Test + public void TestLeaveChat() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getLeaveChat()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, LeaveChat.class); + + assertEquals("{\"chat_id\":\"12345\",\"method\":\"leaveChat\"}", map(result)); + } + + @Test + public void TestSendChatAction() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendChatAction()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SendChatAction.class); + + assertEquals("{\"chat_id\":\"12345\",\"action\":\"record_video\",\"method\":\"sendChatAction\"}", map(result)); + } + + @Test + public void TestSendContact() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendContact()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SendContact.class); + + assertEquals("{\"chat_id\":\"12345\",\"phone_number\":\"123456789\",\"first_name\":\"First Name\",\"last_name\":\"Last Name\",\"reply_to_message_id\":54,\"reply_markup\":{\"@class\":\"org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup\",\"keyboard\":[[{\"@class\":\"org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardButton\",\"text\":\"Button1\",\"request_contact\":true}]],\"resize_keyboard\":true,\"one_time_keyboard\":true,\"selective\":true},\"method\":\"sendContact\"}", map(result)); + } + + @Test + public void TestSendGame() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendGame()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SendGame.class); + + assertEquals("{\"chat_id\":\"12345\",\"game_short_name\":\"MyGame\",\"method\":\"sendGame\"}", map(result)); + } + + @Test + public void TestSendLocation() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendLocation()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SendLocation.class); + + assertEquals("{\"chat_id\":\"12345\",\"latitude\":12.5,\"longitude\":21.5,\"reply_to_message_id\":53,\"method\":\"sendlocation\"}", map(result)); + } + + @Test + public void TestSendVenue() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendVenue()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SendVenue.class); + + assertEquals("{\"chat_id\":\"12345\",\"latitude\":12.5,\"longitude\":21.5,\"title\":\"Venue Title\",\"address\":\"Address\",\"foursquare_id\":\"FourId\",\"reply_to_message_id\":53,\"method\":\"sendVenue\"}", map(result)); + } + + @Test + public void TestSetGameScore() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getSetGameScore()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, SetGameScore.class); + + assertEquals("{\"inline_message_id\":\"12345\",\"edit_message\":true,\"user_id\":98765,\"score\":12,\"method\":\"setGameScore\"}", map(result)); + } + + @Test + public void TestUnbanChatMember() { + webhookBot.setReturnValue(BotApiMethodHelperFactory.getUnbanChatMember()); + + Entity entity = Entity.json(getUpdate()); + BotApiMethod result = + target("callback/testbot") + .request(MediaType.APPLICATION_JSON) + .post(entity, UnbanChatMember.class); + + assertEquals("{\"chat_id\":\"12345\",\"user_id\":98765,\"method\":\"unbanchatmember\"}", map(result)); + } + + private Update getUpdate() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.readValue("{\"update_id\": 10}", Update.class); + } catch (IOException e) { + return null; + } + } + + private String map(BotApiMethod method) { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(method); + } catch (JsonProcessingException e) { + fail("Failed to serialize"); + return null; + } + } +}