├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle ├── gradle-mvn-push.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── gradle.properties └── src │ └── main │ └── java │ └── com │ └── github │ └── telegram │ └── mvc │ ├── HandlerAdapter.java │ ├── HandlerMethodContainer.java │ ├── RequestDispatcher.java │ ├── RequestMappingInfo.java │ ├── TelegramConfiguration.java │ ├── TelegramControllerBeanPostProcessor.java │ ├── TelegramInvocableHandlerMethod.java │ ├── TelegramService.java │ ├── api │ ├── BotController.java │ ├── BotRequest.java │ ├── EnableTelegram.java │ ├── MessageType.java │ ├── TelegramRequest.java │ ├── TelegramSession.java │ └── TextVariable.java │ ├── config │ ├── TelegramBotBuilder.java │ ├── TelegramBotProperties.java │ ├── TelegramBotProperty.java │ ├── TelegramMvcConfiguration.java │ ├── TelegramScope.java │ └── TelegramScopeException.java │ └── handler │ ├── BotBaseRequestMethodProcessor.java │ ├── BotHandlerMethodArgumentResolver.java │ ├── BotHandlerMethodArgumentResolverComposite.java │ ├── BotHandlerMethodReturnValueHandler.java │ ├── BotHandlerMethodReturnValueHandlerComposite.java │ ├── BotRequestMethodArgumentResolver.java │ ├── BotResponseBodyMethodProcessor.java │ └── BotTextVariableMethodArgumentResolver.java ├── sample ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── github │ │ └── telegram │ │ └── sample │ │ └── SampleTelegramBotMvcMain.java │ └── resources │ └── application.yaml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | /out/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | 6 | ### STS ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | nbproject/private/ 22 | build/ 23 | nbbuild/ 24 | dist/ 25 | nbdist/ 26 | .nb-gradle/ 27 | /.gradletasknamecache 28 | !/library/build/ 29 | /library/out/ 30 | /sample/src/main/resources/application-dev.yaml 31 | Будет удалено library/src/main/resources/ 32 | Будет удалено library/src/test/ 33 | Будет удалено sample/src/test/ 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Oleg Nyrkov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java telegram bot mvc 2 | 3 | Библиотека для разработки [Телеграмм бота](https://core.telegram.org/bots) 4 | используется фраемворк [Spring MVC](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html) 5 | для взаимодействия с API телеграмма используется библиотека [java-telegram-bot-api](https://github.com/pengrad/java-telegram-bot-api) 6 | 7 | Идея взята из https://habrahabr.ru/post/335490/ спасибо @PqDn, раелизация скопа юзера отсуда https://habrahabr.ru/post/335490/#comment_10359566 спасибо @eugenehr 8 | 9 | Пример использования в папке /sample 10 | 11 | ```java 12 | @SpringBootApplication 13 | @EnableTelegram 14 | @BotController 15 | public class SampleTelegramBotMvcMain implements TelegramMvcConfiguration { 16 | private static final Logger logger = LoggerFactory.getLogger(SampleTelegramBotMvcMain.class); 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(SampleTelegramBotMvcMain.class); 20 | } 21 | 22 | @Override 23 | public void configuration(TelegramBotBuilder telegramBotBuilder) { 24 | telegramBotBuilder.token('ТОкен доступа').alias("myFirsBean"); 25 | } 26 | 27 | @BotRequest("/start") 28 | BaseRequest hello(String text, 29 | Long chatId, 30 | TelegramRequest telegramRequest, 31 | TelegramBot telegramBot, 32 | Update update, 33 | Message message, 34 | Chat chat, 35 | User user 36 | ) { 37 | logger.info("Text = {}", text); 38 | logger.info("ChatId or UserId = {}", chatId); 39 | logger.info("Telegram Request = {}", telegramRequest); 40 | logger.info("TelegramBot = {}", telegramBot); 41 | logger.info("Update = {}", update); 42 | logger.info("Message = {}", message); 43 | logger.info("Chat = {}", chat); 44 | logger.info("User = {}", user); 45 | 46 | return new SendMessage(chatId, "I test the bot"); 47 | } 48 | } 49 | ``` 50 | Что реализованно: 51 | - Аннотация ```@BotController``` используется чтобы пометить класс обработчик 52 | - Аннотация ```@BotRequest``` Принимает параметр 53 | 1) path - строка фильтрации сообщения понимает запись в форме ant, т.е. ```/run ** service``` 54 | 2) messageType - Енум который опредялет тип сообщения, пока реализован MESSAGE, COMMAND и несколько внутренних для провреки возможности 55 | - возращается строка либо наследник BaseRequest(в терминах API это запрос к телеграм серверу) 56 | - библиотека так же может обрабытывать входящие параметры такие как String text полный текс пользователя к боту, Update, Message, и д.р. 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | subprojects { 2 | repositories { 3 | jcenter() 4 | } 5 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | GROUP=com.github.olegnyr 2 | VERSION_NAME=1.0.0-SNAPSHOT 3 | 4 | POM_DESCRIPTION=Java API for Telegram Bot API 5 | POM_URL=https://github.com/olegnyr/java-telegram-bot-mvc/ 6 | POM_SCM_URL=https://github.com/olegnyr/java-telegram-bot-mvc/ 7 | POM_SCM_CONNECTION=scm:git:git://github.com/OlegNyr/java-telegram-bot-mvc.git 8 | POM_SCM_DEV_CONNECTION=scm:git:git://github.com/OlegNyr/java-telegram-bot-mvc.git 9 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 10 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 11 | POM_LICENCE_DIST=repo 12 | POM_DEVELOPER_ID=olegnyr 13 | POM_DEVELOPER_NAME=Oleg Nyrkov -------------------------------------------------------------------------------- /gradle/gradle-mvn-push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | def isReleaseBuild() { 21 | return VERSION_NAME.contains("SNAPSHOT") == false 22 | } 23 | 24 | def getRepositoryUsername() { 25 | return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : "" 26 | } 27 | 28 | def getRepositoryPassword() { 29 | return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : "" 30 | } 31 | 32 | afterEvaluate { project -> 33 | uploadArchives { 34 | repositories { 35 | mavenDeployer { 36 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 37 | 38 | pom.groupId = GROUP 39 | pom.artifactId = POM_ARTIFACT_ID 40 | pom.version = VERSION_NAME 41 | 42 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 43 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 44 | } 45 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 46 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 47 | } 48 | 49 | pom.project { 50 | name POM_NAME 51 | packaging POM_PACKAGING 52 | description POM_DESCRIPTION 53 | url POM_URL 54 | 55 | scm { 56 | url POM_SCM_URL 57 | connection POM_SCM_CONNECTION 58 | developerConnection POM_SCM_DEV_CONNECTION 59 | } 60 | 61 | licenses { 62 | license { 63 | name POM_LICENCE_NAME 64 | url POM_LICENCE_URL 65 | distribution POM_LICENCE_DIST 66 | } 67 | } 68 | 69 | developers { 70 | developer { 71 | id POM_DEVELOPER_ID 72 | name POM_DEVELOPER_NAME 73 | } 74 | } 75 | } 76 | } 77 | } 78 | } 79 | 80 | signing { 81 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 82 | sign configurations.archives 83 | } 84 | 85 | task javadocJar(type: Jar) { 86 | classifier = 'javadoc' 87 | from javadoc 88 | } 89 | 90 | task sourcesJar(type: Jar) { 91 | classifier = 'sources' 92 | from sourceSets.main.allSource 93 | } 94 | 95 | artifacts { 96 | archives javadocJar 97 | archives sourcesJar 98 | } 99 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OlegNyr/java-telegram-bot-mvc/fdde03c1bba78a86e6cf44a69095a46e6dbee62f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 16 20:16:44 MSK 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /out/ 3 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'jacoco' 3 | 4 | sourceCompatibility = 1.8 5 | targetCompatibility = 1.8 6 | 7 | compileTestJava { 8 | sourceCompatibility = 1.8 9 | targetCompatibility = 1.8 10 | } 11 | 12 | dependencies { 13 | compile 'com.github.pengrad:java-telegram-bot-api:3.4.0' 14 | compile 'org.springframework:spring-context:4.3.11.RELEASE' 15 | compile 'org.springframework:spring-web:4.3.11.RELEASE' 16 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' 17 | compile group: 'com.google.guava', name: 'guava', version: '23.0' 18 | } 19 | 20 | jacoco { 21 | // See https://github.com/jacoco/jacoco/releases 22 | toolVersion = '0.7.5.201505241946' 23 | reportsDir = file("$buildDir/customJacocoReportDir") 24 | } 25 | 26 | jacocoTestReport { 27 | reports { 28 | xml.enabled true 29 | csv.enabled true 30 | html.destination "${buildDir}/reports/jacoco/test" 31 | } 32 | } 33 | 34 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle') -------------------------------------------------------------------------------- /library/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=java-telegram-bot-mvc 2 | POM_NAME=JavaTelegramBotMvc 3 | POM_PACKAGING=jar -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/HandlerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.github.telegram.mvc.handler.*; 5 | import com.pengrad.telegrambot.request.BaseRequest; 6 | import org.springframework.core.convert.ConversionService; 7 | import org.springframework.web.method.HandlerMethod; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Вызывает обработчик запроса, подготавливает параметры метода для выполнения 14 | */ 15 | public class HandlerAdapter { 16 | 17 | private final ConversionService conversionService; 18 | private final BotHandlerMethodArgumentResolverComposite argumentResolvers; 19 | private final BotHandlerMethodReturnValueHandlerComposite returnValueHandlers; 20 | 21 | public HandlerAdapter(ConversionService conversionService) { 22 | this.conversionService = conversionService; 23 | 24 | List resolvers = getDefaultArgumentResolvers(); 25 | this.argumentResolvers = new BotHandlerMethodArgumentResolverComposite().addResolvers(resolvers); 26 | 27 | List handlers = getDefaultReturnValueHandlers(); 28 | this.returnValueHandlers = new BotHandlerMethodReturnValueHandlerComposite().addHandlers(handlers); 29 | } 30 | 31 | /** 32 | * Вызывает медот представленный в handlerMethod 33 | * 34 | * @param telegramRequest описание сообщение 35 | * @param handlerMethod описание медода который нужно вызвать 36 | * @return Возвращает ответ который нужно передать пользователь 37 | * @throws Exception пробрасывает все ошибки 38 | */ 39 | BaseRequest handle(TelegramRequest telegramRequest, HandlerMethod handlerMethod) throws Exception { 40 | TelegramInvocableHandlerMethod invocableMethod = new TelegramInvocableHandlerMethod(handlerMethod); 41 | invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers); 42 | invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers); 43 | invocableMethod.invokeAndHandle(telegramRequest); 44 | return telegramRequest.getBaseRequest(); 45 | } 46 | 47 | 48 | private List getDefaultArgumentResolvers() { 49 | List resolvers = new ArrayList<>(); 50 | 51 | // Annotation-based argument resolution 52 | resolvers.add(new BotTextVariableMethodArgumentResolver(conversionService)); 53 | resolvers.add(new BotRequestMethodArgumentResolver()); 54 | return resolvers; 55 | } 56 | 57 | public List getDefaultReturnValueHandlers() { 58 | List valueHandlers = new ArrayList<>(); 59 | valueHandlers.add(new BotBaseRequestMethodProcessor()); 60 | valueHandlers.add(new BotResponseBodyMethodProcessor(conversionService)); 61 | return valueHandlers; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/HandlerMethodContainer.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | 4 | import com.github.telegram.mvc.api.TelegramRequest; 5 | import org.springframework.web.method.HandlerMethod; 6 | 7 | import java.lang.reflect.Method; 8 | import java.util.LinkedHashMap; 9 | import java.util.Map; 10 | import java.util.Set; 11 | 12 | class HandlerMethodContainer { 13 | private final Map mappingLookup = new LinkedHashMap<>(); 14 | 15 | public HandlerMethod lookupHandlerMethod(TelegramRequest telegramRequest) { 16 | for (RequestMappingInfo requestMappingInfo : mappingLookup.keySet()) { 17 | if(!requestMappingInfo.getMessageTypes().contains(telegramRequest.getMessageType())){ 18 | continue; 19 | } 20 | RequestMappingInfo matchingCondition = requestMappingInfo.getMatchingCondition(telegramRequest.getText()); 21 | if (matchingCondition != null) { 22 | Set patterns = matchingCondition.getPatterns(); 23 | if (!patterns.isEmpty()) { 24 | String basePattern = patterns.iterator().next(); 25 | Map templateVariables = 26 | matchingCondition.getPathMatcher().extractUriTemplateVariables(basePattern, telegramRequest.getText()); 27 | telegramRequest.setBasePattern(basePattern); 28 | telegramRequest.setTemplateVariables(templateVariables); 29 | } 30 | return mappingLookup.get(requestMappingInfo); 31 | } 32 | } 33 | return null; 34 | } 35 | 36 | 37 | public void registerController(Object bean, Method method, RequestMappingInfo mappingInfo) { 38 | HandlerMethod handlerMethod = new HandlerMethod(bean, method); 39 | mappingLookup.put(mappingInfo, handlerMethod); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/RequestDispatcher.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.github.telegram.mvc.api.TelegramSession; 5 | import com.github.telegram.mvc.config.TelegramScope; 6 | import com.pengrad.telegrambot.Callback; 7 | import com.pengrad.telegrambot.TelegramBot; 8 | import com.pengrad.telegrambot.model.Update; 9 | import com.pengrad.telegrambot.request.BaseRequest; 10 | import com.pengrad.telegrambot.response.BaseResponse; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.core.task.TaskExecutor; 15 | import org.springframework.web.method.HandlerMethod; 16 | 17 | import java.io.IOException; 18 | 19 | 20 | public class RequestDispatcher { 21 | private static final Logger logger = LoggerFactory.getLogger(RequestDispatcher.class); 22 | 23 | private final HandlerMethodContainer handlerMethodContainer; 24 | private final HandlerAdapter handlerAdapter; 25 | private final TaskExecutor taskExecutor; 26 | 27 | @Autowired 28 | private TelegramSession telegramSession; 29 | 30 | public RequestDispatcher(HandlerMethodContainer handlerMethodContainer, 31 | HandlerAdapter handlerAdapter, 32 | TaskExecutor taskExecutor) { 33 | this.handlerMethodContainer = handlerMethodContainer; 34 | this.handlerAdapter = handlerAdapter; 35 | this.taskExecutor = taskExecutor; 36 | } 37 | 38 | /** 39 | * Находит обработчик запроса пользователя и вызывает его, далее передает в телеграмм ответ обработчика 40 | * @param update Запрос пользователя 41 | * @param telegramBot какой бот принял запрос 42 | */ 43 | public void execute(Update update, TelegramBot telegramBot) { 44 | taskExecutor.execute(() -> { 45 | TelegramRequest telegramRequest = new TelegramRequest(update, telegramBot); 46 | 47 | HandlerMethod handlerMethod = handlerMethodContainer.lookupHandlerMethod(telegramRequest); 48 | if (handlerMethod == null) { 49 | logger.error("Not found controller for {} type {}", telegramRequest.getText(), telegramRequest.getMessageType()); 50 | } 51 | 52 | TelegramScope.setIdThreadLocal(telegramRequest.chatId()); 53 | telegramRequest.setSession(telegramSession); 54 | 55 | BaseRequest baseRequest = null; 56 | try { 57 | baseRequest = handlerAdapter.handle(telegramRequest, handlerMethod); 58 | if (baseRequest != null) { 59 | logger.debug("Request {}", baseRequest); 60 | telegramBot.execute(baseRequest, new Callback() { 61 | @Override 62 | public void onResponse(BaseRequest request, BaseResponse response) { 63 | telegramRequest.complete(response); 64 | } 65 | 66 | @Override 67 | public void onFailure(BaseRequest request, IOException e) { 68 | logger.error("Send request callback {}", telegramRequest.chatId(), e); 69 | telegramRequest.error(e); 70 | } 71 | }); 72 | TelegramScope.removeId(); 73 | } else { 74 | telegramRequest.complete(null); 75 | logger.debug("handlerAdapter return null"); 76 | } 77 | } catch (Exception e) { 78 | telegramRequest.error(e); 79 | logger.info("Execute error handlerAdapter {}", handlerAdapter, e); 80 | } 81 | }); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/RequestMappingInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | import com.github.telegram.mvc.api.MessageType; 4 | import com.google.common.collect.ImmutableSet; 5 | import com.google.common.collect.Sets; 6 | import org.springframework.util.AntPathMatcher; 7 | import org.springframework.util.PathMatcher; 8 | 9 | import java.util.*; 10 | 11 | /** 12 | * Описание метода обработки 13 | */ 14 | class RequestMappingInfo { 15 | 16 | private final Set patterns; 17 | private final PathMatcher pathMatcher; 18 | private final Set messageTypes; 19 | 20 | private RequestMappingInfo(Collection patterns, Collection messageTypes) { 21 | this.patterns = Collections.unmodifiableSet(Sets.newLinkedHashSet(patterns)); 22 | this.pathMatcher = new AntPathMatcher(); 23 | this.messageTypes = ImmutableSet.copyOf(messageTypes); 24 | } 25 | 26 | public static Builder newBuilder() { 27 | return new Builder(); 28 | } 29 | 30 | 31 | public static final class Builder { 32 | private String[] path; 33 | private MessageType[] messageTypes; 34 | 35 | private Builder() { 36 | } 37 | 38 | public Builder path(String... val) { 39 | path = val; 40 | return this; 41 | } 42 | 43 | public Builder messageType(MessageType... val) { 44 | messageTypes = val; 45 | return this; 46 | } 47 | 48 | public RequestMappingInfo build() { 49 | return new RequestMappingInfo(asList(path), asList(messageTypes)); 50 | } 51 | } 52 | 53 | private static List asList(T... patterns) { 54 | return (patterns != null ? Arrays.asList(patterns) : Collections.emptyList()); 55 | } 56 | 57 | public RequestMappingInfo getMatchingCondition(String requestText) { 58 | if (this.patterns.isEmpty()) { 59 | return this; 60 | } 61 | if (requestText == null) { 62 | requestText = ""; 63 | } 64 | List matches = getMatchingPatterns(requestText); 65 | 66 | return matches.isEmpty() ? null : this; 67 | } 68 | 69 | public List getMatchingPatterns(String lookupPath) { 70 | List matches = new ArrayList(); 71 | for (String pattern : this.patterns) { 72 | String match = getMatchingPattern(pattern, lookupPath); 73 | if (match != null) { 74 | matches.add(match); 75 | } 76 | } 77 | Collections.sort(matches, this.pathMatcher.getPatternComparator(lookupPath)); 78 | return matches; 79 | } 80 | 81 | private String getMatchingPattern(String pattern, String lookupPath) { 82 | if (pattern.equals(lookupPath)) { 83 | return pattern; 84 | } 85 | if (this.pathMatcher.match(pattern, lookupPath)) { 86 | return pattern; 87 | } 88 | return null; 89 | } 90 | 91 | public Set getPatterns() { 92 | return patterns; 93 | } 94 | 95 | public PathMatcher getPathMatcher() { 96 | return pathMatcher; 97 | } 98 | 99 | public Set getMessageTypes() { 100 | return messageTypes; 101 | } 102 | 103 | @Override 104 | public boolean equals(Object o) { 105 | if (this == o) return true; 106 | if (!(o instanceof RequestMappingInfo)) return false; 107 | RequestMappingInfo that = (RequestMappingInfo) o; 108 | return Objects.equals(patterns, that.patterns) && 109 | Objects.equals(messageTypes, that.messageTypes); 110 | } 111 | 112 | @Override 113 | public int hashCode() { 114 | return Objects.hash(patterns, messageTypes); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/TelegramConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | import com.github.telegram.mvc.api.TelegramSession; 4 | import com.github.telegram.mvc.config.*; 5 | import com.google.common.base.Supplier; 6 | import com.google.common.base.Suppliers; 7 | import com.google.common.collect.Lists; 8 | import com.pengrad.telegrambot.TelegramBot; 9 | import okhttp3.Dispatcher; 10 | import okhttp3.OkHttpClient; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.BeansException; 14 | import org.springframework.beans.factory.ObjectProvider; 15 | import org.springframework.beans.factory.config.BeanFactoryPostProcessor; 16 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 17 | import org.springframework.context.ApplicationListener; 18 | import org.springframework.context.EnvironmentAware; 19 | import org.springframework.context.annotation.Bean; 20 | import org.springframework.context.annotation.Configuration; 21 | import org.springframework.context.annotation.Scope; 22 | import org.springframework.context.annotation.ScopedProxyMode; 23 | import org.springframework.context.event.ContextRefreshedEvent; 24 | import org.springframework.core.annotation.AnnotationAwareOrderComparator; 25 | import org.springframework.core.annotation.Order; 26 | import org.springframework.core.convert.ConversionService; 27 | import org.springframework.core.env.Environment; 28 | import org.springframework.core.task.TaskExecutor; 29 | import org.springframework.core.task.support.ExecutorServiceAdapter; 30 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 31 | 32 | import java.util.ArrayList; 33 | import java.util.List; 34 | import java.util.concurrent.TimeUnit; 35 | 36 | import static com.google.common.base.Suppliers.*; 37 | 38 | /** 39 | * Конфигурирование бинов 40 | */ 41 | @Configuration 42 | public class TelegramConfiguration implements BeanFactoryPostProcessor, EnvironmentAware { 43 | 44 | private static final Logger logger = LoggerFactory.getLogger(TelegramConfiguration.class); 45 | private static final String TELEGRAM_BOT_TOKEN = "telegram.bot.token"; 46 | private Environment environment; 47 | private ConfigurableListableBeanFactory beanFactory; 48 | 49 | @Bean 50 | RequestDispatcher requestDispatcher(ConversionService conversionService, 51 | List telegramMvcConfigurations, 52 | ObjectProvider taskExecutor) { 53 | TaskExecutor taskExecutorLocal = taskExecutor.getIfAvailable(); 54 | if (taskExecutorLocal == null) { 55 | ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); 56 | threadPoolTaskExecutor.setCorePoolSize(15); 57 | threadPoolTaskExecutor.setMaxPoolSize(100); 58 | threadPoolTaskExecutor.initialize(); 59 | taskExecutorLocal = threadPoolTaskExecutor; 60 | } 61 | RequestDispatcher requestDispatcher = new RequestDispatcher(handlerMethodContainer(), new HandlerAdapter(conversionService), taskExecutorLocal); 62 | registerTelegramBotService(requestDispatcher, telegramMvcConfigurations, getOkHttpClientSupplier(taskExecutorLocal)); 63 | return requestDispatcher; 64 | } 65 | 66 | private Supplier getOkHttpClientSupplier(TaskExecutor taskExecutorLocal) { 67 | return new Supplier() { 68 | @Override 69 | public OkHttpClient get() { 70 | return new OkHttpClient() 71 | .newBuilder() 72 | .dispatcher(new Dispatcher(new ExecutorServiceAdapter(taskExecutorLocal))) 73 | .build(); 74 | } 75 | }; 76 | } 77 | 78 | @Bean 79 | @Scope(value = TelegramScope.SCOPE, proxyMode = ScopedProxyMode.TARGET_CLASS) 80 | TelegramSession telegramSession() { 81 | return new TelegramSession(); 82 | } 83 | 84 | private void registerTelegramBotService(RequestDispatcher requestDispatcher, List telegramMvcConfigurations, Supplier httpClientSupplier) { 85 | TelegramBotProperties telegramBotProperties = getTelegramBotProperties(telegramMvcConfigurations); 86 | if (!telegramBotProperties.iterator().hasNext()) { 87 | logger.warn("Не найдено не одной настройки бота"); 88 | } else { 89 | for (TelegramBotProperty telegramBotProperty : telegramBotProperties) { 90 | //Если не задан OkHttpClient создадим свой который будет юзать наш TaskExecutor 91 | if (telegramBotProperty.getOkHttpClient() == null) { 92 | telegramBotProperty = 93 | TelegramBotProperty 94 | .newBuilder(telegramBotProperty) 95 | .okHttpClient(memoize(httpClientSupplier).get()) 96 | .build(); 97 | } 98 | 99 | TelegramBot telegramBot = createTelegramBot(telegramBotProperty); 100 | TelegramService telegramService = new TelegramService(telegramBot, requestDispatcher); 101 | beanFactory.registerSingleton("telegramService" + telegramBotProperty.getAlias(), telegramService); 102 | } 103 | } 104 | } 105 | 106 | @Bean 107 | @Order() 108 | ApplicationListener runnerTelegramService(List telegramServices) { 109 | return new ApplicationListener() { 110 | @Override 111 | public void onApplicationEvent(ContextRefreshedEvent event) { 112 | for (TelegramService telegramService : telegramServices) { 113 | telegramService.start(); 114 | } 115 | } 116 | }; 117 | } 118 | 119 | private TelegramBot createTelegramBot(TelegramBotProperty telegramBotProperty) { 120 | return new TelegramBot.Builder(telegramBotProperty.getToken()) 121 | .okHttpClient(telegramBotProperty.getOkHttpClient()) 122 | .updateListenerSleep(telegramBotProperty.getTimeOutMillis()) 123 | .apiUrl(telegramBotProperty.getUrl()) 124 | .build(); 125 | } 126 | 127 | private TelegramBotProperties getTelegramBotProperties(List telegramMvcConfigurations) { 128 | TelegramBotProperties telegramBotProperties = new TelegramBotProperties(); 129 | ArrayList telegramMvcConfigurationsSort = Lists.newArrayList(telegramMvcConfigurations); 130 | AnnotationAwareOrderComparator.sort(telegramMvcConfigurationsSort); 131 | for (TelegramMvcConfiguration telegramMvcConfiguration : telegramMvcConfigurationsSort) { 132 | TelegramBotBuilder telegramBotBuilder = new TelegramBotBuilder(); 133 | telegramMvcConfiguration.configuration(telegramBotBuilder); 134 | telegramBotProperties.addAll(telegramBotBuilder.build()); 135 | } 136 | if (telegramBotProperties == null) { 137 | if (environment.containsProperty(TELEGRAM_BOT_TOKEN)) { 138 | telegramBotProperties.addTelegramProperty(new TelegramBotProperty(environment.getProperty(TELEGRAM_BOT_TOKEN))); 139 | } 140 | } 141 | return telegramBotProperties; 142 | } 143 | 144 | @Bean 145 | HandlerMethodContainer handlerMethodContainer() { 146 | return new HandlerMethodContainer(); 147 | } 148 | 149 | @Bean 150 | TelegramControllerBeanPostProcessor telegramControllerBeanPostProcessor() { 151 | return new TelegramControllerBeanPostProcessor(handlerMethodContainer()); 152 | } 153 | 154 | 155 | @Override 156 | public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { 157 | this.beanFactory = beanFactory; 158 | beanFactory.registerScope(TelegramScope.SCOPE, new TelegramScope(beanFactory, TimeUnit.HOURS.toMillis(1))); 159 | } 160 | 161 | @Override 162 | public void setEnvironment(Environment environment) { 163 | this.environment = environment; 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/TelegramControllerBeanPostProcessor.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | import com.github.telegram.mvc.api.BotController; 4 | import com.github.telegram.mvc.api.BotRequest; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.aop.support.AopUtils; 8 | import org.springframework.beans.BeansException; 9 | import org.springframework.beans.factory.SmartInitializingSingleton; 10 | import org.springframework.beans.factory.config.BeanPostProcessor; 11 | import org.springframework.core.MethodIntrospector; 12 | import org.springframework.core.annotation.AnnotatedElementUtils; 13 | import org.springframework.core.annotation.AnnotationUtils; 14 | 15 | import java.lang.reflect.Method; 16 | import java.util.Collections; 17 | import java.util.Map; 18 | import java.util.Set; 19 | import java.util.concurrent.ConcurrentHashMap; 20 | 21 | /** 22 | * Бин пост процессор, ищет классы помеченные анотацией {@link BotController}, далее ищет анотацию {@link BotRequest} 23 | * в методах и передает мета информацию в {@link HandlerMethodContainer} 24 | */ 25 | public class TelegramControllerBeanPostProcessor implements BeanPostProcessor, SmartInitializingSingleton { 26 | private static final Logger logger = LoggerFactory.getLogger(TelegramControllerBeanPostProcessor.class); 27 | private HandlerMethodContainer botHandlerMethodContainer; 28 | 29 | private final Set> nonAnnotatedClasses = 30 | Collections.newSetFromMap(new ConcurrentHashMap, Boolean>(64)); 31 | 32 | public TelegramControllerBeanPostProcessor(HandlerMethodContainer botHandlerMethodContainer) { 33 | this.botHandlerMethodContainer = botHandlerMethodContainer; 34 | } 35 | 36 | @Override 37 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 38 | return bean; 39 | } 40 | 41 | @Override 42 | public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 43 | Class targetClass = AopUtils.getTargetClass(bean); 44 | if (!nonAnnotatedClasses.contains(targetClass)) { 45 | if (AnnotationUtils.findAnnotation(targetClass, BotController.class) != null) { 46 | Map annotatedMethods = findAnnotatedMethodsBotRequest(targetClass); 47 | if (annotatedMethods.isEmpty()) { 48 | nonAnnotatedClasses.add(targetClass); 49 | if (logger.isTraceEnabled()) { 50 | logger.trace("No @BotRequest annotations found on bean class: {}", bean.getClass()); 51 | } 52 | } else { 53 | // Non-empty set of methods 54 | annotatedMethods.forEach((method, mappingInfo) -> { 55 | Method invocableMethod = AopUtils.selectInvocableMethod(method, targetClass); 56 | botHandlerMethodContainer.registerController(bean, invocableMethod, mappingInfo); 57 | }); 58 | } 59 | } else { 60 | nonAnnotatedClasses.add(targetClass); 61 | } 62 | } 63 | return bean; 64 | } 65 | 66 | private Map findAnnotatedMethodsBotRequest(Class targetClass) { 67 | return MethodIntrospector.selectMethods(targetClass, 68 | (MethodIntrospector.MetadataLookup) method -> { 69 | BotRequest requestMapping = AnnotatedElementUtils.findMergedAnnotation(method, BotRequest.class); 70 | if (requestMapping == null) return null; 71 | 72 | return RequestMappingInfo 73 | .newBuilder() 74 | .path(requestMapping.path()) 75 | .messageType(requestMapping.messageType()) 76 | .build(); 77 | 78 | }); 79 | } 80 | 81 | @Override 82 | public void afterSingletonsInstantiated() { 83 | nonAnnotatedClasses.clear(); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/TelegramInvocableHandlerMethod.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.github.telegram.mvc.handler.BotHandlerMethodArgumentResolverComposite; 5 | import com.github.telegram.mvc.handler.BotHandlerMethodReturnValueHandlerComposite; 6 | import org.springframework.core.DefaultParameterNameDiscoverer; 7 | import org.springframework.core.MethodParameter; 8 | import org.springframework.core.ParameterNameDiscoverer; 9 | import org.springframework.util.ClassUtils; 10 | import org.springframework.util.ReflectionUtils; 11 | import org.springframework.web.method.HandlerMethod; 12 | 13 | import java.lang.reflect.InvocationTargetException; 14 | import java.lang.reflect.Method; 15 | import java.util.Arrays; 16 | 17 | 18 | class TelegramInvocableHandlerMethod extends HandlerMethod { 19 | 20 | private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); 21 | private BotHandlerMethodArgumentResolverComposite argumentResolvers; 22 | private BotHandlerMethodReturnValueHandlerComposite returnValueHandlers; 23 | 24 | /** 25 | * Create an instance from a bean instance and a method. 26 | */ 27 | public TelegramInvocableHandlerMethod(HandlerMethod handlerMethod) { 28 | super(handlerMethod); 29 | } 30 | 31 | public void invokeAndHandle(TelegramRequest telegramRequest) throws Exception { 32 | Object returnValue = invokeForRequest(telegramRequest); 33 | if (returnValue == null) { 34 | return; 35 | } 36 | try { 37 | this.returnValueHandlers.handleReturnValue( 38 | returnValue, getReturnValueType(returnValue), telegramRequest); 39 | } catch (Exception ex) { 40 | if (logger.isTraceEnabled()) { 41 | logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex); 42 | } 43 | throw ex; 44 | } 45 | } 46 | 47 | private Object invokeForRequest(TelegramRequest telegramRequest) throws Exception { 48 | Object[] args = getMethodArgumentValues(telegramRequest); 49 | if (logger.isTraceEnabled()) { 50 | logger.trace("Invoking '" + ClassUtils.getQualifiedMethodName(getMethod(), getBeanType()) + 51 | "' with arguments " + Arrays.toString(args)); 52 | } 53 | Object returnValue = doInvoke(args); 54 | if (logger.isTraceEnabled()) { 55 | logger.trace("Method [" + ClassUtils.getQualifiedMethodName(getMethod(), getBeanType()) + 56 | "] returned [" + returnValue + "]"); 57 | } 58 | return returnValue; 59 | } 60 | 61 | private Object doInvoke(Object[] args) throws Exception { 62 | ReflectionUtils.makeAccessible(getBridgedMethod()); 63 | try { 64 | return getBridgedMethod().invoke(getBean(), args); 65 | } catch (IllegalArgumentException ex) { 66 | assertTargetBean(getBridgedMethod(), getBean(), args); 67 | String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument"); 68 | throw new IllegalStateException(getInvocationErrorMessage(text, args), ex); 69 | } catch (InvocationTargetException ex) { 70 | // Unwrap for HandlerExceptionResolvers ... 71 | Throwable targetException = ex.getTargetException(); 72 | if (targetException instanceof RuntimeException) { 73 | throw (RuntimeException) targetException; 74 | } else if (targetException instanceof Error) { 75 | throw (Error) targetException; 76 | } else if (targetException instanceof Exception) { 77 | throw (Exception) targetException; 78 | } else { 79 | String text = getInvocationErrorMessage("Failed to invoke handler method", args); 80 | throw new IllegalStateException(text, targetException); 81 | } 82 | } 83 | } 84 | 85 | private Object[] getMethodArgumentValues(TelegramRequest telegramRequest) throws Exception { 86 | MethodParameter[] parameters = getMethodParameters(); 87 | Object[] args = new Object[parameters.length]; 88 | for (int i = 0; i < parameters.length; i++) { 89 | MethodParameter parameter = parameters[i]; 90 | parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); 91 | args[i] = resolveProvidedArgument(parameter); 92 | if (args[i] != null) { 93 | continue; 94 | } 95 | if (this.argumentResolvers.supportsParameter(parameter)) { 96 | try { 97 | args[i] = this.argumentResolvers.resolveArgument(parameter, telegramRequest); 98 | continue; 99 | } catch (Exception ex) { 100 | if (logger.isDebugEnabled()) { 101 | logger.debug(getArgumentResolutionErrorMessage("Failed to resolve", i), ex); 102 | } 103 | throw ex; 104 | } 105 | } 106 | if (args[i] == null) { 107 | throw new IllegalStateException("Could not resolve method parameter at index " + 108 | parameter.getParameterIndex() + " in " + parameter.getMethod().toGenericString() + 109 | ": " + getArgumentResolutionErrorMessage("No suitable resolver for", i)); 110 | } 111 | } 112 | return args; 113 | } 114 | 115 | private String getArgumentResolutionErrorMessage(String text, int index) { 116 | Class paramType = getMethodParameters()[index].getParameterType(); 117 | return text + " argument " + index + " of type '" + paramType.getName() + "'"; 118 | } 119 | 120 | 121 | /** 122 | * Attempt to resolve a method parameter from the list of provided argument values. 123 | */ 124 | private Object resolveProvidedArgument(MethodParameter parameter, Object... providedArgs) { 125 | if (providedArgs == null) { 126 | return null; 127 | } 128 | for (Object providedArg : providedArgs) { 129 | if (parameter.getParameterType().isInstance(providedArg)) { 130 | return providedArg; 131 | } 132 | } 133 | return null; 134 | } 135 | 136 | 137 | private void assertTargetBean(Method method, Object targetBean, Object[] args) { 138 | Class methodDeclaringClass = method.getDeclaringClass(); 139 | Class targetBeanClass = targetBean.getClass(); 140 | if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) { 141 | String text = "The mapped handler method class '" + methodDeclaringClass.getName() + 142 | "' is not an instance of the actual controller bean class '" + 143 | targetBeanClass.getName() + "'. If the controller requires proxying " + 144 | "(e.g. due to @Transactional), please use class-based proxying."; 145 | throw new IllegalStateException(getInvocationErrorMessage(text, args)); 146 | } 147 | } 148 | 149 | 150 | private String getInvocationErrorMessage(String text, Object[] resolvedArgs) { 151 | StringBuilder sb = new StringBuilder(getDetailedErrorMessage(text)); 152 | sb.append("Resolved arguments: \n"); 153 | for (int i = 0; i < resolvedArgs.length; i++) { 154 | sb.append("[").append(i).append("] "); 155 | if (resolvedArgs[i] == null) { 156 | sb.append("[null] \n"); 157 | } else { 158 | sb.append("[type=").append(resolvedArgs[i].getClass().getName()).append("] "); 159 | sb.append("[value=").append(resolvedArgs[i]).append("]\n"); 160 | } 161 | } 162 | return sb.toString(); 163 | } 164 | 165 | /** 166 | * Adds HandlerMethod details such as the bean type and method signature to the message. 167 | * 168 | * @param text error message to append the HandlerMethod details to 169 | */ 170 | protected String getDetailedErrorMessage(String text) { 171 | StringBuilder sb = new StringBuilder(text).append("\n"); 172 | sb.append("HandlerMethod details: \n"); 173 | sb.append("Controller [").append(getBeanType().getName()).append("]\n"); 174 | sb.append("Method [").append(getBridgedMethod().toGenericString()).append("]\n"); 175 | return sb.toString(); 176 | } 177 | 178 | public void setHandlerMethodArgumentResolvers(BotHandlerMethodArgumentResolverComposite handlerMethodArgumentResolvers) { 179 | this.argumentResolvers = handlerMethodArgumentResolvers; 180 | } 181 | 182 | public void setHandlerMethodReturnValueHandlers(BotHandlerMethodReturnValueHandlerComposite returnValueHandlers) { 183 | this.returnValueHandlers = returnValueHandlers; 184 | } 185 | 186 | private String getReturnValueHandlingErrorMessage(String message, Object returnValue) { 187 | StringBuilder sb = new StringBuilder(message); 188 | if (returnValue != null) { 189 | sb.append(" [type=").append(returnValue.getClass().getName()).append("]"); 190 | } 191 | sb.append(" [value=").append(returnValue).append("]"); 192 | return getDetailedErrorMessage(sb.toString()); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/TelegramService.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc; 2 | 3 | 4 | import com.pengrad.telegrambot.TelegramBot; 5 | import com.pengrad.telegrambot.UpdatesListener; 6 | import com.pengrad.telegrambot.model.Update; 7 | import com.pengrad.telegrambot.request.GetUpdates; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | public class TelegramService { 12 | private static final Logger logger = LoggerFactory.getLogger(TelegramService.class); 13 | private final TelegramBot telegramBot; 14 | private final RequestDispatcher botRequestDispatcher; 15 | 16 | public TelegramService(TelegramBot telegramBot, RequestDispatcher botRequestDispatcher) { 17 | this.telegramBot = telegramBot; 18 | this.botRequestDispatcher = botRequestDispatcher; 19 | } 20 | 21 | public void start() { 22 | telegramBot.setUpdatesListener(updates -> { 23 | for (Update update : updates) { 24 | try { 25 | botRequestDispatcher.execute(update, telegramBot); 26 | } catch (Exception e) { 27 | logger.error("{}", e); 28 | } 29 | } 30 | return UpdatesListener.CONFIRMED_UPDATES_ALL; 31 | }, new GetUpdates()); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/BotController.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | 4 | import org.springframework.stereotype.Component; 5 | 6 | import java.lang.annotation.*; 7 | 8 | /** 9 | * Анотация помечаем контроллер который будет обрабатывать команды 10 | */ 11 | @Target({ElementType.TYPE}) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Documented 14 | @Component 15 | public @interface BotController { 16 | } 17 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/BotRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | 4 | import org.springframework.core.annotation.AliasFor; 5 | 6 | import java.lang.annotation.*; 7 | 8 | import static com.github.telegram.mvc.api.MessageType.COMMAND; 9 | import static com.github.telegram.mvc.api.MessageType.MESSAGE; 10 | 11 | 12 | @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Documented 15 | public @interface BotRequest { 16 | 17 | @AliasFor("path") 18 | String[] value() default {}; 19 | 20 | @AliasFor("value") 21 | String[] path() default {}; 22 | 23 | MessageType[] messageType() default {MESSAGE, COMMAND}; 24 | } 25 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/EnableTelegram.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | import com.github.telegram.mvc.TelegramConfiguration; 4 | import org.springframework.context.annotation.Import; 5 | 6 | import java.lang.annotation.*; 7 | 8 | @Target({ElementType.TYPE}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Documented 11 | @Import(TelegramConfiguration.class) 12 | public @interface EnableTelegram { 13 | } 14 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/MessageType.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | public enum MessageType { 4 | MESSAGE, 5 | COMMAND, 6 | INLINE_QUERY, 7 | INLINE_CHOSEN, 8 | INLINE_CALLBACK 9 | } 10 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/TelegramRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | import com.pengrad.telegrambot.TelegramBot; 4 | import com.pengrad.telegrambot.model.*; 5 | import com.pengrad.telegrambot.request.BaseRequest; 6 | import com.pengrad.telegrambot.response.BaseResponse; 7 | 8 | import java.util.Map; 9 | 10 | public class TelegramRequest { 11 | /** 12 | * Оригинальный запрос пользователя 13 | */ 14 | private final Update update; 15 | /** 16 | * Сообщение пользователя 17 | */ 18 | private final Message message; 19 | /** 20 | * Идентификатор беседы 21 | */ 22 | private final Long chatId; 23 | /** 24 | * Ссылка на сущьность Chat 25 | */ 26 | private final Chat chat; 27 | /** 28 | * Ссылка на сущьность User 29 | */ 30 | 31 | private final User user; 32 | /** 33 | * строка ввода пользователя 34 | */ 35 | private final String text; 36 | /** 37 | * Сервис бота 38 | */ 39 | private TelegramBot telegramBot; 40 | 41 | /** 42 | * Сессия диалога 43 | */ 44 | private TelegramSession session; 45 | /** 46 | * Тип запроса 47 | */ 48 | private MessageType messageType = MessageType.MESSAGE; 49 | 50 | /** 51 | * переменные распарсенные из запроса 52 | */ 53 | private Map templateVariables; 54 | /** 55 | * Паттрен для поиска запроса 56 | */ 57 | private String basePattern; 58 | /** 59 | * Запрос который отправим в телеграмм 60 | */ 61 | private BaseRequest baseRequest; 62 | private BaseResponse baseResponse; 63 | /** 64 | * Ответ который ответил телеграмм 65 | */ 66 | private boolean responseOk; 67 | private String responseText; 68 | 69 | public TelegramRequest(Update update, TelegramBot telegramBot) { 70 | this.update = update; 71 | this.message = firstNonNull(update.message(), 72 | update.editedMessage(), 73 | update.channelPost(), 74 | update.editedChannelPost()); 75 | 76 | this.telegramBot = telegramBot; 77 | this.messageType = MessageType.MESSAGE; 78 | if (message != null) { 79 | this.user = firstNonNull(message.from(), message.leftChatMember(), message.forwardFrom()); 80 | this.chat = firstNonNull(message.chat(), message.forwardFromChat()); 81 | this.text = message.text(); 82 | if (text != null && text.startsWith("/")) { 83 | this.messageType = MessageType.COMMAND; 84 | } 85 | } else { 86 | InlineQuery inlineQuery = update.inlineQuery(); 87 | if (inlineQuery != null) { 88 | this.user = inlineQuery.from(); 89 | this.text = inlineQuery.query(); 90 | this.chat = null; 91 | this.messageType = MessageType.INLINE_QUERY; 92 | } else { 93 | this.chat = null; 94 | ChosenInlineResult chosenInlineResult = update.chosenInlineResult(); 95 | if (chosenInlineResult != null) { 96 | this.user = chosenInlineResult.from(); 97 | this.text = chosenInlineResult.query(); 98 | this.messageType = MessageType.INLINE_CHOSEN; 99 | } else { 100 | CallbackQuery callbackQuery = update.callbackQuery(); 101 | if (callbackQuery != null) { 102 | this.user = callbackQuery.from(); 103 | this.text = callbackQuery.data(); 104 | this.messageType = MessageType.INLINE_CALLBACK; 105 | } else { 106 | this.messageType = MessageType.MESSAGE; 107 | this.user = null; 108 | this.text = null; 109 | } 110 | } 111 | } 112 | } 113 | if (chat != null) { 114 | chatId = chat.id(); 115 | } else if (user != null) { 116 | chatId = Long.valueOf(user.id()); 117 | } else { 118 | chatId = Long.valueOf(update.updateId()); 119 | } 120 | 121 | } 122 | 123 | public void setBaseRequest(BaseRequest baseRequest) { 124 | this.baseRequest = baseRequest; 125 | } 126 | 127 | public void setTemplateVariables(Map templateVariables) { 128 | this.templateVariables = templateVariables; 129 | } 130 | 131 | public void setBasePattern(String basePattern) { 132 | this.basePattern = basePattern; 133 | } 134 | 135 | public void setSession(TelegramSession session) { 136 | this.session = session; 137 | } 138 | 139 | public void complete(BaseResponse baseResponse) { 140 | if (baseResponse != null) { 141 | this.responseOk = baseResponse.isOk(); 142 | this.baseResponse = baseResponse; 143 | } else { 144 | this.responseOk = true; 145 | } 146 | } 147 | 148 | public void error(Exception e) { 149 | this.responseOk = false; 150 | this.responseText = e.getMessage(); 151 | } 152 | 153 | public long chatId() { 154 | return chatId; 155 | } 156 | 157 | private static T firstNonNull(T... messages) { 158 | for (T message : messages) { 159 | if (message != null) { 160 | return message; 161 | } 162 | } 163 | return null; 164 | } 165 | 166 | public Update getUpdate() { 167 | return update; 168 | } 169 | 170 | public Message getMessage() { 171 | return message; 172 | } 173 | 174 | public Long getChatId() { 175 | return chatId; 176 | } 177 | 178 | public Chat getChat() { 179 | return chat; 180 | } 181 | 182 | public User getUser() { 183 | return user; 184 | } 185 | 186 | public String getText() { 187 | return text; 188 | } 189 | 190 | public TelegramBot getTelegramBot() { 191 | return telegramBot; 192 | } 193 | 194 | public TelegramSession getSession() { 195 | return session; 196 | } 197 | 198 | public MessageType getMessageType() { 199 | return messageType; 200 | } 201 | 202 | public Map getTemplateVariables() { 203 | return templateVariables; 204 | } 205 | 206 | public String getBasePattern() { 207 | return basePattern; 208 | } 209 | 210 | public BaseRequest getBaseRequest() { 211 | return baseRequest; 212 | } 213 | 214 | public BaseResponse getBaseResponse() { 215 | return baseResponse; 216 | } 217 | 218 | public boolean isResponseOk() { 219 | return responseOk; 220 | } 221 | 222 | public String getResponseText() { 223 | return responseText; 224 | } 225 | 226 | @Override 227 | public String toString() { 228 | final StringBuilder sb = new StringBuilder("TelegramRequest{"); 229 | sb.append("chatId=").append(chatId); 230 | sb.append(", chat=").append(chat); 231 | sb.append(", user=").append(user); 232 | sb.append(", text='").append(text).append('\''); 233 | sb.append(", messageType=").append(messageType); 234 | sb.append('}'); 235 | return sb.toString(); 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/TelegramSession.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | import java.util.concurrent.ConcurrentHashMap; 4 | 5 | public class TelegramSession { 6 | private ConcurrentHashMap attribute; 7 | 8 | public ConcurrentHashMap getAttribute() { 9 | return attribute; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/api/TextVariable.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.api; 2 | 3 | import org.springframework.core.annotation.AliasFor; 4 | 5 | import java.lang.annotation.*; 6 | 7 | @Target(ElementType.PARAMETER) 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Documented 10 | public @interface TextVariable { 11 | 12 | /** 13 | * Алиас для параметра 14 | * @return Имя переменных из запроса 15 | */ 16 | @AliasFor("name") 17 | String value() default ""; 18 | 19 | /** 20 | * Имя параметра 21 | * @return Имя переменных из запроса 22 | * 23 | */ 24 | @AliasFor("value") 25 | String name() default ""; 26 | 27 | boolean required() default true; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/config/TelegramBotBuilder.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.config; 2 | 3 | import okhttp3.OkHttpClient; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | /** 10 | * Билдер конфигурации бота 11 | */ 12 | public class TelegramBotBuilder { 13 | 14 | private List telegramBotProperties = new ArrayList<>(); 15 | private TelegramBotProperty.Builder lastBuilder; 16 | 17 | public TelegramBotBuilderExt token(String val) { 18 | if (lastBuilder != null) { 19 | telegramBotProperties.add(lastBuilder); 20 | } 21 | lastBuilder = TelegramBotProperty.newBuilder().token(val); 22 | return new TelegramBotBuilderExt(); 23 | } 24 | 25 | public class TelegramBotBuilderExt extends TelegramBotBuilder { 26 | public TelegramBotBuilderExt() { 27 | } 28 | 29 | public TelegramBotBuilderExt alias(String val) { 30 | lastBuilder.alias(val); 31 | return this; 32 | } 33 | 34 | public TelegramBotBuilderExt okHttpClient(OkHttpClient val) { 35 | lastBuilder.okHttpClient(val); 36 | return this; 37 | } 38 | 39 | public TelegramBotBuilderExt url(String val) { 40 | lastBuilder.url(val); 41 | return this; 42 | } 43 | 44 | public TelegramBotBuilderExt timeOutMillis(long val) { 45 | lastBuilder.timeOutMillis(val); 46 | return this; 47 | } 48 | } 49 | 50 | public TelegramBotProperties build() { 51 | if (lastBuilder != null) { 52 | telegramBotProperties.add(lastBuilder); 53 | } 54 | TelegramBotProperties result = new TelegramBotProperties(); 55 | for (TelegramBotProperty.Builder builder : telegramBotProperties) { 56 | result.addTelegramProperty(builder.build()); 57 | } 58 | return result; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/config/TelegramBotProperties.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.config; 2 | 3 | import com.google.common.collect.Lists; 4 | 5 | import java.util.Iterator; 6 | import java.util.Set; 7 | import java.util.TreeSet; 8 | 9 | public class TelegramBotProperties implements Iterable { 10 | private Set telegramBotProperties; 11 | 12 | public TelegramBotProperties() { 13 | this.telegramBotProperties = new TreeSet<>((o1, o2) -> o1.getToken().compareToIgnoreCase(o2.getToken())); 14 | } 15 | 16 | public void addTelegramProperty(TelegramBotProperty telegramBotProperty) { 17 | telegramBotProperties.add(telegramBotProperty); 18 | } 19 | 20 | @Override 21 | public Iterator iterator() { 22 | return telegramBotProperties.iterator(); 23 | } 24 | 25 | public void addAll(TelegramBotProperties telegramBotProperties) { 26 | this.telegramBotProperties.addAll(Lists.newArrayList(telegramBotProperties)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/config/TelegramBotProperty.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.config; 2 | 3 | import okhttp3.OkHttpClient; 4 | import org.springframework.util.Assert; 5 | 6 | public class TelegramBotProperty { 7 | private final String token; 8 | private String alias; 9 | private OkHttpClient okHttpClient; 10 | private String url; 11 | private long timeOutMillis = 100L; 12 | 13 | public String getToken() { 14 | return token; 15 | } 16 | 17 | public OkHttpClient getOkHttpClient() { 18 | return okHttpClient; 19 | } 20 | 21 | public String getUrl() { 22 | return url; 23 | } 24 | 25 | public long getTimeOutMillis() { 26 | return timeOutMillis; 27 | } 28 | 29 | public TelegramBotProperty(String token) { 30 | this.token = token; 31 | } 32 | 33 | private TelegramBotProperty(Builder builder) { 34 | Assert.hasText(builder.token, "Токен должен быть задан"); 35 | token = builder.token; 36 | alias = builder.alias; 37 | okHttpClient = builder.okHttpClient; 38 | url = builder.url; 39 | timeOutMillis = builder.timeOutMillis; 40 | } 41 | 42 | public static Builder newBuilder() { 43 | return new Builder(); 44 | } 45 | 46 | public static Builder newBuilder(TelegramBotProperty copy) { 47 | Builder builder = new Builder(); 48 | builder.token = copy.getToken(); 49 | builder.alias = copy.getAlias(); 50 | builder.okHttpClient = copy.getOkHttpClient(); 51 | builder.url = copy.getUrl(); 52 | builder.timeOutMillis = copy.getTimeOutMillis(); 53 | return builder; 54 | } 55 | 56 | public String getAlias() { 57 | return alias; 58 | } 59 | 60 | public static final class Builder { 61 | private String token; 62 | private String alias; 63 | private OkHttpClient okHttpClient; 64 | private String url; 65 | private long timeOutMillis; 66 | 67 | private Builder() { 68 | } 69 | 70 | public Builder token(String val) { 71 | token = val; 72 | return this; 73 | } 74 | 75 | public Builder alias(String val) { 76 | alias = val; 77 | return this; 78 | } 79 | 80 | public Builder okHttpClient(OkHttpClient val) { 81 | okHttpClient = val; 82 | return this; 83 | } 84 | 85 | public Builder url(String val) { 86 | url = val; 87 | return this; 88 | } 89 | 90 | public Builder timeOutMillis(long val) { 91 | timeOutMillis = val; 92 | return this; 93 | } 94 | 95 | public TelegramBotProperty build() { 96 | return new TelegramBotProperty(this); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/config/TelegramMvcConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.config; 2 | 3 | /** 4 | * Интерфейс конфигурации бота 5 | */ 6 | public interface TelegramMvcConfiguration { 7 | void configuration(TelegramBotBuilder telegramBotBuilder); 8 | } 9 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/config/TelegramScope.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.config; 2 | 3 | import com.google.common.cache.CacheBuilder; 4 | import com.google.common.cache.CacheLoader; 5 | import com.google.common.cache.LoadingCache; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.ObjectFactory; 9 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 10 | import org.springframework.beans.factory.config.Scope; 11 | 12 | import java.util.Map; 13 | import java.util.concurrent.ConcurrentHashMap; 14 | import java.util.concurrent.ExecutionException; 15 | import java.util.concurrent.TimeUnit; 16 | 17 | public class TelegramScope implements Scope { 18 | private static final Logger logger = LoggerFactory.getLogger(TelegramScope.class); 19 | public static final String SCOPE = "telegramScope"; 20 | private static final ThreadLocal USER_THREAD_LOCAL = new ThreadLocal<>(); 21 | 22 | private final ConfigurableListableBeanFactory beanFactory; 23 | private final LoadingCache> conversations; 24 | 25 | public TelegramScope(ConfigurableListableBeanFactory beanFactory, long expireMiileSeconds) { 26 | this.beanFactory = beanFactory; 27 | // По истечению 1 часа пользовательские бины удаляются 28 | conversations = CacheBuilder 29 | .newBuilder() 30 | .expireAfterAccess(expireMiileSeconds, TimeUnit.MILLISECONDS) 31 | .removalListener(notification -> { 32 | if (notification.wasEvicted()) { 33 | logger.debug("Evict session for key {}", notification.getKey()); 34 | Map userScope = (Map) notification.getValue(); 35 | userScope.values().forEach(this::removeBean); 36 | } 37 | }) 38 | .build(new CacheLoader>() { 39 | @Override 40 | public ConcurrentHashMap load(String key) throws Exception { 41 | logger.debug("Create session for key = {}", key); 42 | return new ConcurrentHashMap<>(); 43 | } 44 | }); 45 | } 46 | 47 | private void removeBean(Object bean) { 48 | beanFactory.destroyBean(bean); 49 | } 50 | 51 | public static void setIdThreadLocal(Long chatId) { 52 | USER_THREAD_LOCAL.set(chatId); 53 | } 54 | 55 | public static void removeId() { 56 | USER_THREAD_LOCAL.remove(); 57 | } 58 | 59 | @Override 60 | public Object get(String name, ObjectFactory objectFactory) { 61 | final String sessionId = getConversationId(); 62 | if (sessionId == null) { 63 | throw new TelegramScopeException("There is no current user"); 64 | } 65 | ConcurrentHashMap beans = null; 66 | try { 67 | beans = conversations.get(sessionId); 68 | } catch (ExecutionException e) { 69 | throw new TelegramScopeException(e); 70 | } 71 | return beans.computeIfAbsent(name, (k) -> objectFactory.getObject()); 72 | } 73 | 74 | @Override 75 | public Object remove(String name) { 76 | final String sessionId = getConversationId(); 77 | if (sessionId != null) { 78 | final Map userBeans = conversations.getIfPresent(sessionId); 79 | if (userBeans != null) { 80 | return userBeans.remove(name); 81 | } 82 | } 83 | return null; 84 | } 85 | 86 | @Override 87 | public void registerDestructionCallback(String name, Runnable callback) { 88 | } 89 | 90 | @Override 91 | public Object resolveContextualObject(String key) { 92 | return null; 93 | } 94 | 95 | @Override 96 | public String getConversationId() { 97 | Long id = USER_THREAD_LOCAL.get(); 98 | if (id == null) { 99 | return null; 100 | } 101 | return Long.toString(id); 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/config/TelegramScopeException.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.config; 2 | 3 | 4 | public class TelegramScopeException extends RuntimeException { 5 | public TelegramScopeException(String message) { 6 | super(message); 7 | } 8 | 9 | public TelegramScopeException(Throwable e) { 10 | super(e); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotBaseRequestMethodProcessor.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.pengrad.telegrambot.request.BaseRequest; 5 | import org.springframework.core.MethodParameter; 6 | 7 | public class BotBaseRequestMethodProcessor 8 | implements BotHandlerMethodReturnValueHandler { 9 | 10 | @Override 11 | public boolean supportsReturnType(MethodParameter returnType) { 12 | Class paramType = returnType.getParameterType(); 13 | return BaseRequest.class.isAssignableFrom(paramType); 14 | } 15 | 16 | @Override 17 | public void handleReturnValue(Object returnValue, MethodParameter returnType, TelegramRequest telegramRequest) throws Exception { 18 | Class paramType = returnType.getParameterType(); 19 | if (BaseRequest.class.isAssignableFrom(paramType)) { 20 | if (!paramType.isInstance(returnValue)) { 21 | throw new IllegalStateException( 22 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest); 23 | } 24 | telegramRequest.setBaseRequest((BaseRequest) returnValue); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotHandlerMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import org.springframework.core.MethodParameter; 5 | 6 | /** 7 | * Имплементация интрефейса должна уметь обрабатывать аргументы метода который обрабатывает запрос 8 | */ 9 | public interface BotHandlerMethodArgumentResolver { 10 | boolean supportsParameter(MethodParameter parameter); 11 | 12 | /** 13 | * Праметры метода 14 | * @param parameter Метаданные параметра 15 | * @param telegramRequest Описание запроса 16 | * @return Значение параметра передается 17 | * @throws Exception Общие ошибки возникают 18 | */ 19 | Object resolveArgument(MethodParameter parameter, TelegramRequest telegramRequest) throws Exception; 20 | } 21 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotHandlerMethodArgumentResolverComposite.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.core.MethodParameter; 7 | 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.concurrent.ConcurrentHashMap; 12 | 13 | /** 14 | * Композитный ресолвер аргументов метода, ищет поддерживаемый и вызывает взято источник 15 | * {@link org.springframework.web.method.support.HandlerMethodArgumentResolverComposite} 16 | */ 17 | public class BotHandlerMethodArgumentResolverComposite implements BotHandlerMethodArgumentResolver { 18 | 19 | private static final Logger logger = LoggerFactory.getLogger(BotHandlerMethodArgumentResolverComposite.class); 20 | private final List argumentResolvers = new LinkedList<>(); 21 | 22 | private final Map argumentResolverCache = 23 | new ConcurrentHashMap<>(256); 24 | 25 | /** 26 | * Add the given {@link BotHandlerMethodArgumentResolver}s. 27 | * @param resolvers список ресолверов параметров 28 | * @return Композитный ресолвер 29 | */ 30 | public BotHandlerMethodArgumentResolverComposite addResolvers(List resolvers) { 31 | if (resolvers != null) { 32 | for (BotHandlerMethodArgumentResolver resolver : resolvers) { 33 | this.argumentResolvers.add(resolver); 34 | } 35 | } 36 | return this; 37 | } 38 | 39 | @Override 40 | public boolean supportsParameter(MethodParameter parameter) { 41 | return (getArgumentResolver(parameter) != null); 42 | } 43 | 44 | @Override 45 | public Object resolveArgument(MethodParameter parameter, TelegramRequest telegramRequest) throws Exception { 46 | BotHandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); 47 | if (resolver == null) { 48 | throw new IllegalArgumentException("Unknown parameter type [" + parameter.getParameterType().getName() + "]"); 49 | } 50 | return resolver.resolveArgument(parameter, telegramRequest); 51 | } 52 | 53 | /** 54 | * Find a registered {@link BotHandlerMethodArgumentResolver} that supports the given method parameter. 55 | */ 56 | private BotHandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) { 57 | BotHandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter); 58 | if (result == null) { 59 | for (BotHandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) { 60 | if (logger.isTraceEnabled()) { 61 | logger.trace("Testing if argument resolver [" + methodArgumentResolver + "] supports [" + 62 | parameter.getGenericParameterType() + "]"); 63 | } 64 | if (methodArgumentResolver.supportsParameter(parameter)) { 65 | result = methodArgumentResolver; 66 | this.argumentResolverCache.put(parameter, result); 67 | break; 68 | } 69 | } 70 | } 71 | return result; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotHandlerMethodReturnValueHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import org.springframework.core.MethodParameter; 5 | 6 | /** 7 | * Имплементация интерфейса умеет преобразовывать возвращаемый параметр, заполняет в {@link TelegramRequest} параметр baseRequest 8 | */ 9 | public interface BotHandlerMethodReturnValueHandler { 10 | 11 | boolean supportsReturnType(MethodParameter returnType); 12 | 13 | void handleReturnValue(Object returnValue, MethodParameter returnType, TelegramRequest telegramRequest) throws Exception; 14 | } 15 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotHandlerMethodReturnValueHandlerComposite.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import org.springframework.core.MethodParameter; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class BotHandlerMethodReturnValueHandlerComposite implements BotHandlerMethodReturnValueHandler { 10 | 11 | private final List returnValueHandlers = new ArrayList<>(); 12 | 13 | @Override 14 | public boolean supportsReturnType(MethodParameter returnType) { 15 | return getReturnValueHandler(returnType) != null; 16 | } 17 | 18 | private BotHandlerMethodReturnValueHandler getReturnValueHandler(MethodParameter returnType) { 19 | for (BotHandlerMethodReturnValueHandler handler : this.returnValueHandlers) { 20 | if (handler.supportsReturnType(returnType)) { 21 | return handler; 22 | } 23 | } 24 | return null; 25 | } 26 | 27 | /** 28 | * Iterate over registered {@link BotHandlerMethodReturnValueHandler}s and invoke the one that supports it. 29 | * 30 | * @throws IllegalStateException if no suitable {@link BotHandlerMethodReturnValueHandler} is found. 31 | */ 32 | @Override 33 | public void handleReturnValue(Object returnValue, MethodParameter returnType, TelegramRequest telegramRequest) throws Exception { 34 | BotHandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType); 35 | if (handler == null) { 36 | throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName()); 37 | } 38 | handler.handleReturnValue(returnValue, returnType, telegramRequest); 39 | } 40 | 41 | private BotHandlerMethodReturnValueHandler selectHandler(Object value, MethodParameter returnType) { 42 | for (BotHandlerMethodReturnValueHandler handler : this.returnValueHandlers) { 43 | if (handler.supportsReturnType(returnType)) { 44 | return handler; 45 | } 46 | } 47 | return null; 48 | } 49 | 50 | /** 51 | * Add the given {@link BotHandlerMethodReturnValueHandler}s. 52 | * @param handlers Список ресолверов 53 | * @return Композитный ресолвер 54 | */ 55 | public BotHandlerMethodReturnValueHandlerComposite addHandlers(List handlers) { 56 | if (handlers != null) { 57 | for (BotHandlerMethodReturnValueHandler handler : handlers) { 58 | this.returnValueHandlers.add(handler); 59 | } 60 | } 61 | return this; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotRequestMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.github.telegram.mvc.api.TelegramSession; 5 | import com.pengrad.telegrambot.TelegramBot; 6 | import com.pengrad.telegrambot.model.*; 7 | import org.springframework.core.MethodParameter; 8 | 9 | 10 | public class BotRequestMethodArgumentResolver implements BotHandlerMethodArgumentResolver { 11 | @Override 12 | public boolean supportsParameter(MethodParameter parameter) { 13 | Class paramType = parameter.getParameterType(); 14 | return TelegramRequest.class.isAssignableFrom(paramType) || 15 | TelegramSession.class.isAssignableFrom(paramType) || 16 | TelegramBot.class.isAssignableFrom(paramType) || 17 | Long.class.isAssignableFrom(paramType) || 18 | String.class.isAssignableFrom(paramType) || 19 | Update.class.isAssignableFrom(paramType) || 20 | Message.class.isAssignableFrom(paramType) || 21 | InlineQuery.class.isAssignableFrom(paramType) || 22 | ChosenInlineResult.class.isAssignableFrom(paramType) || 23 | CallbackQuery.class.isAssignableFrom(paramType) || 24 | ShippingQuery.class.isAssignableFrom(paramType) || 25 | PreCheckoutQuery.class.isAssignableFrom(paramType) || 26 | Chat.class.isAssignableFrom(paramType) || 27 | User.class.isAssignableFrom(paramType); 28 | } 29 | 30 | @Override 31 | public Object resolveArgument(MethodParameter parameter, TelegramRequest telegramRequest) { 32 | 33 | Class paramType = parameter.getParameterType(); 34 | if (TelegramRequest.class.isAssignableFrom(paramType)) { 35 | return telegramRequest; 36 | } else if (TelegramSession.class.isAssignableFrom(paramType)) { 37 | return telegramRequest.getSession(); 38 | } else if (Update.class.isAssignableFrom(paramType)) { 39 | return telegramRequest.getUpdate(); 40 | } else if (Message.class.isAssignableFrom(paramType)) { 41 | if (telegramRequest.getMessage() != null && !paramType.isInstance(telegramRequest.getMessage())) { 42 | throw new IllegalStateException( 43 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest.getMessage()); 44 | } 45 | return telegramRequest.getMessage(); 46 | } else { 47 | if (User.class.isAssignableFrom(paramType)) { 48 | if (telegramRequest.getUser() != null && !paramType.isInstance(telegramRequest.getUser())) { 49 | throw new IllegalStateException( 50 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest.getUser()); 51 | } 52 | return telegramRequest.getUser(); 53 | } else if (Chat.class.isAssignableFrom(paramType)) { 54 | if (telegramRequest.getChat() != null && !paramType.isInstance(telegramRequest.getChat())) { 55 | throw new IllegalStateException( 56 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest.getChat()); 57 | } 58 | return telegramRequest.getChat(); 59 | } else if (String.class.isAssignableFrom(paramType)) { 60 | if (telegramRequest.getText() != null && !paramType.isInstance(telegramRequest.getText())) { 61 | throw new IllegalStateException( 62 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest.getText()); 63 | } 64 | return telegramRequest.getText(); 65 | } else if (TelegramBot.class.isAssignableFrom(paramType)) { 66 | if (telegramRequest.getTelegramBot() != null && !paramType.isInstance(telegramRequest.getTelegramBot())) { 67 | throw new IllegalStateException( 68 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest.getTelegramBot()); 69 | } 70 | return telegramRequest.getTelegramBot(); 71 | } else if (Long.class.isAssignableFrom(paramType)) { 72 | if (telegramRequest.getChatId() != null && !paramType.isInstance(telegramRequest.getChatId())) { 73 | throw new IllegalStateException( 74 | "Current request is not of type [" + paramType.getName() + "]: " + telegramRequest.getChatId()); 75 | } 76 | return telegramRequest.getChatId(); 77 | } else { 78 | Update update = telegramRequest.getUpdate(); 79 | if (InlineQuery.class.isAssignableFrom(paramType)) { 80 | if (update.callbackQuery() != null && !paramType.isInstance(update.callbackQuery())) { 81 | throw new IllegalStateException( 82 | "Current request is not of type [" + paramType.getName() + "]: " + update.callbackQuery()); 83 | } 84 | return update.callbackQuery(); 85 | } else if (ChosenInlineResult.class.isAssignableFrom(paramType)) { 86 | if (update.chosenInlineResult() != null && !paramType.isInstance(update.chosenInlineResult())) { 87 | throw new IllegalStateException( 88 | "Current request is not of type [" + paramType.getName() + "]: " + update.chosenInlineResult()); 89 | } 90 | return update.chosenInlineResult(); 91 | } else if (ShippingQuery.class.isAssignableFrom(paramType)) { 92 | if (update.shippingQuery() != null && !paramType.isInstance(update.shippingQuery())) { 93 | throw new IllegalStateException( 94 | "Current request is not of type [" + paramType.getName() + "]: " + update.shippingQuery()); 95 | } 96 | return update.shippingQuery(); 97 | } else if (PreCheckoutQuery.class.isAssignableFrom(paramType)) { 98 | if (update.preCheckoutQuery() != null && !paramType.isInstance(update.preCheckoutQuery())) { 99 | throw new IllegalStateException( 100 | "Current request is not of type [" + paramType.getName() + "]: " + update.preCheckoutQuery()); 101 | } 102 | return update.preCheckoutQuery(); 103 | } 104 | } 105 | } 106 | return null; 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotResponseBodyMethodProcessor.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.pengrad.telegrambot.request.SendMessage; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.core.ResolvableType; 7 | import org.springframework.core.convert.ConversionService; 8 | import org.springframework.http.HttpEntity; 9 | import org.springframework.http.converter.HttpMessageConverter; 10 | 11 | import java.lang.reflect.Type; 12 | 13 | public class BotResponseBodyMethodProcessor implements BotHandlerMethodReturnValueHandler { 14 | private ConversionService conversionService; 15 | 16 | public BotResponseBodyMethodProcessor(ConversionService conversionService) { 17 | 18 | this.conversionService = conversionService; 19 | } 20 | 21 | @Override 22 | public boolean supportsReturnType(MethodParameter returnType) { 23 | return true; 24 | } 25 | 26 | @Override 27 | public void handleReturnValue(Object returnValue, MethodParameter returnType, TelegramRequest telegramRequest) throws Exception { 28 | Object outputValue; 29 | Class valueType; 30 | 31 | if (returnValue instanceof CharSequence) { 32 | outputValue = returnValue.toString(); 33 | } else { 34 | outputValue = returnValue; 35 | valueType = getReturnValueType(outputValue, returnType); 36 | if (conversionService.canConvert(valueType, String.class)) { 37 | outputValue = conversionService.convert(outputValue, String.class); 38 | } else if (conversionService.canConvert(returnType.getParameterType(), String.class)) { 39 | outputValue = conversionService.convert(returnType.getParameterType(), String.class); 40 | } 41 | } 42 | telegramRequest.setBaseRequest(new SendMessage(telegramRequest.chatId(), (String) outputValue)); 43 | } 44 | 45 | private Class getReturnValueType(Object value, MethodParameter returnType) { 46 | return (value != null ? value.getClass() : returnType.getParameterType()); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/telegram/mvc/handler/BotTextVariableMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.mvc.handler; 2 | 3 | import com.github.telegram.mvc.api.TelegramRequest; 4 | import com.github.telegram.mvc.api.TextVariable; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.core.convert.ConversionService; 7 | 8 | import java.util.Map; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | 11 | /** 12 | * Ищет переменные в тексте 13 | */ 14 | public class BotTextVariableMethodArgumentResolver implements BotHandlerMethodArgumentResolver { 15 | private final Map namedValueInfoCache = 16 | new ConcurrentHashMap(256); 17 | private ConversionService conversionService; 18 | 19 | public BotTextVariableMethodArgumentResolver(ConversionService conversionService) { 20 | this.conversionService = conversionService; 21 | } 22 | 23 | @Override 24 | public boolean supportsParameter(MethodParameter parameter) { 25 | return parameter.hasParameterAnnotation(TextVariable.class); 26 | } 27 | 28 | @Override 29 | public Object resolveArgument(MethodParameter parameter, TelegramRequest telegramRequest) throws Exception { 30 | NamedValueInfo namedValueInfo = getNamedValueInfo(parameter); 31 | MethodParameter nestedParameter = parameter.nestedIfOptional(); 32 | Object arg = telegramRequest.getTemplateVariables().get(namedValueInfo.getName()); 33 | if (arg == null) { 34 | arg = handleNullValue(namedValueInfo.getName(), arg, nestedParameter.getNestedParameterType()); 35 | if (arg == null) { 36 | if (namedValueInfo.required && !nestedParameter.isOptional()) { 37 | throw new RuntimeException("Missing template variable '" + namedValueInfo.getName() + 38 | "' for method parameter of type " + parameter.getParameterType().getSimpleName()); 39 | } 40 | } 41 | } else { 42 | if (conversionService.canConvert(arg.getClass(), nestedParameter.getNestedParameterType())) { 43 | return conversionService.convert(arg, nestedParameter.getNestedParameterType()); 44 | } 45 | } 46 | return arg; 47 | } 48 | 49 | private NamedValueInfo getNamedValueInfo(MethodParameter parameter) { 50 | NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter); 51 | if (namedValueInfo == null) { 52 | TextVariable annotation = parameter.getParameterAnnotation(TextVariable.class); 53 | 54 | namedValueInfo = new NamedValueInfo( 55 | annotation.name() == null ? parameter.getParameterName() : annotation.name(), 56 | annotation.required()); 57 | this.namedValueInfoCache.put(parameter, namedValueInfo); 58 | } 59 | return namedValueInfo; 60 | } 61 | 62 | /** 63 | * A {@code null} results in a {@code false} value for {@code boolean}s or an exception for other primitives. 64 | */ 65 | private Object handleNullValue(String name, Object value, Class paramType) { 66 | if (value == null) { 67 | if (Boolean.TYPE.equals(paramType)) { 68 | return Boolean.FALSE; 69 | } else if (paramType.isPrimitive()) { 70 | throw new IllegalStateException("Optional " + paramType.getSimpleName() + " parameter '" + name + 71 | "' is present but cannot be translated into a null value due to being declared as a " + 72 | "primitive type. Consider declaring it as object wrapper for the corresponding primitive type."); 73 | } 74 | } 75 | return value; 76 | } 77 | 78 | 79 | private class NamedValueInfo { 80 | private final String name; 81 | 82 | private final boolean required; 83 | 84 | public NamedValueInfo(String name, boolean required) { 85 | this.name = name; 86 | this.required = required; 87 | } 88 | 89 | public String getName() { 90 | return name; 91 | } 92 | 93 | public boolean isRequired() { 94 | return required; 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '1.5.7.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | 17 | 18 | sourceCompatibility = 1.8 19 | targetCompatibility = 1.8 20 | 21 | dependencies { 22 | compile project(':library') 23 | compile('org.springframework.boot:spring-boot-starter-web') 24 | } 25 | -------------------------------------------------------------------------------- /sample/src/main/java/com/github/telegram/sample/SampleTelegramBotMvcMain.java: -------------------------------------------------------------------------------- 1 | package com.github.telegram.sample; 2 | 3 | import com.github.telegram.mvc.api.BotController; 4 | import com.github.telegram.mvc.api.BotRequest; 5 | import com.github.telegram.mvc.api.EnableTelegram; 6 | import com.github.telegram.mvc.api.TelegramRequest; 7 | import com.github.telegram.mvc.config.TelegramBotBuilder; 8 | import com.github.telegram.mvc.config.TelegramMvcConfiguration; 9 | import com.pengrad.telegrambot.TelegramBot; 10 | import com.pengrad.telegrambot.model.Chat; 11 | import com.pengrad.telegrambot.model.Message; 12 | import com.pengrad.telegrambot.model.Update; 13 | import com.pengrad.telegrambot.model.User; 14 | import com.pengrad.telegrambot.request.BaseRequest; 15 | import com.pengrad.telegrambot.request.SendMessage; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | import org.springframework.core.env.Environment; 22 | 23 | @SpringBootApplication 24 | @EnableTelegram 25 | @BotController 26 | public class SampleTelegramBotMvcMain implements TelegramMvcConfiguration { 27 | private static final Logger logger = LoggerFactory.getLogger(SampleTelegramBotMvcMain.class); 28 | 29 | @Autowired 30 | private Environment environment; 31 | 32 | public static void main(String[] args) { 33 | SpringApplication.run(SampleTelegramBotMvcMain.class); 34 | } 35 | 36 | @Override 37 | public void configuration(TelegramBotBuilder telegramBotBuilder) { 38 | telegramBotBuilder 39 | .token(environment.getProperty("telegram.bot.token")).alias("myFirsBean"); 40 | } 41 | 42 | @BotRequest("/start") 43 | BaseRequest hello(String text, 44 | Long chatId, 45 | TelegramRequest telegramRequest, 46 | TelegramBot telegramBot, 47 | Update update, 48 | Message message, 49 | Chat chat, 50 | User user 51 | ) { 52 | logger.info("Text = {}", text); 53 | logger.info("ChatId or UserId = {}", chatId); 54 | logger.info("Telegram Request = {}", telegramRequest); 55 | logger.info("TelegramBot = {}", telegramBot); 56 | logger.info("Update = {}", update); 57 | logger.info("Message = {}", message); 58 | logger.info("Chat = {}", chat); 59 | logger.info("User = {}", user); 60 | 61 | return new SendMessage(chatId, "I test bot"); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /sample/src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | telegram: 2 | bot: 3 | token: https://habrahabr.ru/post/262247/ -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-telegram-bot-mvc' 2 | 3 | include 'library' 4 | include 'sample' 5 | 6 | --------------------------------------------------------------------------------