diff --git a/.github/workflows/build_java_docker.yml b/.github/workflows/build_java_docker.yml new file mode 100644 index 0000000..dd5f82a --- /dev/null +++ b/.github/workflows/build_java_docker.yml @@ -0,0 +1,53 @@ +# This is a basic workflow to help you get started with Actions + +name: CI + +# Controls when the workflow will run +on: + # Triggers the workflow on push or pull request events but only for the master branch + push: + pull_request: + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "build" + build: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' + - name: Build with Maven + run: mvn --batch-mode --update-snapshots verify + + - + name: Set up QEMU + uses: docker/setup-qemu-action@v1 + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + - + name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKER_USER }} + password: ${{ secrets.DOCKER_PASSWORD }} + - + name: Build and push + id: docker_build + uses: docker/build-push-action@v2 + with: + push: true + tags: amgamen/chatbot:latest \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3f862b6..e8bb6a1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,7 @@ /bin /build /out +/target/ +microStream.db/ +data/ +herthaehnchen_bot* diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..0396cec --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM eclipse-temurin:17.0.1_12-jdk-focal +LABEL maintainer="AMDev" + +RUN groupadd --system -g 1001 telegrambot && adduser --uid 1001 --gid 1001 --disabled-password --shell /bin/false telegrambot + +COPY --chown=telegrambot:telegrambot target/lib /opt/telegrambot/lib/ +COPY --chown=telegrambot:telegrambot target/java.telegrambots-0.9-FINAL.jar /opt/telegrambot/ +RUN chown telegrambot:telegrambot /opt/telegrambot +RUN chmod +x /opt/telegrambot/java.telegrambots-0.9-FINAL.jar +# Set the locale +RUN sed -i '/de_DE.UTF-8/s/^# //g' /etc/locale.gen && \ + locale-gen +ENV LANG de_DE.UTF-8 +ENV LANGUAGE de_DE:en +ENV LC_ALL de_DE.UTF-8 + +WORKDIR /opt/telegrambot/ + +USER telegrambot + +#CMD ["echo $UID"] + +ENTRYPOINT ["sh" , "-c", "java -cp java.telegrambots-0.9-FINAL.jar:./lib/* de.bigamgamen.java.telegrambots.hertlhendl.HertlHendlBot ${BOT_TOKEN}:${BOT_KEY} ${BOT_NAME} ${CREATOR_ID}"] \ No newline at end of file diff --git a/LICENSE.adoc b/LICENSE.adoc index a4d3799..a2fecaf 100644 --- a/LICENSE.adoc +++ b/LICENSE.adoc @@ -1,671 +1,56 @@ -[[gnu-affero-general-public-license]] -==== GNU AFFERO GENERAL PUBLIC LICENSE -Version 3, 19 November 2007 -Copyright (C) 2007 Free Software Foundation, Inc. https://fsf.org/ +Apache License -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. +Version 2.0, January 2004 -[[preamble]] -==== Preamble +http://www.apache.org/licenses/ -The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -The licenses for most software and other practical works are designed to -take away your freedom to share and change the works. By contrast, our -General Public Licenses are 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. +1. Definitions. -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. +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. -Developers that use our General Public Licenses protect your rights with -two steps: (1) assert copyright on the software, and (2) offer you this -License which gives you legal permission to copy, distribute and/or -modify the software. +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. -A secondary benefit of defending all users’ freedom is that improvements -made in alternate versions of the program, if they receive widespread -use, become available for other developers to incorporate. Many -developers of free software are heartened and encouraged by the -resulting cooperation. However, in the case of software used on network -servers, this result may fail to come about. The GNU General Public -License permits making a modified version and letting the public access -it on a server without ever releasing its source code to the public. +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. -The GNU Affero General Public License is designed specifically to ensure -that, in such cases, the modified source code becomes available to the -community. It requires the operator of a network server to provide the -source code of the modified version running there to the users of that -server. Therefore, public use of a modified version, on a publicly -accessible server, gives the public access to the source code of the -modified version. +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. -An older license, called the Affero General Public License and published -by Affero, was designed to accomplish similar goals. This is a different -license, not a version of the Affero GPL, but Affero has released a new -version of the Affero GPL which permits relicensing under this license. +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. -The precise terms and conditions for copying, distribution and -modification follow. +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. -[[terms-and-conditions]] -==== TERMS AND CONDITIONS +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). -[[definitions.]] -===== 0. Definitions. +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. -``This License'' refers to version 3 of the GNU Affero General Public -License. +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." -``Copyright'' also means copyright-like laws that apply to other kinds -of works, such as semiconductor masks. +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. -``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. +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. -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. +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. -A ``covered work'' means either the unmodified Program or a work based -on the Program. +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: -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. + You must give any other recipients of the Work or Derivative Works a copy of this License; and + You must cause any modified files to carry prominent notices stating that You changed the files; and + You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. -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. + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. -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. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. -[[source-code.]] -===== 1. Source Code. +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. -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. +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. -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. +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. -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. - -[[basic-permissions.]] -===== 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. - -[[protecting-users-legal-rights-from-anti-circumvention-law.]] -===== 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. - -[[conveying-verbatim-copies.]] -===== 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. - -[[conveying-modified-source-versions.]] -===== 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. -* a. 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''. -* a. 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. -* a. 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. - -[[conveying-non-source-forms.]] -===== 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. -* a. 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. -* a. 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. -* a. 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. -* a. 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. - -[[additional-terms.]] -===== 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 -* a. 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 -* a. 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 -* a. Limiting the use for publicity purposes of names of licensors or -authors of the material; or -* a. Declining to grant rights under trademark law for use of some -trade names, trademarks, or service marks; or -* a. 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. - -[[termination.]] -===== 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. - -[[acceptance-not-required-for-having-copies.]] -===== 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. - -[[automatic-licensing-of-downstream-recipients.]] -===== 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. - -[[patents.]] -===== 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. - -[[no-surrender-of-others-freedom.]] -===== 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. - -[[remote-network-interaction-use-with-the-gnu-general-public-license.]] -===== 13. Remote Network Interaction; Use with the GNU General Public License. - -Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - -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 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 work with which it -is combined will remain governed by version 3 of the GNU General Public -License. - -[[revised-versions-of-this-license.]] -===== 14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 Affero 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 -Affero 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 Affero 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. - -[[disclaimer-of-warranty.]] -===== 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. - -[[limitation-of-liability.]] -===== 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. - -[[interpretation-of-sections-15-and-16.]] -===== 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. +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS - -[[how-to-apply-these-terms-to-your-new-programs]] -==== 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. - -.... - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -.... - -Also add information on how to contact you by electronic and paper mail. - -If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a ``Source'' link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - -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 AGPL, see https://www.gnu.org/licenses/. diff --git a/README.adoc b/README.adoc index e1a9890..173bb03 100644 --- a/README.adoc +++ b/README.adoc @@ -1,26 +1,68 @@ -= Java & Telegram ChatBot Workshop += Telegram ChatBot For Order things in Small Groups, with a Microstream storing solution + ifdef::env-github[:outfilesuffix: .adoc] -image:https://travis-ci.org/chatbot-workshop/java-telegram-workshop.svg?branch=master["Build Status", link="https://travis-ci.org/chatbot-workshop/java-telegram-workshop"] -image:https://img.shields.io/badge/gitmoji-%20😜%20😍-FFDD67.svg["gitmoji", link="https://gitmoji.carloscuesta.me"] +== How to + +=== Developer how to use: + +Create your Ownbot : + https://github.com/chatbot-workshop/java-telegram-workshop/blob/master/WORKSHOP.adoc + +Start the Bot like this. + + java -cp java.telegrambots-0.9-FINAL.jar:./lib/* de.bigamgamen.java.telegrambots.hertlhendl.HertlHendlBot TOKEN bot_name CREATOR_ID + +Or test it with this bot: + @herthaehnchen_bot + + + +=== User how to use: + +type + /help +and choose an command. + +Usecase: Make an order: + + /neuebestellung + /bestellungenkeyboard + +choose a Button + + /bestellung 0 + +add article to order with Buttons + + /addposition 1/2-Hähnchen 0 + /addposition Krautsalat 0 + +Commit your order + + /commitorder 0 + + +=== Admin how to use: + + /adminoffnenebestellungen + -*This repository is part of the chat bot workshop with https://www.fihlon.ch/[Marcus Fihlon].* == Copyright and Licensing -Copyright (C) 2018 Marcus Fihlon +Copyright (C) 2020 Arne Meier -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -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 Affero General Public License for more details. + http://www.apache.org/licenses/LICENSE-2.0 -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. See the <> file for details. diff --git a/WORKSHOP.adoc b/WORKSHOP.adoc deleted file mode 100644 index a86dbb6..0000000 --- a/WORKSHOP.adoc +++ /dev/null @@ -1,801 +0,0 @@ -= Java & Telegram ChatBot Workshop - -Copyright (c) 2018 https://www.fihlon.ch/[Marcus Fihlon] - -== Prerequesites - -- Java 8 -- Java IDE -- You should be familiar with your IDE -- You need your own Telegram account -- You need Telegram installed on your mobile or desktop - -== Register - -Use Telegram to talk to the `BotFather` to register a new bot. Write down your bot username and your bot token. - -== Project setup - -For this workshop we use gradle. Please create a new gradle project using your IDE. I highly recommend to use the gradle application plugin to easily start you bot from the command line: - -```groovy -apply plugin: 'application' -mainClassName = 'ch.fihlon.workshop.chatbot.WorkshopBot' -``` - -Of course, you may have to modify the `mainClassName` according your package structure and bot name. To run your bot (while you follow this workshop), just run the following command on your commandline: - -```bash -./gradlew run -``` - -On Windows, you may have to replace `/` by `\`. - -== Getting started - -=== Dependencies - -To use the Telegram Bot API, please add the following dependency: - -```groovy -compile group: 'org.telegram', name: 'telegrambots', version: '4.3.1' -``` - -=== Create a bot class - -Create a class `GettingStartedBot` that extends `TelegramLongPollingBot` and add empty methods to satisfy the class contract: - -```java -public class GettingStartedBot extends TelegramLongPollingBot { - - @Override - public String getBotUsername() { - return null; - } - - @Override - public String getBotToken() { - return null; - } - - @Override - public void onUpdateReceived(final Update update) { - } - -} -``` - -=== Bot username - -The first method must return the username of your bot you wrote down while you registered your bot: - -```java -@Override -public String getBotUsername() { - return "MyWorkshopBot"; -} -``` - -=== Bot token - -As you might imagine, the second method has to return the token of your bot. The token is needed for identification, like a password, so keep it private and *do not* commit it to any registry: - -```java -@Override -public String getBotToken() { - return "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ"; -} -``` - -=== React on a message - -In the third method you write your code which will be executed when your bot receives a message. For our first example we will just send the same message back to the sender: - -```java -@Override -public void onUpdateReceived(final Update update) { - if (update.hasMessage() && update.getMessage().hasText()) { - final Long chatId = update.getMessage().getChatId(); - final String text = update.getMessage().getText(); - final SendMessage message = new SendMessage() - .setChatId(chatId) - .setText(text); - try { - execute(message); - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - } -} -``` - -This example should be quite easy to understand. First, we check if we have a message and it is a text message. Then we extract two values: - -. The `chatId`, which identifies a chat. We need this id, to send the answer to the correct person. Every chat has a unique id. We could save this id for later use and reply at any time. But here, we reply immediately. -. The text. This is just the text of the message, the bot received. - -To send an answer, we have to create a `SendMessage` method and set the `chatId` and the text, which should be send. Then we `excute` this method, which will send the message. Of course, there can happen a lot of errors (servers down, network failures etc), so have to do really good error handling like in the example above. - -=== Start your bot - -For our simple example, we just a good old `main` method. The start needs four steps: - -. We need a Telegram API context -. We need an instance of the Telegram API -. We need an instance of our bot -. We need to register our bot instance at Telegram - -```java -public static void main(final String[] args) throws TelegramApiRequestException { - ApiContextInitializer.init(); // 1 - final TelegramBotsApi api = new TelegramBotsApi(); // 2 - final GettingStartedBot bot = new GettingStartedBot(); // 3 - api.registerBot(bot); // 4 -} -``` - -=== Play with your bot - -Now, start your bot by running your `main` method. - -_Congratulations!_ - -== Thinking in Abilities - -// TODO describe the ability feature of the Telegram Bot API - -=== Dependencies - -To use the Telegram Bot Ability API, please add the following dependency: - -```groovy -compile group: 'org.telegram', name: 'telegrambots-abilities', version: '4.3.1' -``` - -=== Create a bot class - -Create a class `WorkshopBot` that extends `AbilityBot` and add a no argument constructor and empty methods to satisfy the class contract: - -```java -public class WorkshopBot extends AbilityBot { - - WorkshopBot() { - super(null, null); - } - - @Override - public int creatorId() { - return 0; - } -} -``` - -=== Bot token and username - -The easy part: Add the token and username of your bot as constants to your class and specify them in the super constructor call: - -```java -public class WorkshopBot extends AbilityBot { - - private static String BOT_TOKEN = "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - private static String BOT_USERNAME = "MyWorkshopBot"; - - WorkshopBot() { - super(BOT_TOKEN, BOT_USERNAME); - } - - … -} -``` - -=== Your Telegram ID - -AbilityBot forces a single implementation of creator ID. This ID corresponds to you, the bot developer. The bot needs to know its master since it has sensitive commands that only the master can use. So, if your Telegram ID Is 123456789, then add the following method: - -```java -private static int CREATOR_ID = 1234567890; - -@Override -public int creatorId() { - return CREATOR_ID; -} -``` - -If you do not know your Telegram ID, just start a chat to the `userinfobot`. - -=== Say hello - -Should be easy: Let's say hello. For creating an ability, we use the builder pattern: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability sayHelloWorld() { - return Ability - .builder() - .name("hello") // 1 - .info("says hello world") // 2 - .locality(ALL) // 3 - .privacy(PUBLIC) // 4 - .action(context -> silent.send("Hello world!", context.chatId())) // 5 - .build(); -} -``` - -. the name of the command -. a description of the command -. the location of the command (`ALL`, `USER`, `GROUP`) -. the privacy setting (`PUBLIC`, `GROUP_ADMIN`, `ADMIN`, `CREATOR`) -. the action to be executed - -=== Start your bot - -To start the ability bot we need to do exactly the same as with the bot, we created before: - -. We need a Telegram API context -. We need an instance of the Telegram API -. We need an instance of our bot -. We need to register our bot instance at Telegram - -```java -public static void main(final String[] args) throws TelegramApiRequestException { - ApiContextInitializer.init(); // 1 - final TelegramBotsApi api = new TelegramBotsApi(); // 2 - final WorkshopBot bot = new WorkshopBot(); // 3 - api.registerBot(bot); // 4 -} -``` - -=== Play with your bot - -Now, start your bot by running your `main` method and send the `/hello` command to your bot. - -_Congratulations!_ - -Wait! Since you've implemented an ability bot, you get factory abilities as well. Try: - -* `/commands` – Prints all commands supported by the bot. - This will essentially print `hello - says hello world`. Yes! This is the information we supplied to the ability. The bot prints the commands in the format accepted by `BotFather`. So, whenever you change, add or remove commands, you can simply send `/commands` to your bot and forward that message to `BotFather`. -* `/claim` – Claims this bot -* `/backup` – returns a backup of the bot database -* `/recover` – recovers the database -* `/promote @username` – promotes user to bot admin -* `/demote @username` – demotes bot admin to user -* `/ban @username` – bans the user from accessing your bot commands and features -* `/unban @username` – lifts the ban from the user - -== Replies - -A reply is AbilityBot's swiss army knife. It comes in two variants and is able to handle all possible use cases. - -=== Standalon Reply - -Standalone replies do not need abilities. Lets add one to our bot: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Reply replyToPhoto() { - return Reply.of( - update -> silent.send("Nice pic!", getChatId(update)), - Flag.PHOTO); -} -``` - -As you can see, you just provide a lambda function which consumes the update. In addition to the required lambda function, replies can have optional predicates. In our example we let the bot know, that we only want to reply to images. Take a look at the `Flag` enum. - -Wow, that was easy! How easy would it be to implement a `VoxxedDaysBucharestBot`, where you can send pictures which are automatically uploaded to a Google Drive (or similar) share? If you are a nerd and finish this workshop early, try to implement it… - -=== Ability Reply and own Predicates - -In exactly the same manner, you are able to attach replies to abilities. This way you can localize replies that relate to the same ability. - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability sayHi() { - return Ability - .builder() - .name("hi") - .info("says hi") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> { - final String firstName = context.user().getFirstName(); - silent.send("Hi, " + firstName, context.chatId()); - }) - .reply( - update -> silent.send("Wow, nice name!", update.getMessage().getChatId()), - TEXT, - update -> update.getMessage().getText().startsWith("/hi"), - isMarcus() - ) - .build(); -} - -private Predicate isMarcus() { - return update -> update.getMessage().getFrom().getFirstName().equalsIgnoreCase("Marcus"); -} -``` - -In this example you can see how easy it is to create and use your own predicates. Using predicates, you can implement all checks, so your logic keeps clean and can focus on action. - -== Database Handling - -If you use the ability bot, you have an integrated database. To persist the data, a file with the name of your bot is created in the working directory (depending on your IDE, usually project root folder). - -=== Persistent Counter - -Let's use it to implement a simple counter: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability counter() { - return Ability.builder() - .name("count") - .info("increments a counter per user") - .privacy(PUBLIC) - .locality(ALL) - .action(context -> { - final Map counterMap = db.getMap("COUNTERS"); - final int userId = context.user().getId(); - final Integer counter = counterMap.compute( - String.valueOf(userId), (id, count) -> count == null ? 1 : ++count); - final String message = String.format("%s, your count is now %d!", - context.user().getUserName(), counter); - silent.send(message, context.chatId()); - }) - .build(); -} -``` - -As you can see, the interface to the database is just a simple map. Cool, we can now implement actions that need persistence. - -=== Automatic Contacts - -The ability bot automatically stores basic user information of every user, who contacted your bot. So we have some kind of an automatically contact list. We can access this list very easy: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability contacts() { - return Ability.builder() - .name("contacts") - .info("lists all users who contacted this bot") - .privacy(PUBLIC) - .locality(ALL) - .action(context -> { - final Map usersMap = db.getMap("USERS"); - final String users = usersMap.values().stream().map(User::getUserName).collect(joining(", ")); - final String message = "The following users already contacted me: " + users; - silent.send(message, context.chatId()); - }) - .build(); -} -``` - -== Photos - -=== Receiving Photos - -The process of receiving a photo is not very intuitive. Maybe it will be improved in the future. Anyway, let's try to get the photo out of the message and store it to the filesystem. - -From Telegram we do not get the photo directly. Instead, we get a list of `PhotoSize` objects. A list? Yeas, the photo will be available in different sizes. If the sender sends a photo from his mobile device, it will be displayed in the chat history as a thumbnail. That's why one photo will end up in a list of `PhotoSize` objects. In our case, we want the original photo in the original size, so we sort that list by size and take the biggest one. - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Reply savePhoto() { - return Reply.of( - update -> { - final List photos = update.getMessage().getPhoto(); - final PhotoSize photoSize = photos.stream() - .max(Comparator.comparing(PhotoSize::getFileSize)) - .orElse(null); - if (photoSize != null) { - // TODO download the photo - silent.send("Yeah, I got it!", getChatId(update)); - } else { - silent.send("Houston, we have a problem!", getChatId(update)); - } - }, - Flag.PHOTO); - } -``` - -So far, so good. but there is still no photo, just a `PhotoSize` object. We have to actively download the photo in that size, we want, to reduce network traffic and server load. But to download a photo, we first need to get the file path of the photo. Sometimes photos already have a file path, sometimes not – then we have to ask Telegram for it. This is how we do that: - -```java -private String getFilePath(final PhotoSize photo) { - if (photo.hasFilePath()) { - return photo.getFilePath(); - } - final GetFile getFileMethod = new GetFile(); - getFileMethod.setFileId(photo.getFileId()); - try { - final org.telegram.telegrambots.meta.api.objects.File file = execute(getFileMethod); - return file.getFilePath(); - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - return null; -} -``` - -Be careful to use the correct `File` object! - -Using the file path we are now able to download the photo from Telegram. Luckily, this task is very easy: - -```java -private File downloadPhoto(final String filePath) { - try { - return downloadFile(filePath); - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - return null; -} -``` - -With these two helper methods we can now finish our `savePhoto` method: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Reply savePhoto() { - return Reply.of( - update -> { - final List photos = update.getMessage().getPhoto(); - final PhotoSize photoSize = photos.stream() - .max(Comparator.comparing(PhotoSize::getFileSize)) - .orElse(null); - if (photoSize != null) { - final String filePath = getFilePath(photoSize); - final File file = downloadPhoto(filePath); - System.out.println("Temporary file: " + file); - silent.send("Yeah, I got it!", getChatId(update)); - } else { - silent.send("Houston, we have a problem!", getChatId(update)); - } - }, - Flag.PHOTO); -} -``` - -Uff, done! Try it and send a photo to your bot! On the console you can see the temporary file on the bot host. Now you can easily continue and move it everywhere you like or implement some filter magic and send the photo back to the user. - -=== Sending Photos - -Compared to receiving a photo it is very easy to send a photo. There are three ways to do send a photo and all the three ways have the following four steps in common: - -. Create send method -. Set destination chat id -. Set the photo -. Send the photo - -==== Send Photo from URL - -In this example we implement a `/logo` command which will, difficult to guess, send a logo: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability sendLogo() { - return Ability - .builder() - .name("logo") - .info("send the logo") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> sendPhotoFromUrl("https://avatars3.githubusercontent.com/u/13538066?s=200&v=4", context.chatId())) - .build(); -} - -private void sendPhotoFromUrl(final String url, final Long chatId) { - final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 - sendPhotoRequest.setChatId(chatId); // 2 - sendPhotoRequest.setPhoto(url); // 3 - try { - execute(sendPhotoRequest); // 4 - } catch (final TelegramApiException e) { - e.printStackTrace(); - } -} -``` - -==== Send Photo from File ID - -This is especially useful, if your bot receives a photo and wants to forward it. The file id is on the `PhotoSize` object and the bot does not need to download the photo before it forwards (sends) the photo another user. - -To test this, we extend our previously written `savePhoto` method that it sends the received photo back to the sender by using the file id of the photo. First, the implementation of the `sendPhotoFromFileId`: - -```java -private void sendPhotoFromFileId(final String fileId, final Long chatId) { - final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 - sendPhotoRequest.setChatId(chatId); // 2 - sendPhotoRequest.setPhoto(fileId); // 3 - try { - execute(sendPhotoRequest); // 4 - } catch (final TelegramApiException e) { - e.printStackTrace(); - } -} -``` - -Here you can see the modified `savePhoto` method, we just added one line: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Reply savePhoto() { - return Reply.of( - update -> { - final List photos = update.getMessage().getPhoto(); - final PhotoSize photoSize = photos.stream() - .max(Comparator.comparing(PhotoSize::getFileSize)) - .orElse(null); - if (photoSize != null) { - final String filePath = getFilePath(photoSize); - final File file = downloadPhoto(filePath); - System.out.println("Temporary file: " + file); - silent.send("Yeah, I got it!", getChatId(update)); - sendPhotoFromFileId(photoSize.getFileId(), getChatId(update)); // here - } else { - silent.send("Houston, we have a problem!", getChatId(update)); - } - }, - Flag.PHOTO); -} -``` - -==== Upload and send a Photo - -This is so easy, you just need to specify a `File` object! The photo will be uploaded to Telegram and send to the user: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability sendIcon() { - return Ability - .builder() - .name("icon") - .info("send the icon") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> sendPhotoFromUpload("src/main/resources/chatbot.jpg", context.chatId())) - .build(); -} - -private void sendPhotoFromUpload(final String filePath, final Long chatId) { - final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 - sendPhotoRequest.setChatId(chatId); // 2 - sendPhotoRequest.setPhoto(new File(filePath)); // 3 - try { - execute(sendPhotoRequest); // 4 - } catch (final TelegramApiException e) { - e.printStackTrace(); - } -} -``` - -== Custom Keyboard (Buttons) - -To create a custom keyboard, we have to follow these four steps: - -. Create a `ReplyKeyboardMarkup` object -. Create the keyboard as a list of keyboard rows -. Add buttons to each row -. Activate the keyboard - -In the following example we create a custom keyboard with two rows and three buttons on each row. If the user presses one of these buttons, the text will be send to the bot. - -In our example we want to provide buttons for the actions of our bot so we use the command as button text: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability sendKeyboard() { - return Ability - .builder() - .name("keyboard") - .info("send a custom keyboard") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> { - final SendMessage message = new SendMessage(); - message.setChatId(context.chatId()); - message.setText("Enjoy this wonderful keyboard!"); - - final ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); - final List keyboard = new ArrayList<>(); - - // row 1 - KeyboardRow row = new KeyboardRow(); - row.add("/hello"); - row.add("/hi"); - row.add("/count"); - keyboard.add(row); - - // row 2 - row = new KeyboardRow(); - row.add("/contacts"); - row.add("/logo"); - row.add("/icon"); - keyboard.add(row); - - // activate the keyboard - keyboardMarkup.setKeyboard(keyboard); - message.setReplyMarkup(keyboardMarkup); - - silent.execute(message); - }) - .build(); -} -``` - -== Formatted Messages - -To send formatted messages, you can use Markdown syntax. As of today, Telegram supports only a small subset of markdown. To activate Markdown support for a message, use `sendMd(…)` instead of just `send(…)`. - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability format() { - return Ability - .builder() - .name("format") - .info("formats the message") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> { - silent.sendMd("You can make text *bold* or _italic_.", context.chatId()); - silent.sendMd("`This is code.`", context.chatId()); - silent.sendMd("```\nThis\nis\nmulti\nline\ncode.\n```", context.chatId()); - }) - .build(); -} -``` - -== Arguments - -Commands can have arguments. Usually arguments are separated by whitespace. You can, of course, get the message and parse the arguments yourself. But with the ability bot you can easily access the arguments: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability add() { - return Ability - .builder() - .name("add") - .info("adds to numbers") - .locality(ALL) - .privacy(PUBLIC) - .input(2) - .action(context -> { - final int a = Integer.parseInt(context.firstArg()); - final int b = Integer.parseInt(context.secondArg()); - final int sum = a + b; - silent.send(String.format("The sum of %d and %d is %d", a, b, sum), context.chatId()); - }) - .build(); -} -``` - -To automatically create error messages if the use has not specified the correct amount of arguments, you can configure the number of required arguments like in the example above: `.input(2)` - -== Default Abilities - -You can answer to non-command messages, too. That's what default abilities are for. Just specify an ability with the `DEFAULT` constant as command: - -```java -@SuppressWarnings({"unused", "WeakerAccess"}) -public Ability sayNo() { - return Ability.builder() - .name(DEFAULT) - .privacy(PUBLIC) - .locality(ALL) - .action(context -> silent.send("Sorry, I have no answer for you today.", context.chatId())) - .build(); -} -``` - -== Testing - -=== Dependencies - -Better late than never – let's talk about testing. For testing our bot we need the help of a mocking library. Please add the following dependencies to your project: - -```groovy -testCompile group: 'junit', name: 'junit', version: '4.12' -testCompile group: 'org.mockito', name: 'mockito-core', version: '2.28.2' -``` - -=== Prepare your Bot - -In some of our abilities we use a database connection. We need to add an additional constructor to be able to inject a database for the tests: - -```java -@VisibleForTesting -WorkshopBot(final DBContext db) { - super(BOT_TOKEN, BOT_USERNAME, db); -} -``` - -To prevent that the live system of Telegram is used, we need to inject mocks for the `MessageSender` and `SilentSender`. To be able to do this, we add the following two methods to our bot: - -```java -@VisibleForTesting -void setSender(final MessageSender sender) { - this.sender = sender; -} - -@VisibleForTesting -void setSilent(final SilentSender silent) { - this.silent = silent; -} -``` - -=== Prepare the Test - -. In some of our abilities we use a database connection. For the tests we create a separate database instance which will be deleted on JVM shutdown automatically. -. We create an instance of our bot and inject our test database into it. -. We need to mock the sender to prevent the use of the live Telegram API. -. We inject the sender into our bot. -. We create and inject the silent object into our bot. - - -```java -public class WorkshopBotTest { - - private WorkshopBot bot; - private DBContext db; - private MessageSender sender; - - @Before - public void setUp() { - db = MapDBContext.offlineInstance("test"); // 1 - bot = new WorkshopBot(db); // 2 - sender = mock(MessageSender.class); // 3 - bot.setSender(sender); // 4 - bot.setSilent(new SilentSender(sender)); // 5 - } - - @After - public void tearDown() { - db.clear(); - } - -} -``` - -=== Simple Test - -First, we take a very simple test case: Our "Hello World" example. The test for this ability would be: - -```java -private static final int USER_ID = 12345; -private static final long CHAT_ID = 12345L; - -@Test -public void sayHelloWorld() throws TelegramApiException { - final Update mockedUpdate = mock(Update.class); - final User user = new User(USER_ID, "Foo", false, "Bar", "foobar42", "en"); - final MessageContext context = MessageContext.newContext(mockedUpdate, user, CHAT_ID); - - bot.sayHelloWorld().action().accept(context); - - final SendMessage message = new SendMessage(); - message.setChatId(CHAT_ID); - message.setText("Hello world!"); - verify(sender, times(1)).execute(message); -} -``` - -In the first code block we mock the `Update` class, which is used by the context object. Then we create an `EndUser` for our test case and create a new context object with all needed information. - -The one line in the middle block executes our bot ability. - -The last block does the assertions. In this example we check, that the message was send exactly once to the correct chat. Therefore we need a message object with the text and chat id for the `verify` method of Mockito. - -== Additional Exercises - -. Instead of adding just text to the `KeyboardRow` object, try to use `KeyboardButton` objects. -. Add a button to send the users phone number to the bot. -. Add a button to send the current location of the user to the bot. -. Reply to the phone number and location with a confirmation message. -. In addition to using the `ReplyKeyboardMarkup`, take a look at `ReplyKeyboardHide`, `ForceReply` and `InlineKeyboardMarkup` and try to use them. -. Extend the `/add` command to accept an unlimited number of numbers. -. Write tests for all abilities of your bot. -. Refactor your bot into smaller classes (create smaller bots which focus on one topic) -. Tell the `BotFather` which commands are accepted by your bot. -. Refactor your bot to always inject a database. Specify the name of the database file. -. Refactor your bot to remove the hard coded username and token to avoid to accidentally commit them. -. Provide feedback to me about this workshop. diff --git a/build.gradle b/build.gradle deleted file mode 100644 index f92bcb2..0000000 --- a/build.gradle +++ /dev/null @@ -1,39 +0,0 @@ -/* - * ChatBot Workshop - * Copyright (C) 2018 Marcus Fihlon - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -group 'ch.fihlon.workshop.chatbot' -version '1.0-SNAPSHOT' - -apply plugin: 'java' -apply plugin: 'application' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -mainClassName = 'ch.fihlon.workshop.chatbot.WorkshopBot' - -repositories { - mavenCentral() -} - -dependencies { - compile group: 'org.telegram', name: 'telegrambots', version: '4.3.1' - compile group: 'org.telegram', name: 'telegrambots-abilities', version: '4.3.1' - testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile group: 'org.mockito', name: 'mockito-core', version: '2.28.2' -} diff --git a/config/formatter.xml b/config/formatter.xml new file mode 100644 index 0000000..7b3a115 --- /dev/null +++ b/config/formatter.xml @@ -0,0 +1,390 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/create_volume.sh b/create_volume.sh new file mode 100644 index 0000000..a76d241 --- /dev/null +++ b/create_volume.sh @@ -0,0 +1,2 @@ +docker volume create chatbotvol +chown 1001:1001 /var/lib/docker/volumes/chatbotvol/_data \ No newline at end of file diff --git a/env.list b/env.list new file mode 100644 index 0000000..4dde0c3 --- /dev/null +++ b/env.list @@ -0,0 +1,4 @@ +BOT_TOKEN= +BOT_KEY= +BOT_NAME= +CREATOR_ID= \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index b90af11..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1c3ef56..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Thu Mar 22 09:05:31 CET 2018 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-all.zip diff --git a/gradlew b/gradlew deleted file mode 100755 index cccdd3d..0000000 --- a/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index f955316..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/multiarch.txt b/multiarch.txt new file mode 100644 index 0000000..09d4e23 --- /dev/null +++ b/multiarch.txt @@ -0,0 +1,3 @@ +https://www.docker.com/blog/multi-arch-build-and-images-the-simple-way/ +https://github.com/docker/buildx +docker buildx build --push --platform linux/arm/v7,linux/arm64/v8,linux/amd64 --tag amgamen/chatbot:0.9 . \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f667ca4 --- /dev/null +++ b/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + + de.bigamgamen + java.telegrambots + 0.9-FINAL + + + UTF-8 + 11 + 11 + 5.4.0 + + + + + microstream-releases + https://repo.microstream.one/repository/maven-public/ + + + + + + org.telegram + telegrambots + ${telegram.bot.version} + + + org.telegram + telegrambots-abilities + ${telegram.bot.version} + + + + one.microstream + storage.embedded + 04.00.00-MS-GA + + + one.microstream + storage.embedded.configuration + 04.00.00-MS-GA + + + org.apache.commons + commons-lang3 + 3.11 + + + + + + + + org.mockito + mockito-core + 2.28.2 + test + + + org.slf4j + slf4j-api + 1.7.30 + + + org.slf4j + slf4j-simple + 1.7.30 + + + + org.apache.logging.log4j + log4j-api + 2.13.0 + + + + + org.apache.logging.log4j + log4j-core + 2.13.0 + + + junit + junit + 4.11 + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + package + + copy-dependencies + + + ${basedir}/target/lib + false + true + true + + + + + + + + + + \ No newline at end of file diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index d7a3605..0000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'java-telegram-workshop' diff --git a/src/main/java/ch/fihlon/workshop/chatbot/GettingStartedBot.java b/src/main/java/ch/fihlon/workshop/chatbot/GettingStartedBot.java deleted file mode 100644 index 33e348a..0000000 --- a/src/main/java/ch/fihlon/workshop/chatbot/GettingStartedBot.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ChatBot Workshop - * Copyright (C) 2018 Marcus Fihlon - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -package ch.fihlon.workshop.chatbot; - -import org.telegram.telegrambots.ApiContextInitializer; -import org.telegram.telegrambots.bots.TelegramLongPollingBot; -import org.telegram.telegrambots.meta.TelegramBotsApi; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.objects.Update; -import org.telegram.telegrambots.meta.exceptions.TelegramApiException; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; - -public class GettingStartedBot extends TelegramLongPollingBot { - - public static void main(final String[] args) throws TelegramApiRequestException { - ApiContextInitializer.init(); - final TelegramBotsApi api = new TelegramBotsApi(); - final GettingStartedBot bot = new GettingStartedBot(); - api.registerBot(bot); - } - - @Override - public String getBotUsername() { - return "MyWorkshopBot"; - } - - @Override - public String getBotToken() { - return "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - } - - @Override - public void onUpdateReceived(final Update update) { - if (update.hasMessage() && update.getMessage().hasText()) { - final Long chatId = update.getMessage().getChatId(); - final String text = update.getMessage().getText(); - final SendMessage message = new SendMessage() - .setChatId(chatId) - .setText(text); - try { - execute(message); - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - } - } - -} diff --git a/src/main/java/ch/fihlon/workshop/chatbot/WorkshopBot.java b/src/main/java/ch/fihlon/workshop/chatbot/WorkshopBot.java deleted file mode 100644 index ec58f43..0000000 --- a/src/main/java/ch/fihlon/workshop/chatbot/WorkshopBot.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * ChatBot Workshop - * Copyright (C) 2018 Marcus Fihlon - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -package ch.fihlon.workshop.chatbot; - -import com.google.common.annotations.VisibleForTesting; -import org.telegram.abilitybots.api.bot.AbilityBot; -import org.telegram.abilitybots.api.db.DBContext; -import org.telegram.abilitybots.api.db.MapDBContext; -import org.telegram.abilitybots.api.objects.Ability; -import org.telegram.abilitybots.api.objects.Flag; -import org.telegram.abilitybots.api.objects.Reply; -import org.telegram.abilitybots.api.sender.MessageSender; -import org.telegram.abilitybots.api.sender.SilentSender; -import org.telegram.telegrambots.ApiContextInitializer; -import org.telegram.telegrambots.meta.TelegramBotsApi; -import org.telegram.telegrambots.meta.api.methods.GetFile; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.send.SendPhoto; -import org.telegram.telegrambots.meta.api.objects.PhotoSize; -import org.telegram.telegrambots.meta.api.objects.Update; -import org.telegram.telegrambots.meta.api.objects.User; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; -import org.telegram.telegrambots.meta.exceptions.TelegramApiException; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - -import static java.util.stream.Collectors.joining; -import static org.telegram.abilitybots.api.objects.Flag.TEXT; -import static org.telegram.abilitybots.api.objects.Locality.ALL; -import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC; -import static org.telegram.abilitybots.api.util.AbilityUtils.getChatId; - -public class WorkshopBot extends AbilityBot { - - private static String BOT_TOKEN = "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - private static String BOT_USERNAME = "MyWorkshopBot"; - private static int CREATOR_ID = 1234567890; - - public static void main(String[] args) throws TelegramApiRequestException { - ApiContextInitializer.init(); - final DBContext db = MapDBContext.onlineInstance("bot.db"); - final WorkshopBot bot = new WorkshopBot(db); - final TelegramBotsApi api = new TelegramBotsApi(); - api.registerBot(bot); - } - - WorkshopBot(final DBContext db) { - super(BOT_TOKEN, BOT_USERNAME, db); - } - - @Override - public int creatorId() { - return CREATOR_ID; - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability sayHelloWorld() { - return Ability - .builder() - .name("hello") - .info("says hello world") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> silent.send("Hello world", context.chatId())) - .build(); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Reply replyToPhoto() { - return Reply.of( - update -> silent.send("Nice pic!", getChatId(update)), - Flag.PHOTO); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability sayHi() { - return Ability - .builder() - .name("hi") - .info("says hi") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> { - final String firstName = context.user().getFirstName(); - silent.send("Hi, " + firstName, context.chatId()); - }) - .reply( - update -> silent.send("Wow, nice name!", update.getMessage().getChatId()), - TEXT, - update -> update.getMessage().getText().startsWith("/hi"), - isMarcus() - ) - .build(); - } - - private Predicate isMarcus() { - return update -> update.getMessage().getFrom().getFirstName().equalsIgnoreCase("Marcus"); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability counter() { - return Ability.builder() - .name("count") - .info("increments a counter per user") - .privacy(PUBLIC) - .locality(ALL) - .action(context -> { - final Map counterMap = db.getMap("COUNTERS"); - final int userId = context.user().getId(); - final Integer counter = counterMap.compute( - String.valueOf(userId), (id, count) -> count == null ? 1 : ++count); - final String message = String.format("%s, your count is now %d!", - context.user().getUserName(), counter); - silent.send(message, context.chatId()); - }) - .build(); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability contacts() { - return Ability.builder() - .name("contacts") - .info("lists all users who contacted this bot") - .privacy(PUBLIC) - .locality(ALL) - .action(context -> { - final Map usersMap = db.getMap("USERS"); - final String users = usersMap.values().stream().map(User::getUserName).collect(joining(", ")); - final String message = "The following users already contacted me: " + users; - silent.send(message, context.chatId()); - }) - .build(); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Reply savePhoto() { - return Reply.of( - update -> { - final List photos = update.getMessage().getPhoto(); - final PhotoSize photoSize = photos.stream() - .max(Comparator.comparing(PhotoSize::getFileSize)) - .orElse(null); - if (photoSize != null) { - final String filePath = getFilePath(photoSize); - final File file = downloadPhoto(filePath); - System.out.println("Temporary file: " + file); - silent.send("Yeah, I got it!", getChatId(update)); - sendPhotoFromFileId(photoSize.getFileId(), getChatId(update)); - } else { - silent.send("Houston, we have a problem!", getChatId(update)); - } - }, - Flag.PHOTO); - } - - private String getFilePath(final PhotoSize photo) { - if (photo.hasFilePath()) { - return photo.getFilePath(); - } - final GetFile getFileMethod = new GetFile(); - getFileMethod.setFileId(photo.getFileId()); - try { - final org.telegram.telegrambots.meta.api.objects.File file = execute(getFileMethod); - return file.getFilePath(); - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - return null; - } - - private File downloadPhoto(final String filePath) { - try { - return downloadFile(filePath); - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - return null; - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability sendLogo() { - return Ability - .builder() - .name("logo") - .info("send the logo") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> sendPhotoFromUrl("https://avatars3.githubusercontent.com/u/13538066?s=200&v=4", context.chatId())) - .build(); - } - - private void sendPhotoFromUrl(final String url, final Long chatId) { - final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 - sendPhotoRequest.setChatId(chatId); // 2 - sendPhotoRequest.setPhoto(url); // 3 - try { - execute(sendPhotoRequest); // 4 - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - } - - private void sendPhotoFromFileId(final String fileId, final Long chatId) { - final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 - sendPhotoRequest.setChatId(chatId); // 2 - sendPhotoRequest.setPhoto(fileId); // 3 - try { - execute(sendPhotoRequest); // 4 - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability sendIcon() { - return Ability - .builder() - .name("icon") - .info("send the icon") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> sendPhotoFromUpload("src/main/resources/chatbot.jpg", context.chatId())) - .build(); - } - - private void sendPhotoFromUpload(final String filePath, final Long chatId) { - final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 - sendPhotoRequest.setChatId(chatId); // 2 - sendPhotoRequest.setPhoto(new File(filePath)); // 3 - try { - execute(sendPhotoRequest); // 4 - } catch (final TelegramApiException e) { - e.printStackTrace(); - } - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability sendKeyboard() { - return Ability - .builder() - .name("keyboard") - .info("send a custom keyboard") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> { - final SendMessage message = new SendMessage(); - message.setChatId(context.chatId()); - message.setText("Enjoy this wonderful keyboard!"); - - final ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); - final List keyboard = new ArrayList<>(); - - // row 1 - KeyboardRow row = new KeyboardRow(); - row.add("/hello"); - row.add("/hi"); - row.add("/count"); - keyboard.add(row); - - // row 2 - row = new KeyboardRow(); - row.add("/contacts"); - row.add("/logo"); - row.add("/icon"); - keyboard.add(row); - - // activate the keyboard - keyboardMarkup.setKeyboard(keyboard); - message.setReplyMarkup(keyboardMarkup); - - silent.execute(message); - }) - .build(); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability format() { - return Ability - .builder() - .name("format") - .info("formats the message") - .locality(ALL) - .privacy(PUBLIC) - .action(context -> { - silent.sendMd("You can make text *bold* or _italic_.", context.chatId()); - silent.sendMd("`This is code.`", context.chatId()); - silent.sendMd("```\nThis\nis\nmulti\nline\ncode.\n```", context.chatId()); - }) - .build(); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability add() { - return Ability - .builder() - .name("add") - .info("adds to numbers") - .locality(ALL) - .privacy(PUBLIC) - .input(2) - .action(context -> { - final int a = Integer.parseInt(context.firstArg()); - final int b = Integer.parseInt(context.secondArg()); - final int sum = a + b; - silent.send(String.format("The sum of %d and %d is %d", a, b, sum), context.chatId()); - }) - .build(); - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - public Ability sayNo() { - return Ability.builder() - .name(DEFAULT) - .privacy(PUBLIC) - .locality(ALL) - .action(context -> silent.send("Sorry, I have no answer for you today.", context.chatId())) - .build(); - } - - @VisibleForTesting - void setSender(final MessageSender sender) { - this.sender = sender; - } - - @VisibleForTesting - void setSilent(final SilentSender silent) { - this.silent = silent; - } - -} diff --git a/src/main/java/de/bigamgamen/java/helper/IOHelper.java b/src/main/java/de/bigamgamen/java/helper/IOHelper.java new file mode 100644 index 0000000..a2e4bee --- /dev/null +++ b/src/main/java/de/bigamgamen/java/helper/IOHelper.java @@ -0,0 +1,83 @@ +package de.bigamgamen.java.helper; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +public class IOHelper { + /** + * Searches for a resource in the application's classpath and the + * filesystem. + *

+ * If the resource is found an {@link InputStream} is returned to read from + * the resource.
+ * If no resource is found an {@link FileNotFoundException} is thrown. + * + * @param relativePath + * The relative path of the resource, e.g. 'res/pics/splash.png' + * @return An {@link InputStream} to read from the resource + * @throws IOException + * if an IO-error occurs + * @throws FileNotFoundException + * if the resource cannot be found + * @since 3.1 + */ + public static InputStream findResource(String relativePath) throws IOException, + FileNotFoundException + { + relativePath = relativePath.replace('\\','/'); + + ClassLoader classLoader = IOHelper.class.getClassLoader(); + InputStream in = classLoader.getResourceAsStream(relativePath); + if(in == null) + { + if(relativePath.startsWith("/")) + { + in = classLoader.getResourceAsStream(relativePath.substring(1)); + } + else + { + in = classLoader.getResourceAsStream("/" + relativePath); + } + } + if(in != null) + { + return in; + } + + File f = new File(relativePath).getAbsoluteFile(); + if(f.exists()) + { + return new FileInputStream(f); + } + + String projectHome = System.getProperty("project.home",null); + if(projectHome != null) + { + StringBuilder path = new StringBuilder(); + if(projectHome.endsWith("/")) + { + path.append(projectHome,0,projectHome.length() - 1); + } + else + { + path.append(projectHome); + } + if(!relativePath.startsWith("/")) + { + path.append("/"); + } + path.append(relativePath); + + f = new File(path.toString()).getAbsoluteFile(); + if(f.exists()) + { + return new FileInputStream(f); + } + } + + throw new FileNotFoundException(relativePath); + } +} diff --git a/src/main/java/de/bigamgamen/java/helper/Pricehelper.java b/src/main/java/de/bigamgamen/java/helper/Pricehelper.java new file mode 100644 index 0000000..ddc0eec --- /dev/null +++ b/src/main/java/de/bigamgamen/java/helper/Pricehelper.java @@ -0,0 +1,14 @@ +package de.bigamgamen.java.helper; + +import java.math.BigInteger; +import java.text.NumberFormat; + +public class Pricehelper { + private Pricehelper() { + + } + + public static String getPriceAsEuroString(BigInteger priceInCent) { + return NumberFormat.getCurrencyInstance().format(priceInCent.doubleValue() / 100); + } +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/HertlHendlBot.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/HertlHendlBot.java new file mode 100644 index 0000000..41b0d97 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/HertlHendlBot.java @@ -0,0 +1,565 @@ +/* + * ChatBot Workshop + * Copyright (C) 2020 Arne Meier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package de.bigamgamen.java.telegrambots.hertlhendl; + +import static org.telegram.abilitybots.api.objects.Locality.ALL; +import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.math.BigInteger; +import java.net.URISyntaxException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.ParserConfigurationException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.telegram.abilitybots.api.bot.AbilityBot; +import org.telegram.abilitybots.api.objects.Ability; +import org.telegram.abilitybots.api.sender.MessageSender; +import org.telegram.abilitybots.api.sender.SilentSender; +import org.telegram.telegrambots.meta.TelegramBotsApi; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.send.SendPhoto; +import org.telegram.telegrambots.meta.api.objects.InputFile; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; +import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; +import org.xml.sax.SAXException; + +import com.google.common.annotations.VisibleForTesting; + +import de.bigamgamen.java.helper.IOHelper; +import de.bigamgamen.java.telegrambots.hertlhendl.api.RightController; +import de.bigamgamen.java.telegrambots.hertlhendl.api.RoleController; +import de.bigamgamen.java.telegrambots.hertlhendl.builder.TelegramKeyBoardBuilder; +import de.bigamgamen.java.telegrambots.hertlhendl.controller.HertlRightController; +import de.bigamgamen.java.telegrambots.hertlhendl.controller.HertlRoleController; +import de.bigamgamen.java.telegrambots.hertlhendl.dal.HertlBotRootDao; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotArticle; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotOrder; +import de.bigamgamen.java.telegrambots.hertlhendl.helper.OrderHelper; +import de.bigamgamen.java.telegrambots.hertlhendl.helper.TelegramHelper; +import de.bigamgamen.java.telegrambots.hertlhendl.init.InitArticles; + +public class HertlHendlBot extends AbilityBot +{ + + public static final String ABILITY_NAME_HELP = "help"; + public static final String ABILITY_NAME_LOCATION_PHOTO = "standortefoto"; + public static final String ABILITY_NAME_PRICES_PHOTO = "preisefoto"; + public static final String ABILITY_NAME_ORDER = "bestellung"; + public static final String ABILITY_NAME_ITEM_LIST = "artikel"; + public static final String ABILITY_NAME_ADD_POSITION = "addposition"; + public static final String ABILITY_NAME_LIST_MY_ORDERS = "bestellungenauflistung"; + public static final String ABILITY_NAME_MY_ORDERS_AS_KEYBOARD = "bestellungenkeyboard"; + public static final String ABILITY_NAME_NEW_ORDER = "neuebestellung"; + public static final String ABILITY_NAME_MY_OPEN_ORDERS = "meineoffnenebestellungen"; + public static final String ABILITY_NAME_ADMIN_OPEN_ORDERS = "adminoffnenebestellungen"; + public static final String ABILITY_NAME_ADMIN_CLOSE_ORDERS = "admincloseorders"; + public static final String ABILITY_NAME_CLOSE_ORDER = "closeorder"; + public static final String ABILITY_NAME_COMMIT_ORDER = "commitorder"; + + private static final String MESSAGE_CLOSE_SUCCESSFULL = "Die Bestellung wurde erfolgreich geschlossen."; + private static final String ALL_MESSAGE_CLOSE_SUCCESSFULL = "Alle offenen Bestellungen wurde erfolgreich geschlossen."; + private static final String MESSAGE_CLOSE_ALREADY_CLOSED = "Die Bestellung ist bereits geschlossen."; + private static final String MESSAGE_ALREADY_COMMITED = "Die Bestellung wurde bereits bestätigt"; + private static final String MESSAGE_COMMIT_SUCCESSFULL = "Die Bestellung wurde erfolgreich bestätigt"; + + private static final String HENDL_PREISE_JPG = "hendl_preise.jpg"; + private final static Logger LOG = LoggerFactory.getLogger(HertlHendlBot.class); + private final static String BOT_TOKEN = ""; + private final static String BOT_USERNAME = ""; + private static Integer CREATOR_ID = 0; + private static String HERTL_URL = "https://hertel-haehnchen.de/standplatzsuche?search=92637"; + private static HertlBotRootDao hertlBotDao; + + private final TelegramKeyBoardBuilder keyBoardBuilder; + private final RightController rightController; + private RoleController roleController; + private final Integer creatorId; + + public static void main(final String[] args) + throws ParserConfigurationException, SAXException, IOException, URISyntaxException, TelegramApiException + { + LOG.info("HertlHendlBot starting"); + + final String token = args[0] != null ? args[0] : BOT_TOKEN; + final String username = args[1] != null ? args[1] : BOT_USERNAME; + final Integer creatorId = args[2] != null ? Integer.valueOf(args[2]) : CREATOR_ID; + final HertlHendlBot bot = new HertlHendlBot(token, username, creatorId); + TelegramBotsApi api = new TelegramBotsApi(DefaultBotSession.class); + api.registerBot(bot); + LOG.info("HertlHendlBot successfull started"); + } + + public HertlHendlBot(final String botToken, final String botUsername, Integer creatorId) + throws ParserConfigurationException, SAXException, IOException, URISyntaxException + { + super(botToken, botUsername); + hertlBotDao = new HertlBotRootDao(); + InitArticles.initArtikels(hertlBotDao); + this.keyBoardBuilder = new TelegramKeyBoardBuilder(hertlBotDao); + this.rightController = new HertlRightController(creatorId); + this.roleController = new HertlRoleController(rightController); + this.creatorId = creatorId; + } + + @Override + public long creatorId() + { + return this.creatorId; + } + + public Ability showHelp() + { + return Ability.builder().name(ABILITY_NAME_HELP).info("shows help").locality(ALL).privacy(PUBLIC) + .action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_HELP)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText(keyBoardBuilder + .createAbilityListForHelp(roleController.getAbilitiesForUser(context.user()))); + this.silent.execute(message); + } + }).build(); + } + + public Ability showOrder() + { + return Ability.builder().name(ABILITY_NAME_ORDER).info("zeigt eine bestimmte Bestellung").locality(ALL) + .privacy(PUBLIC).input(1).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_ORDER)) + { + final int bestellId = Integer.parseInt(context.firstArg()); + final Long chatId = context.chatId(); + final HertlBotOrder bestellung = hertlBotDao.loadBestellung(chatId, TelegramHelper.getTotalUserName(context.user()), bestellId); + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + final String messageText = bestellung.toString() + System.lineSeparator() + + "Füge Positionen zu deiner Bestellung hinzu"; + + message.setText(messageText); + + final ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); + final List keyboard = keyBoardBuilder + .loadAndShowAllArticleForOrder(context.chatId(), bestellId); + + // activate the keyboard + keyboardMarkup.setKeyboard(keyboard); + message.setReplyMarkup(keyboardMarkup); + + this.silent.execute(message); + } + }).build(); + } + + public Ability showArticle() + { + return Ability.builder().name(ABILITY_NAME_ITEM_LIST).info("Listet alle Artikel auf").locality(ALL).privacy(PUBLIC) + .action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_ITEM_LIST)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText(this.loadAndShowAllArticle()); + this.silent.execute(message); + } + }).build(); + } + + public Ability showMyOrders() + { + return Ability.builder().name(ABILITY_NAME_LIST_MY_ORDERS).info("Zeigt die eigenen Bestellungen").locality(ALL) + .privacy(PUBLIC).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_LIST_MY_ORDERS)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText(this.loadAndShowMyOrder(context.chatId(), TelegramHelper.getTotalUserName(context.user()))); + final ReplyKeyboardMarkup keyboardMarkup = keyBoardBuilder.buildOrderMarkup(context); + message.setReplyMarkup(keyboardMarkup); + this.silent.execute(message); + } + }).build(); + } + + public Ability showAdminOpenOrders() + { + return Ability.builder().name(ABILITY_NAME_ADMIN_OPEN_ORDERS).info("Zeigt die offenen Bestellungen").locality(ALL) + .privacy(PUBLIC).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_ADMIN_OPEN_ORDERS)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText(OrderHelper.getTotalOrder(hertlBotDao.loadOpenOrdersForToday()).toString()); + + this.silent.execute(message); + } + }).build(); + } + + public Ability adminCloseOrders() + { + return Ability.builder().name(ABILITY_NAME_ADMIN_CLOSE_ORDERS).info("Schliest alle offnen Bestellungen für Heute").locality(ALL) + .privacy(PUBLIC).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_ADMIN_CLOSE_ORDERS)) + { + SendMessage messageOrder = new SendMessage(); + messageOrder.setChatId(Long.toString(context.chatId())); + hertlBotDao.loadOpenOrdersForToday().stream().forEach(order -> closeOrder(order, messageOrder));; + + + SendMessage message = new SendMessage(); + message.setText(ALL_MESSAGE_CLOSE_SUCCESSFULL); + message.setChatId(Long.toString(context.chatId())); + this.silent.execute(message); + } + }).build(); + } + + public Ability showMyOrderKeyBoard() + { + + return Ability.builder().name(ABILITY_NAME_MY_ORDERS_AS_KEYBOARD) + .info("Zeigt die eigenen Bestellungen als keyboard").locality(ALL).privacy(PUBLIC).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_MY_ORDERS_AS_KEYBOARD)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText("Öffne die Bestellungen über die Tastatur: "); + + final ReplyKeyboardMarkup keyboardMarkup = keyBoardBuilder.buildOrderMarkup(context); + message.setReplyMarkup(keyboardMarkup); + + this.silent.execute(message); + } + }).build(); + } + + public Ability createNewOrder() + { + + return Ability.builder().name(ABILITY_NAME_NEW_ORDER).info("Erstellt eine neue Bestellung").locality(ALL) + .privacy(PUBLIC).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_NEW_ORDER)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText(keyBoardBuilder.createAndShowNewOrder(context.chatId(), TelegramHelper.getTotalUserName(context.user()))); + final ReplyKeyboardMarkup keyboardMarkup = keyBoardBuilder.buildOrderMarkup(context); + message.setReplyMarkup(keyboardMarkup); + this.silent.execute(message); + } + }).build(); + } + + public Ability addPositionToOrder() + { + + return Ability.builder().name(ABILITY_NAME_ADD_POSITION).info("Fügt eine Position zu einer Bestellung hinzu") + .locality(ALL).privacy(PUBLIC).input(2).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_ADD_POSITION)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText(this.createPositionForOrder(context.firstArg(), context.chatId(), TelegramHelper.getTotalUserName(context.user()), + Integer.valueOf(context.secondArg()))); + this.silent.execute(message); + } + }).build(); + } + + public Ability sendKeyboard() + { + return Ability.builder().name("keyboard").info("send a custom keyboard").locality(ALL).privacy(PUBLIC) + .action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_HELP)) + { + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + message.setText("Enjoy this wonderful keyboard!"); + + final ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); + final List keyboard = new ArrayList<>(); + + // row 1 + final KeyboardRow row = new KeyboardRow(); + row.add(keyBoardBuilder.createKeyForAbility(ABILITY_NAME_PRICES_PHOTO)); + row.add(keyBoardBuilder.createKeyForAbility(ABILITY_NAME_LOCATION_PHOTO)); + keyboard.add(row); + + // activate the keyboard + keyboardMarkup.setKeyboard(keyboard); + message.setReplyMarkup(keyboardMarkup); + + this.silent.execute(message); + } + }).build(); + } + + public Ability closeOrderAbility() + { + + return Ability.builder().name(ABILITY_NAME_CLOSE_ORDER).info("Schließt die Bestellung ab.").locality(ALL) + .privacy(PUBLIC) + .input(1) + .action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_CLOSE_ORDER)) + { + final int bestellId = Integer.parseInt(context.firstArg()); + final Long chatId = context.chatId(); + final HertlBotOrder bestellung = hertlBotDao.loadBestellung(chatId, TelegramHelper.getTotalUserName(context.user()), bestellId); + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + + closeOrder(bestellung, message); + + this.silent.execute(message); + } + }).build(); + } + + private void closeOrder(final HertlBotOrder bestellung, final SendMessage message) + { + if (bestellung.isClosed()) + { + + message.setText(MESSAGE_CLOSE_ALREADY_CLOSED); + } else + { + bestellung.setClosed(true); + HertlBotRootDao.storageManager().store(bestellung); + message.setText(MESSAGE_CLOSE_SUCCESSFULL); + } + } + + public Ability commitOrder() + { + + return Ability.builder().name(ABILITY_NAME_COMMIT_ORDER).info("Bestätigt die Bestellung.").locality(ALL) + .privacy(PUBLIC) + .input(1) + .action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_COMMIT_ORDER)) + { + final int bestellId = Integer.parseInt(context.firstArg()); + final Long chatId = context.chatId(); + final HertlBotOrder bestellung = hertlBotDao.loadBestellung(chatId, TelegramHelper.getTotalUserName(context.user()), bestellId); + final SendMessage message = new SendMessage(); + message.setChatId(Long.toString(context.chatId())); + + if (bestellung.isCommited()) + { + + message.setText(MESSAGE_ALREADY_COMMITED); + } else + { + bestellung.setCommited(true); + HertlBotRootDao.storageManager().store(bestellung); + message.setText(MESSAGE_COMMIT_SUCCESSFULL); + } + + this.silent.execute(message); + } + }).build(); + } + + public Ability showPricePhoto() + { + return Ability.builder().name(ABILITY_NAME_PRICES_PHOTO).info("send Preisfoto").locality(ALL).privacy(PUBLIC) + .action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_PRICES_PHOTO)) + { + this.sendPhotoFromUpload(HENDL_PREISE_JPG, context.chatId()); + } + }).build(); + } + + public Ability showLocationPhoto() + { + return Ability.builder().name(ABILITY_NAME_LOCATION_PHOTO).info("standorteFoto Weiden").locality(ALL) + .privacy(PUBLIC).action(context -> + { + if (roleController.canUseAbility(context.user(), ABILITY_NAME_LOCATION_PHOTO)) + { + this.makeScreenshotSenditDeleteit(context.chatId()); + } + }).build(); + } + + private void makeScreenshotSenditDeleteit(final Long chatId) + { + final String fileName = this.makingScreenshotOfHertlHomepage(); + this.sendPhotoFromUpload(fileName, chatId); + final File fileToDelete = new File(fileName); + fileToDelete.delete(); + } + + private void sendPhotoFromUpload(final String filePath, final Long chatId) + { + final SendPhoto sendPhotoRequest = new SendPhoto(); // 1 + sendPhotoRequest.setChatId(Long.toString(chatId)); // 2 + try + { + sendPhotoRequest.setPhoto(new InputFile(IOHelper.findResource(filePath), filePath)); + } catch (final Exception e1) + { + LOG.error("Fehler beim schicken des Photos:{}", e1); + } + + try + { + this.execute(sendPhotoRequest); // 4 + } + catch(final TelegramApiException e) + { + e.printStackTrace(); + } + } + + /** + * Make an Screenshot of the Hmepage with docker. Works only on Linux + * + * @return Fullqualified Filename to load from Hdd. + */ + private String makingScreenshotOfHertlHomepage() + { + final ProcessBuilder processBuilder = new ProcessBuilder(); + + final String hertlTimeStampFileName = "hertl_standorteFoto" + + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd__HH-mm-ss-SSS")) + ".png"; + + try + { + + // -- Linux -- + final String command = "sudo docker run --rm -v $PWD:/srv lifenz/docker-screenshot " + HERTL_URL + " " + + hertlTimeStampFileName + " 1500px 2000 1"; + System.out.println(command); + // Run a shell command + processBuilder.command("bash", "-c", command); + + final Process process = processBuilder.start(); + System.out.println("Docker gestartet"); + + final StringBuilder output = new StringBuilder(); + + final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + + String line; + while ((line = reader.readLine()) != null) + { + output.append(line + "\n"); + } + + final int exitVal = process.waitFor(); + System.out.println("exitvalue: " + exitVal); + if (exitVal == 0) + { + System.out.println("Success!"); + System.out.println(output); + return hertlTimeStampFileName; + } else + { + return null; + } + + } catch (final IOException e) + { + e.printStackTrace(); + } catch (final InterruptedException e) + { + e.printStackTrace(); + } + return ""; + + } + + @VisibleForTesting + void setSender(final MessageSender sender) + { + this.sender = sender; + } + + @VisibleForTesting + void setSilent(final SilentSender silent) + { + this.silent = silent; + } + + private String createPositionForOrder(final String artikelName, final Long chatId, String userName, + final Integer bestellungId) + { + final HertlBotArticle artikel = hertlBotDao.root().artikels().ofName(artikelName); + final HertlBotOrder bestellung = hertlBotDao.loadBestellung(chatId, userName, bestellungId); + OrderHelper.addArticleToOrder(artikel,BigInteger.valueOf(1L), bestellung); + + return this.loadAndShowOrder(chatId,userName, bestellungId); + + } + + + + private String loadAndShowOrder(final Long chatId, String userName, final int bestellId) + { + final HertlBotOrder bestellung = hertlBotDao.loadBestellung(chatId, userName, bestellId); + return bestellung.toString(); + } + + public String loadAndShowMyOrder(final Long chatId ,String userName) + { + final StringBuilder sb = new StringBuilder( + "Ihre Bestellungen:" + System.lineSeparator() + System.lineSeparator()); + HertlHendlBot.hertlBotDao.loadUser(chatId, userName).getBestellungen() + .forEach(bestellung -> sb.append(loadAndShowOrder(chatId, userName, bestellung.getIndex())) + .append(System.lineSeparator() + System.lineSeparator())); + return sb.toString(); + } + + private String loadAndShowAllArticle() + { + final StringBuilder sb = new StringBuilder(); + hertlBotDao.root().artikels().all() + .forEach(artikel -> sb.append(artikel.toString()).append(System.lineSeparator())); + return sb.toString(); + } + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/api/RightController.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/api/RightController.java new file mode 100644 index 0000000..11910b3 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/api/RightController.java @@ -0,0 +1,16 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.api; + +import java.util.List; + +import org.telegram.telegrambots.meta.api.objects.User; + +public interface RightController { + + /** + * Checks if the User is the Admin + * @param user + * @return + */ + public boolean isAdmin(User user); + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/api/RoleController.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/api/RoleController.java new file mode 100644 index 0000000..3c025a6 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/api/RoleController.java @@ -0,0 +1,23 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.api; + +import java.util.List; + +import org.telegram.telegrambots.meta.api.objects.User; + +public interface RoleController { + + /** + * Get the KeyboardShortcuts which this User can use. + * @param user + * @return + */ + public List getAbilitiesForUser(User user); + + /** + * Checks if the user can use the Ability + * @param ability + * @param user + * @return + */ + public Boolean canUseAbility(User user, String ability); +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/builder/TelegramKeyBoardBuilder.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/builder/TelegramKeyBoardBuilder.java new file mode 100644 index 0000000..fc525f1 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/builder/TelegramKeyBoardBuilder.java @@ -0,0 +1,112 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.telegram.abilitybots.api.objects.MessageContext; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; + +import de.bigamgamen.java.telegrambots.hertlhendl.HertlHendlBot; +import de.bigamgamen.java.telegrambots.hertlhendl.dal.HertlBotRootDao; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotArticle; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotOrder; +import de.bigamgamen.java.telegrambots.hertlhendl.helper.TelegramHelper; + +public class TelegramKeyBoardBuilder { + + private static final int MAX_BUTTON_PER_ROW = 1; + + private static final String KEY_PRE_SYMBOL = "/"; + + private final HertlBotRootDao hertlBotDao; + + public TelegramKeyBoardBuilder(HertlBotRootDao hertlBotDao) { + this.hertlBotDao = hertlBotDao; + } + + public List loadAndShowMyOrdersAsKeyBoard(final Long chatId, String userName) { + final List keyboard = new ArrayList<>(); + + hertlBotDao.loadUser(chatId,userName).getBestellungen() + .forEach(bestellung -> addButtonToKeyBoard(keyboard, this.createOrderLink(bestellung))); + + return keyboard; + } + + public List loadAndShowAllArticleForOrder(final Long chatId, final Integer bestellungId) { + final List keyboard = new ArrayList<>(); + + hertlBotDao.root().artikels().all().forEach( + artikel -> addButtonToKeyBoard(keyboard, createAddPositiontoOrderLink(artikel, bestellungId))); + + KeyboardRow row = new KeyboardRow(); + row.add(new KeyboardButton(createKeyForAbility(HertlHendlBot.ABILITY_NAME_COMMIT_ORDER+" "+bestellungId))); + keyboard.add(row); + + row = new KeyboardRow(); + row.add(new KeyboardButton(createKeyForAbility(HertlHendlBot.ABILITY_NAME_CLOSE_ORDER+" "+bestellungId))); + keyboard.add(row); + + return keyboard; + } + + private void addButtonToKeyBoard(List keyboard, String buttonString) { + KeyboardRow rowToUse = null; + + for (KeyboardRow row : keyboard) { + if (row.size() < MAX_BUTTON_PER_ROW) { + rowToUse = row; + } + } + + if (rowToUse == null) { + rowToUse = new KeyboardRow(); + keyboard.add(rowToUse); + } + + rowToUse.add(buttonString); + + } + + public String createAndShowNewOrder(final Long chatId, String userName) { + + final HertlBotOrder bestellung = hertlBotDao.createNewBestellungForUser(chatId, userName); + + return this.createOrderLink(bestellung); + } + + public String createOrderLink(final HertlBotOrder bestellung) { + return this.createKeyForAbility(HertlHendlBot.ABILITY_NAME_ORDER) + " " + Integer.toString(bestellung.getIndex()) + + System.lineSeparator(); + } + + public String createAddPositiontoOrderLink(final HertlBotArticle artikel, final Integer bestellungId) { + return this.createKeyForAbility(HertlHendlBot.ABILITY_NAME_ADD_POSITION) + " " + artikel.getName() + " " + + bestellungId + System.lineSeparator(); + } + + public String createAbilityListForHelp(List abilities) { + final StringBuilder sb = new StringBuilder(); + abilities.forEach(ability -> sb.append(this.createKeyForAbility(ability) + System.lineSeparator())); + return sb.toString(); + } + + public String createKeyForAbility(final String ability) { + return KEY_PRE_SYMBOL + ability; + } + + private void addClearButtonOrder(List keyboard, HertlBotOrder bestellung) { + + } + + public ReplyKeyboardMarkup buildOrderMarkup(MessageContext context) { + final ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(); + final List keyboard = this.loadAndShowMyOrdersAsKeyBoard(context.chatId(), TelegramHelper.getTotalUserName(context.user())); + + // activate the keyboard + keyboardMarkup.setKeyboard(keyboard); + return keyboardMarkup; + } +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/controller/HertlRightController.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/controller/HertlRightController.java new file mode 100644 index 0000000..356cfde --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/controller/HertlRightController.java @@ -0,0 +1,23 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.controller; + +import org.telegram.telegrambots.meta.api.objects.User; + +import de.bigamgamen.java.telegrambots.hertlhendl.api.RightController; + +public class HertlRightController implements RightController{ + + private final Integer adminId; + + + public HertlRightController(Integer adminId) { + this.adminId = adminId; + } + + + @Override + public boolean isAdmin(User user) { + return user.getId().equals(this.adminId); + } + + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/controller/HertlRoleController.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/controller/HertlRoleController.java new file mode 100644 index 0000000..fcf0564 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/controller/HertlRoleController.java @@ -0,0 +1,70 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.controller; + +import java.util.Arrays; +import java.util.List; + +import org.telegram.telegrambots.meta.api.objects.User; + +import de.bigamgamen.java.telegrambots.hertlhendl.HertlHendlBot; +import de.bigamgamen.java.telegrambots.hertlhendl.api.RightController; +import de.bigamgamen.java.telegrambots.hertlhendl.api.RoleController; + +public class HertlRoleController implements RoleController +{ + + private static List ADMIN_SET = Arrays.asList( + HertlHendlBot.ABILITY_NAME_HELP, + HertlHendlBot.ABILITY_NAME_LOCATION_PHOTO, + HertlHendlBot.ABILITY_NAME_PRICES_PHOTO, + HertlHendlBot.ABILITY_NAME_ITEM_LIST, + HertlHendlBot.ABILITY_NAME_NEW_ORDER, + HertlHendlBot.ABILITY_NAME_LIST_MY_ORDERS, + HertlHendlBot.ABILITY_NAME_MY_ORDERS_AS_KEYBOARD, + HertlHendlBot.ABILITY_NAME_MY_OPEN_ORDERS, + HertlHendlBot.ABILITY_NAME_ADMIN_OPEN_ORDERS, + HertlHendlBot.ABILITY_NAME_ADMIN_CLOSE_ORDERS, + HertlHendlBot.ABILITY_NAME_ADD_POSITION, + HertlHendlBot.ABILITY_NAME_ORDER, + HertlHendlBot.ABILITY_NAME_COMMIT_ORDER, + HertlHendlBot.ABILITY_NAME_CLOSE_ORDER); + private static List USER_SET = Arrays.asList( + HertlHendlBot.ABILITY_NAME_HELP, + HertlHendlBot.ABILITY_NAME_LOCATION_PHOTO, + HertlHendlBot.ABILITY_NAME_PRICES_PHOTO, + HertlHendlBot.ABILITY_NAME_ITEM_LIST, + HertlHendlBot.ABILITY_NAME_NEW_ORDER, + HertlHendlBot.ABILITY_NAME_LIST_MY_ORDERS, + HertlHendlBot.ABILITY_NAME_MY_ORDERS_AS_KEYBOARD, + HertlHendlBot.ABILITY_NAME_MY_OPEN_ORDERS, + HertlHendlBot.ABILITY_NAME_ADD_POSITION, + HertlHendlBot.ABILITY_NAME_ORDER, + HertlHendlBot.ABILITY_NAME_COMMIT_ORDER, + HertlHendlBot.ABILITY_NAME_CLOSE_ORDER); + + private RightController rigthController; + + public HertlRoleController(RightController rigthController) + { + this.rigthController = rigthController; + } + + @Override + public List getAbilitiesForUser(User user) + { + if (rigthController.isAdmin(user)) + { + return ADMIN_SET; + } else + { + return USER_SET; + } + } + + @Override + public Boolean canUseAbility(User user, String ability) + { + List roles = getAbilitiesForUser(user); + return roles.contains(ability); + } + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/dal/HertlBotRootDao.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/dal/HertlBotRootDao.java new file mode 100644 index 0000000..9820803 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/dal/HertlBotRootDao.java @@ -0,0 +1,112 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.dal; + +import java.nio.file.Paths; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotOrder; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotRoot; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotUser; +import one.microstream.storage.configuration.Configuration; +import one.microstream.storage.types.EmbeddedStorageFoundation; +import one.microstream.storage.types.EmbeddedStorageManager; + +public class HertlBotRootDao +{ + + private final static EmbeddedStorageManager storageManager = createStorageManager(); + + private Predicate openOrderUntilToday = order -> + { + LocalDate now = LocalDate.now(); + LocalDate orderDate = order.getBestellDatum(); + return (orderDate.isBefore(now) || orderDate.equals(now)) && !order.isClosed() && order.isCommited(); + }; + + + public HertlBotRootDao() + { + + } + + private static EmbeddedStorageManager createStorageManager() + { + final Configuration configuration = Configuration.Default(); + configuration.setBaseDirectory(Paths.get("data", "microstream", "storage").toString()); + configuration.setChannelCount(2); + + final EmbeddedStorageFoundation foundation = configuration.createEmbeddedStorageFoundation(); + + final EmbeddedStorageManager storageManager = foundation.createEmbeddedStorageManager().start(); + + if (storageManager.root() == null) + { + final HertlBotRoot root = new HertlBotRoot(); + storageManager.setRoot(root); + storageManager.storeRoot(); + } + + return storageManager; + } + + public static EmbeddedStorageManager storageManager() + { + return storageManager; + } + + public HertlBotRoot root() + { + return (HertlBotRoot) storageManager().root(); + } + + public HertlBotOrder loadBestellung(Long chatId, String userName, int bestellId) + { + HertlBotUser user = loadUser(chatId,userName); + + return user.getBestellungen().stream().filter(bestellung -> bestellung.getIndex() == bestellId).findFirst() + .get(); + } + + public HertlBotUser loadUser(Long chatId, String userName) + { + + Optional userOpt = root().users().ofId(chatId); + + if (userOpt.isPresent()) + { + return userOpt.get(); + } + + HertlBotUser user = new HertlBotUser(chatId,userName); + root().users().add(user, storageManager()); + return user; + } + + public HertlBotOrder createNewBestellungForUser(Long chatId, String userName) + { + HertlBotUser user = this.loadUser(chatId,userName); + HertlBotOrder bestellung = new HertlBotOrder(user, new ArrayList<>()); + user.addBestellung(bestellung, storageManager); + + return bestellung; + } + + public List loadOpenOrdersForToday() + { + List orders = new ArrayList<>(); + root().users().all().forEach(user -> orders + .addAll(user.getBestellungen().stream().filter(openOrderUntilToday).collect(Collectors.toList()))); + return orders; + } + + public void shutDown() + { + + storageManager.shutdown(); + } + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotArticle.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotArticle.java new file mode 100644 index 0000000..c64741d --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotArticle.java @@ -0,0 +1,48 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +import java.math.BigInteger; + +import de.bigamgamen.java.helper.Pricehelper; + +public class HertlBotArticle { + private int id; + private String name; + private BigInteger priceInCent; + + public HertlBotArticle() { + + } + + public HertlBotArticle(int id, String name, BigInteger priceInCent) { + super(); + this.id = id; + this.name = name; + this.priceInCent = priceInCent; + } + + @Override + public String toString() { + return this.name + ": " + Pricehelper.getPriceAsEuroString(priceInCent); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public BigInteger getPriceInCent() { + return priceInCent; + } + + public void setPriceInCent(BigInteger priceInCent) { + this.priceInCent = priceInCent; + } + + public int getId() { + return id; + } + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotArticles.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotArticles.java new file mode 100644 index 0000000..206583f --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotArticles.java @@ -0,0 +1,81 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import de.bigamgamen.java.telegrambots.hertlhendl.dal.HertlBotRootDao; +import one.microstream.persistence.types.Persister; + +public class HertlBotArticles { + + private final Map artikels = new HashMap<>(); + + public HertlBotArticles() { + super(); + } + + + + public void add( + final HertlBotArticle artikel, + final Persister persister + ) + { + this.artikels.put(artikel.getName(), artikel); + persister.store(this.artikels); + } + + public void addAll(final Collection HertlBotArtikels) + { + this.addAll(HertlBotArtikels, HertlBotRootDao.storageManager()); + } + + public void addAll( + final Collection artikels, + final Persister persister + ) + { + this.artikels.putAll( + artikels.stream().collect( + Collectors.toMap(HertlBotArticle::getName, Function.identity()) + ) + ); + persister.store(this.artikels); + } + + public int HertlBotArtikelCount() + { + return this.artikels.size(); + } + + public List all() + { + return new ArrayList<>(this.artikels.values()); + } + + public HertlBotArticle ofName(final String artikelName) + { + return this.artikels.get(artikelName); + } + + public void clearAll() + { + this.clearAll(HertlBotRootDao.storageManager()); + } + + public void clearAll( + final Persister persister + ) + { + this.artikels.clear(); + persister.store(this.artikels); + } + + + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotOrder.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotOrder.java new file mode 100644 index 0000000..f82a745 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotOrder.java @@ -0,0 +1,120 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +import java.math.BigInteger; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +import de.bigamgamen.java.helper.Pricehelper; +import one.microstream.persistence.types.Persister; + +public class HertlBotOrder { + + private static final String ORDER_COMMITED = "BESTÄTIGT"; + private static final String ORDER_CLOSED = "GESCHLOSSEN"; + private static final String ORDER_TITLE = "Ihre Bestellung:"; + private static final String DD_MM_YYYY = "dd-MM-yyyy"; + private int index; + private LocalDate bestellDatum; + private HertlBotUser user; + private List positionen = new ArrayList<>(); + private Boolean commited = false; + private Boolean closed = false; + + public HertlBotOrder() { + + } + + public HertlBotOrder(final HertlBotUser user, final List positionen) { + this.bestellDatum = LocalDate.now(); + this.user = user; + this.positionen = positionen; + } + + public synchronized void addPosition(HertlBotPosition position, final Persister persister) + { + positionen.add(position); + persister.store(position); + persister.store(positionen); + } + + + public String getBestellDatumFormated() { + return this.bestellDatum.format(DateTimeFormatter.ofPattern(DD_MM_YYYY)); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(ORDER_TITLE + " " +this.index); + sb.append(" Für: " + this.getUser().getUserName()) + .append(" Vom: " + this.getBestellDatumFormated() + "." + + (isCommited() ? ORDER_COMMITED + " und ":"") + + (isClosed() ? ORDER_CLOSED:"") + + System.lineSeparator()); + this.positionen.forEach(pos -> sb.append(pos.toString()+System.lineSeparator())); + sb.append("Summe: "+ this.getSumme()); + return sb.toString(); + } + + private String getSumme() { + BigInteger summe = new BigInteger("0"); + for(HertlBotPosition pos : positionen) + { + summe = summe.add(pos.getPositionPrice()); + } + return Pricehelper.getPriceAsEuroString(summe); + } + + public HertlBotUser getUser() { + return this.user; + } + public void setUser(final HertlBotUser user) { + this.user = user; + } + public List getPositionen() { + return this.positionen; + } + public void setPositionen(final List positionen) { + this.positionen = positionen; + } + + public LocalDate getBestellDatum() { + return this.bestellDatum; + } + + public void setBestellDatum(final LocalDate bestellDatum) { + this.bestellDatum = bestellDatum; + } + + public int getIndex() { + return this.index; + } + + public void setIndex(final int index) { + this.index = index; + } + + public Boolean isClosed() + { + return closed; + } + + public void setClosed(Boolean closed) + { + this.closed = closed; + } + + public Boolean isCommited() + { + return this.commited; + } + + public void setCommited(Boolean commited) + { + this.commited = commited; + } + + + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotPosition.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotPosition.java new file mode 100644 index 0000000..454335f --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotPosition.java @@ -0,0 +1,57 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +import java.math.BigInteger; + +public class HertlBotPosition { + private BigInteger menge = BigInteger.valueOf(1L); + private HertlBotArticle artikel; + private HertlBotOrder bestelllung; + + public HertlBotPosition() { + + } + + public HertlBotPosition(BigInteger menge, HertlBotArticle artikel) { + this.menge = menge; + this.artikel = artikel; + } + + @Override + public String toString() { + String positionString = menge + "-mal "+ artikel.getName(); + return positionString; + } + + public BigInteger getPositionPrice() { + return artikel.getPriceInCent().multiply(menge); + } + + public BigInteger getMenge() { + return this.menge; + } + + public void setMenge(final BigInteger menge) { + this.menge = menge; + } + + public HertlBotArticle getArtikel() { + return this.artikel; + } + + public void setArtikel(final HertlBotArticle artikel) { + this.artikel = artikel; + } + + public HertlBotOrder getBestelllung() + { + return this.bestelllung; + } + + public void setBestelllung(final HertlBotOrder bestelllung) + { + this.bestelllung = bestelllung; + } + + + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotRoot.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotRoot.java new file mode 100644 index 0000000..9ac398e --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotRoot.java @@ -0,0 +1,20 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +public class HertlBotRoot { + private HertlBotUsers users = new HertlBotUsers(); + private HertlBotArticles artikels = new HertlBotArticles(); + + public HertlBotRoot() + { + + } + + public HertlBotUsers users() { + return users; + } + + public HertlBotArticles artikels() { + return artikels; + } + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotUser.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotUser.java new file mode 100644 index 0000000..0e411b0 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotUser.java @@ -0,0 +1,56 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +import java.util.ArrayList; +import java.util.List; + +import one.microstream.persistence.types.Persister; + +public class HertlBotUser { + + private Long chatId; + private String userName; + private List bestellungen = new ArrayList<>(); + + public HertlBotUser(Long chatId, String userName) { + this.chatId = chatId; + this.userName = userName; + } + + public synchronized void addBestellung(HertlBotOrder bestellung, final Persister persister) + { + bestellung.setUser(this); + this.bestellungen.add(bestellung); + bestellung.setIndex(this.bestellungen.indexOf(bestellung)); + persister.store(bestellungen); + } + + public boolean isRightUser(Long chatId) + { + return this.chatId.equals(chatId); + } + + + + public List getBestellungen() { + return new ArrayList<>(bestellungen); + } + + public void setChatId(Long chatId) { + this.chatId = chatId; + } + + public Long getChatId() { + return chatId; + } + + public String getUserName() + { + return userName; + } + + public void setUserName(String userName) + { + this.userName = userName; + } + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotUsers.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotUsers.java new file mode 100644 index 0000000..48e7233 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/domain/HertlBotUsers.java @@ -0,0 +1,69 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.domain; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import java.util.Optional; + +import de.bigamgamen.java.telegrambots.hertlhendl.dal.HertlBotRootDao; +import one.microstream.persistence.types.Persister; + +public class HertlBotUsers { + + private final Map users = new HashMap<>(); + + public HertlBotUsers() { + super(); + } + + + public void add( + final HertlBotUser HertlBotUser, + final Persister persister + ) + { + this.users.put(HertlBotUser.getChatId(), HertlBotUser); + persister.store(this.users); + } + + public void addAll(final Collection HertlBotUsers) + { + this.addAll(HertlBotUsers, HertlBotRootDao.storageManager()); + } + + public void addAll( + final Collection users, + final Persister persister + ) + { + this.users.putAll( + users.stream().collect( + Collectors.toMap(HertlBotUser::getChatId, Function.identity()) + ) + ); + persister.store(this.users); + } + + public int HertlBotUserCount() + { + return this.users.size(); + } + + public List all() + { + return new ArrayList<>(this.users.values()); + } + + public Optional ofId(final long chatId) + { + return Optional.ofNullable(this.users.get(chatId)); + } + + + +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/helper/OrderHelper.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/helper/OrderHelper.java new file mode 100644 index 0000000..dabd548 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/helper/OrderHelper.java @@ -0,0 +1,56 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.helper; + +import java.math.BigInteger; +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + +import de.bigamgamen.java.telegrambots.hertlhendl.dal.HertlBotRootDao; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotArticle; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotOrder; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotPosition; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotUser; + +public class OrderHelper +{ + private OrderHelper () + { + + } + + public static HertlBotOrder getTotalOrder(List orderList) + { + HertlBotOrder totalOrder = new HertlBotOrder(); + HertlBotUser totalUser = new HertlBotUser(1L,"Gesamtbestellung"); + + totalOrder.setUser(totalUser); + totalOrder.setBestellDatum(LocalDate.now()); + orderList.forEach(order -> order.getPositionen().forEach(position -> addArticleToOrder(position.getArtikel(), position.getMenge(), totalOrder))); + + return totalOrder; + } + + public static void addArticleToOrder(final HertlBotArticle artikel, BigInteger amount, final HertlBotOrder bestellung) + { + final Predicate positionAlreadyExist = position -> position.getArtikel().getName() + .equals(artikel.getName()); + + HertlBotPosition position; + + final Optional positionOpt = bestellung.getPositionen().stream().filter(positionAlreadyExist) + .findFirst(); + if (positionOpt.isPresent()) + { + position = positionOpt.get(); + position.setMenge(position.getMenge().add(amount)); + HertlBotRootDao.storageManager().store(position); + } else + { + position = new HertlBotPosition(); + position.setArtikel(artikel); + position.setMenge(amount); + bestellung.addPosition(position, HertlBotRootDao.storageManager()); + } + } +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/helper/TelegramHelper.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/helper/TelegramHelper.java new file mode 100644 index 0000000..df52606 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/helper/TelegramHelper.java @@ -0,0 +1,20 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.helper; + +import org.telegram.telegrambots.meta.api.objects.User; + +public class TelegramHelper +{ + private TelegramHelper() + { + + } + + public static String getTotalUserName(User user) + { + return + (user.getFirstName() != null ? user.getFirstName() : "") + +" " + + (user.getLastName() != null ? user.getLastName() : "") + +"(" + (user.getUserName() != null ? user.getUserName() : "") +")"; + } +} diff --git a/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/init/InitArticles.java b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/init/InitArticles.java new file mode 100644 index 0000000..fd02129 --- /dev/null +++ b/src/main/java/de/bigamgamen/java/telegrambots/hertlhendl/init/InitArticles.java @@ -0,0 +1,35 @@ +package de.bigamgamen.java.telegrambots.hertlhendl.init; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import de.bigamgamen.java.telegrambots.hertlhendl.dal.HertlBotRootDao; +import de.bigamgamen.java.telegrambots.hertlhendl.domain.HertlBotArticle; + +public class InitArticles +{ + + private InitArticles() + { + + } + + public synchronized static void initArtikels(final HertlBotRootDao dao) + { + final List artikelList = new ArrayList<>(); + // Die Namen Dürfen keine Leerzeichen enthalten !!!! + artikelList.add(new HertlBotArticle(1, "1/2-Hähnchen", BigInteger.valueOf(400L))); + artikelList.add(new HertlBotArticle(2, "Hähnchen-Schenkel", BigInteger.valueOf(220L))); + artikelList.add(new HertlBotArticle(3, "Krautsalat", BigInteger.valueOf(160L))); + artikelList.add(new HertlBotArticle(4, "Brezel-klein", BigInteger.valueOf(80L))); + artikelList.add(new HertlBotArticle(5, "Brezel-groß", BigInteger.valueOf(160L))); + artikelList.add(new HertlBotArticle(6, "Kartoffelsalat-Essig-Öl", BigInteger.valueOf(160L))); + artikelList.add(new HertlBotArticle(7, "Kartoffelsalat-Majo", BigInteger.valueOf(160L))); + + dao.root().artikels().clearAll(); + + dao.root().artikels().addAll(artikelList); + } + +} diff --git a/src/main/resources/hendl_preise.jpg b/src/main/resources/hendl_preise.jpg new file mode 100644 index 0000000..642d71d Binary files /dev/null and b/src/main/resources/hendl_preise.jpg differ diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml new file mode 100644 index 0000000..0041f6d --- /dev/null +++ b/src/main/resources/log4j.xml @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/run.sh b/src/main/resources/run.sh new file mode 100644 index 0000000..596e5bb --- /dev/null +++ b/src/main/resources/run.sh @@ -0,0 +1 @@ +java -cp java.telegrambots-1.0.0-SNAPSHOT.jar:./lib/* de.bigamgamen.java.telegrambots.hertlhendl.HertlHendlBot \ No newline at end of file diff --git a/src/test/java/ch/fihlon/workshop/chatbot/WorkshopBotTest.java b/src/test/java/ch/fihlon/workshop/chatbot/WorkshopBotTest.java deleted file mode 100644 index 531e9de..0000000 --- a/src/test/java/ch/fihlon/workshop/chatbot/WorkshopBotTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ChatBot Workshop - * Copyright (C) 2018 Marcus Fihlon - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -package ch.fihlon.workshop.chatbot; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.telegram.abilitybots.api.db.DBContext; -import org.telegram.abilitybots.api.db.MapDBContext; -import org.telegram.abilitybots.api.objects.MessageContext; -import org.telegram.abilitybots.api.sender.MessageSender; -import org.telegram.abilitybots.api.sender.SilentSender; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.objects.Update; -import org.telegram.telegrambots.meta.api.objects.User; -import org.telegram.telegrambots.meta.exceptions.TelegramApiException; - -import static org.mockito.Mockito.*; - -public class WorkshopBotTest { - - private static final int USER_ID = 1337; - private static final long CHAT_ID = 1337L; - - private WorkshopBot bot; - private DBContext db; - private MessageSender sender; - - @Before - public void setUp() { - // Offline instance will get deleted at JVM shutdown - db = MapDBContext.offlineInstance("test"); - bot = new WorkshopBot(db); - sender = mock(MessageSender.class); - bot.setSender(sender); - bot.setSilent(new SilentSender(sender)); - } - - @Test - public void sayHelloWorld() throws TelegramApiException { - final Update mockedUpdate = mock(Update.class); - final User user = new User(USER_ID, "Foo", false, "Bar", "foobar42", "en"); - final MessageContext context = MessageContext.newContext(mockedUpdate, user, CHAT_ID); - - bot.sayHelloWorld().action().accept(context); - - final SendMessage message = new SendMessage(); - message.setChatId(CHAT_ID); - message.setText("Hello world"); - verify(sender, times(1)).execute(message); - } - - @After - public void tearDown() { - db.clear(); - } - -} diff --git a/start_docker_example.sh b/start_docker_example.sh new file mode 100644 index 0000000..c830d86 --- /dev/null +++ b/start_docker_example.sh @@ -0,0 +1,6 @@ +#Production +docker run -d --restart unless-stopped --name chatbot -v chatbotvol:/opt/telegrambot/data --env-file ./env.list amgamen/chatbot + +#Develop +docker run -it -v chatbotvol:/opt/telegrambot/data --env-file ./env.list amgamen/chatbot +docker run -it -v chatbotvol:/opt/telegrambot/data -e "BOT_TOKEN=" -e "BOT_KEY=" -e "BOT_NAME=" -e "CREATOR_ID=" amgamen/chatbot