├── .gitignore
├── .travis.yml
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
└── src
│ ├── main
│ └── java
│ │ └── ru
│ │ └── mail
│ │ └── im
│ │ └── botapi
│ │ ├── BotApiClient.java
│ │ ├── BotApiClientController.java
│ │ ├── BotLogger.java
│ │ ├── api
│ │ ├── Api.java
│ │ ├── ApiImplementationFactory.java
│ │ ├── BotApi.java
│ │ ├── Chats.java
│ │ ├── Events.java
│ │ ├── GetRequest.java
│ │ ├── Messages.java
│ │ ├── OkHttpRequestExecutor.java
│ │ ├── PostRequest.java
│ │ ├── QueryBuilder.java
│ │ ├── QueryParameter.java
│ │ ├── RequestExecutor.java
│ │ ├── RequestParam.java
│ │ ├── Self.java
│ │ └── entity
│ │ │ ├── AnswerCallbackQueryRequest.java
│ │ │ ├── DeleteMessagesRequest.java
│ │ │ ├── EditTextRequest.java
│ │ │ ├── InlineKeyboardButton.java
│ │ │ ├── SendFileRequest.java
│ │ │ └── SendTextRequest.java
│ │ ├── entity
│ │ ├── Admin.java
│ │ ├── Buddy.java
│ │ ├── ChatAction.java
│ │ ├── ChatType.java
│ │ └── Photo.java
│ │ ├── fetcher
│ │ ├── BackoffFetcher.java
│ │ ├── Chat.java
│ │ ├── EventDeserializer.java
│ │ ├── FetchResponse.java
│ │ ├── Fetcher.java
│ │ ├── Message.java
│ │ ├── OnEventFetchListener.java
│ │ ├── PartDeserializer.java
│ │ ├── User.java
│ │ └── event
│ │ │ ├── CallbackQueryEvent.java
│ │ │ ├── DeletedMessageEvent.java
│ │ │ ├── EditedMessageEvent.java
│ │ │ ├── Event.java
│ │ │ ├── EventVisitor.java
│ │ │ ├── LeftChatMembersEvent.java
│ │ │ ├── NewChatMembersEvent.java
│ │ │ ├── NewMessageEvent.java
│ │ │ ├── PinnedMessageEvent.java
│ │ │ ├── UnknownEvent.java
│ │ │ ├── UnpinnedMessageEvent.java
│ │ │ └── parts
│ │ │ ├── File.java
│ │ │ ├── Forward.java
│ │ │ ├── Mention.java
│ │ │ ├── Part.java
│ │ │ ├── Reply.java
│ │ │ ├── Sticker.java
│ │ │ └── Voice.java
│ │ ├── json
│ │ └── ChatTypeGsonDeserializer.java
│ │ ├── response
│ │ ├── ApiResponse.java
│ │ ├── ChatsGetAdminsResponse.java
│ │ ├── ChatsGetInfoResponse.java
│ │ ├── MessageResponse.java
│ │ └── SelfGetResponse.java
│ │ └── util
│ │ ├── IOBackoff.java
│ │ ├── ListenerDescriptor.java
│ │ └── ListenerList.java
│ └── test
│ └── java
│ └── ru
│ └── mail
│ └── im
│ └── botapi
│ ├── api
│ ├── ApiImplementationFactoryTest.java
│ ├── QueryBuilderTest.java
│ └── QueryParameterTest.java
│ └── util
│ ├── IOBackoffTest.java
│ └── ListenerListTest.java
├── sample
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── java
│ └── ru
│ └── mail
│ └── im
│ └── botapi
│ └── sample
│ ├── AppCommandHandler.java
│ ├── FileFetchWriter.java
│ ├── Main.java
│ ├── OnRequestExecuteListener.java
│ ├── PlaceholderValueProviderImpl.java
│ ├── ResponsePrinter.java
│ ├── SimpleStart.java
│ └── command
│ ├── CommandHandler.java
│ ├── CommandProcessor.java
│ └── PlaceholderValueProvider.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .gradle
3 | *.iml
4 | local.properties
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - openjdk8
4 |
5 | script:
6 | - ./gradlew check
7 |
8 | after_success:
9 | - bash <(curl -s https://codecov.io/bash)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Java interface for bot API
4 |
5 | [](https://travis-ci.org/mail-ru-im/bot-java)
6 | [](https://codecov.io/gh/mail-ru-im/bot-java)
7 |
8 | [](https://maven-badges.herokuapp.com/maven-central/ru.mail.im/bot-api)
9 |
10 | ## Install
11 |
12 | Group ids `io.github.mail-ru-im` and `ru.mail` will no longer being maintained. We moved this artifact to the `ru.mail.im` group id.
13 |
14 | ### Maven
15 | ```xml
16 |
17 | ...
18 |
19 | mavencentral
20 | Maven Central Repository
21 | http://repo1.maven.org/maven2
22 |
23 | ...
24 |
25 |
26 |
27 | ...
28 |
29 | ru.mail.im
30 | bot-api
31 | 1.2.3
32 |
33 | ...
34 |
35 |
36 | ```
37 | ### Gradle
38 | ```groovy
39 | repositories {
40 | mavenCentral()
41 | }
42 |
43 | dependencies {
44 | implementation 'ru.mail.im:bot-api:1.2.3'
45 | }
46 | ```
47 |
48 | ## Usage
49 |
50 | Create your own bot by sending the /newbot command to Metabot and follow the instructions.
51 |
52 | Note a bot can only reply after the user has added it to his contacts list, or if the user was the first to start a dialogue.
53 |
54 | ### Create your bot
55 |
56 | ```java
57 |
58 | // For ICQ New/Agent: create bot with token received from Metabot
59 | BotApiClient client = new BotApiClient(token);
60 | // For Myteam: create bot with token from Metabot and host url (for example `https://myteam.mail.ru/`)
61 | BotApiClient client = new BotApiClient(apiBaseUrl, token);
62 |
63 | BotApiClientController controller = BotApiClientController.startBot(client);
64 | client.addOnEventFetchListener(events -> {
65 | //subscribe to new events
66 | });
67 |
68 | // send actions
69 | controller.sendActions(chatId, ChatAction.TYPING);
70 |
71 | // send message
72 | long messageId = controller.sendTextMessage(
73 | new SendTextRequest()
74 | .setChatId(chatId)
75 | .setText("Bot message")
76 | ).getMsgId();
77 |
78 | // edit message
79 | controller.editText(
80 | new EditTextRequest()
81 | .setChatId(chatId)
82 | .setMsgId(messageId)
83 | .setNewText("Edited bot message")
84 | );
85 |
86 | // reply message
87 | controller.sendTextMessage(
88 | new SendTextRequest()
89 | .setChatId(chatId)
90 | .setText("Reply msg")
91 | .setReplyMsgId(Collections.singletonList(messageId))
92 | );
93 |
94 | File file = new File("myfile.txt");
95 | // send file
96 | controller.sendFile(
97 | new SendFileRequest()
98 | .setChatId(chatId)
99 | .setFile(file)
100 | );
101 |
102 | // reply file
103 | MessageResponse sendFileResponse = controller.sendFile(
104 | new SendFileRequest()
105 | .setChatId(chatId)
106 | .setFile(file)
107 | .setCaption("Awesome file")
108 | .setReplyMsgId(Collections.singletonList(messageId))
109 | );
110 | if (!sendFileResponse.isOk()) { // sent successfully or not
111 | // and get the error description if sending failed
112 | String errorDescription = sendFileResponse.getDescription();
113 | }
114 |
115 | client.stop(); // stop when work done
116 | ```
117 |
118 | ## Changelog
119 |
120 | `1.2.3`
121 | - Catch all exceptions in IOBackoff.execute
122 |
123 | `1.2.2`
124 | - Support text formats: MarkdownV2, HTML
125 | - Support button's style for inline keyboard
126 | - Moved from JCenter with `ru.mail` group id to Maven Central with `ru.mail.im` group id
127 |
128 | `1.2.1`
129 | - Api response status check possibility
130 |
131 | `1.2.0`
132 | - Support inline keyboards
133 | - Moved from `io.github.mail-ru-im` to `ru.mail` group id
134 |
135 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.versions = [
3 | 'junit' : '4.12',
4 | 'jsr305' : '3.0.2',
5 | 'okhttp' : '3.14.1',
6 | 'gson' : '2.8.5',
7 | 'slf4j' : '1.7.28',
8 | 'javaVersion': JavaVersion.VERSION_1_8
9 | ]
10 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mail-ru-im/bot-java/915d8d0579c8cbedc73061f72be542266b6e83f0/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Apr 16 14:59:49 MSK 2019
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-5.0-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 | /out
2 | /build
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "maven"
3 | id "maven-publish"
4 | id "java"
5 | id "jacoco"
6 | id "signing"
7 | }
8 |
9 | targetCompatibility = versions.javaVersion
10 | sourceCompatibility = versions.javaVersion
11 |
12 | group = "ru.mail.im"
13 | archivesBaseName = "bot-api"
14 | version = "1.2.3"
15 |
16 | repositories {
17 | mavenCentral()
18 | }
19 |
20 | jacocoTestReport {
21 | reports {
22 | xml.enabled = true
23 | html.enabled = false
24 | }
25 | }
26 |
27 | check.dependsOn jacocoTestReport
28 |
29 | dependencies {
30 | compile "com.google.code.findbugs:jsr305:${versions.jsr305}"
31 | compile "com.squareup.okhttp3:okhttp:${versions.okhttp}"
32 | compile "com.google.code.gson:gson:${versions.gson}"
33 | compile "org.slf4j:slf4j-api:${versions.slf4j}"
34 |
35 | testCompile "junit:junit:${versions.junit}"
36 | }
37 |
38 | task sourcesJar(type: Jar, dependsOn: classes) {
39 | classifier = 'sources'
40 | from sourceSets.main.allSource
41 | }
42 |
43 | javadoc.failOnError = false
44 | task javadocJar(type: Jar, dependsOn: javadoc) {
45 | classifier = 'javadoc'
46 | from javadoc.destinationDir
47 | }
48 |
49 | artifacts {
50 | archives sourcesJar
51 | archives javadocJar
52 | }
53 |
54 | signing {
55 | useGpgCmd()
56 | sign configurations.archives
57 | }
58 |
59 | File propsFile = project.rootProject.file('local.properties')
60 | if (propsFile.exists()) {
61 | Properties properties = new Properties()
62 | properties.load(propsFile.newDataInputStream())
63 | uploadArchives {
64 | repositories {
65 | mavenDeployer {
66 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
67 |
68 | repository(url: "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") {
69 | authentication(
70 | userName: properties['sonatype.ossrhUsername'],
71 | password: properties['sonatype.ossrhPassword']
72 | )
73 | }
74 |
75 | snapshotRepository(url: "https://s01.oss.sonatype.org/content/repositories/snapshots/") {
76 | authentication(
77 | userName: properties['sonatype.ossrhUsername'],
78 | password: properties['sonatype.ossrhPassword']
79 | )
80 | }
81 |
82 | pom.project {
83 | name 'bot-api'
84 | packaging 'jar'
85 | // optionally artifactId can be defined here
86 | description 'Java interface for bot API'
87 | url 'https://github.com/mail-ru-im/bot-java'
88 |
89 | scm {
90 | connection 'scm:git:https://github.com/mail-ru-im/bot-java'
91 | developerConnection 'scm:git:https://github.com/mail-ru-im/bot-java'
92 | url 'https://github.com/mail-ru-im/bot-java'
93 | }
94 |
95 | licenses {
96 | license {
97 | name "MIT License"
98 | url "http://www.opensource.org/licenses/mit-license.php"
99 | distribution "repo"
100 | }
101 | }
102 |
103 | developers {
104 | developer {
105 | id properties['developer.id']
106 | name properties['developer.name']
107 | email properties['developer.email']
108 | }
109 | }
110 | }
111 | }
112 | }
113 | }
114 | } else {
115 | println("There is no local.properties file included")
116 | }
117 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/BotApiClient.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi;
2 |
3 | import com.google.gson.Gson;
4 | import okhttp3.OkHttpClient;
5 | import ru.mail.im.botapi.api.Api;
6 | import ru.mail.im.botapi.api.BotApi;
7 | import ru.mail.im.botapi.api.Chats;
8 | import ru.mail.im.botapi.api.Messages;
9 | import ru.mail.im.botapi.api.Self;
10 | import ru.mail.im.botapi.fetcher.BackoffFetcher;
11 | import ru.mail.im.botapi.fetcher.Fetcher;
12 | import ru.mail.im.botapi.fetcher.OnEventFetchListener;
13 | import ru.mail.im.botapi.util.ListenerDescriptor;
14 | import ru.mail.im.botapi.util.ListenerList;
15 |
16 | import javax.annotation.Nonnull;
17 | import java.util.concurrent.TimeUnit;
18 | import java.util.concurrent.atomic.AtomicBoolean;
19 |
20 | public class BotApiClient {
21 |
22 | private static final String ICQ_BOT_API_URL = "https://api.icq.net";
23 |
24 | private final long lastEventId;
25 | private final long pollTime;
26 |
27 | private final AtomicBoolean started = new AtomicBoolean();
28 | private final ListenerList fetchListenerList;
29 |
30 | private final Api api;
31 | private Fetcher fetcher;
32 |
33 | public BotApiClient(@Nonnull final String token) {
34 | this(ICQ_BOT_API_URL, token);
35 | }
36 |
37 | public BotApiClient(
38 | final String apiUrl,
39 | final String token
40 | ) {
41 | this(apiUrl, token, 0, 60);
42 | }
43 |
44 | public BotApiClient(
45 | final String token,
46 | final long lastEventId,
47 | final long pollTime
48 | ) {
49 | this(ICQ_BOT_API_URL, token, lastEventId, pollTime);
50 | }
51 |
52 | public BotApiClient(
53 | final String apiBaseUrl,
54 | final String token,
55 | final long lastEventId,
56 | final long pollTime
57 | ) {
58 | this(new Gson(), apiBaseUrl, token, lastEventId, pollTime);
59 | }
60 |
61 | public BotApiClient(
62 | final Gson gson,
63 | final String apiBaseUrl,
64 | final String token,
65 | final long lastEventId,
66 | final long pollTime
67 | ) {
68 | this(
69 | gson,
70 | new OkHttpClient.Builder().readTimeout(pollTime, TimeUnit.SECONDS).build(),
71 | new ListenerList<>(OnEventFetchListener.class),
72 | apiBaseUrl,
73 | token,
74 | lastEventId,
75 | pollTime
76 | );
77 | }
78 |
79 | public BotApiClient(
80 | final Gson gson,
81 | final OkHttpClient httpClient,
82 | final ListenerList fetchListenerList,
83 | final String apiBaseUrl,
84 | final String token,
85 | final long lastEventId,
86 | final long pollTime
87 | ) {
88 | this(
89 | new BotApi(gson, httpClient, apiBaseUrl + "/bot/v1/", token),
90 | new BackoffFetcher(
91 | httpClient,
92 | events -> fetchListenerList.asListener().onEventFetch(events),
93 | apiBaseUrl + "/bot/v1/events/get?token=" + token
94 | ),
95 | fetchListenerList,
96 | lastEventId,
97 | pollTime
98 | );
99 | }
100 |
101 | public BotApiClient(
102 | final Api api,
103 | final Fetcher fetcher,
104 | final ListenerList fetchListenerList,
105 | final long lastEventId,
106 | final long pollTime
107 | ) {
108 | this.api = api;
109 | this.fetcher = fetcher;
110 | this.fetchListenerList = fetchListenerList;
111 | this.lastEventId = lastEventId;
112 | this.pollTime = pollTime;
113 | }
114 |
115 | public void start() {
116 | if (started.compareAndSet(false, true)) {
117 | startInternal();
118 | BotLogger.i("bot successfully started");
119 | } else {
120 | BotLogger.i("bot already started");
121 | }
122 | }
123 |
124 | public void stop() {
125 | if (started.compareAndSet(true, false)) {
126 | stopInternal();
127 | BotLogger.i("bot successfully stopped");
128 | } else {
129 | BotLogger.i("bot is not running");
130 | }
131 | }
132 |
133 | public ListenerDescriptor addOnEventFetchListener(final OnEventFetchListener listener) {
134 | return fetchListenerList.add(listener);
135 | }
136 |
137 | public Messages messages() {
138 | return api.messages();
139 | }
140 |
141 | public Self self() {
142 | return api.self();
143 | }
144 |
145 | public Chats chats() {
146 | return api.chats();
147 | }
148 |
149 | private void startInternal() {
150 | fetcher.start(lastEventId, pollTime);
151 | }
152 |
153 | private void stopInternal() {
154 | fetcher.stop();
155 | }
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/BotApiClientController.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi;
2 |
3 | import ru.mail.im.botapi.api.entity.AnswerCallbackQueryRequest;
4 | import ru.mail.im.botapi.api.entity.DeleteMessagesRequest;
5 | import ru.mail.im.botapi.api.entity.EditTextRequest;
6 | import ru.mail.im.botapi.api.entity.SendFileRequest;
7 | import ru.mail.im.botapi.api.entity.SendTextRequest;
8 | import ru.mail.im.botapi.entity.ChatAction;
9 | import ru.mail.im.botapi.response.ApiResponse;
10 | import ru.mail.im.botapi.response.ChatsGetAdminsResponse;
11 | import ru.mail.im.botapi.response.ChatsGetInfoResponse;
12 | import ru.mail.im.botapi.response.MessageResponse;
13 | import ru.mail.im.botapi.response.SelfGetResponse;
14 |
15 | import java.io.File;
16 | import java.io.IOException;
17 | import java.util.List;
18 |
19 | public class BotApiClientController {
20 |
21 | private final BotApiClient client;
22 |
23 | public static BotApiClientController startBot(BotApiClient client) {
24 | return new BotApiClientController(client);
25 | }
26 |
27 | private BotApiClientController(BotApiClient client) {
28 | this.client = client;
29 | client.start();
30 | }
31 |
32 | public MessageResponse sendTextMessage(final SendTextRequest request) throws IOException {
33 | return client.messages().sendText(
34 | request.getChatId(),
35 | request.getText(),
36 | request.getFormat(),
37 | request.getParseMode(),
38 | toLongArray(request.getReplyMsgId()),
39 | request.getForwardChatId(),
40 | toLongArray(request.getForwardMsgId()),
41 | request.getKeyboard()
42 | );
43 | }
44 |
45 | /**
46 | * @deprecated Use {@link BotApiClientController#sendTextMessage(SendTextRequest)}
47 | */
48 | @Deprecated
49 | public MessageResponse sendTextMessage(
50 | final String chatId,
51 | final String text
52 | ) throws IOException {
53 | return client.messages().sendText(chatId, text, null, null, null, null, null, null);
54 | }
55 |
56 | /**
57 | * @deprecated Use {@link BotApiClientController#sendTextMessage(SendTextRequest)}
58 | */
59 | @Deprecated
60 | public MessageResponse replyText(
61 | final String chatId,
62 | final String text,
63 | final long replyMsgId
64 | ) throws IOException {
65 | return client.messages().sendText(chatId, text, null, null, new long[]{replyMsgId}, null, null, null);
66 | }
67 |
68 | /**
69 | * @deprecated Use {@link BotApiClientController#sendTextMessage(SendTextRequest)}
70 | */
71 | @Deprecated
72 | public MessageResponse forwardText(
73 | final String chatId,
74 | final String text,
75 | final String forwardChatId,
76 | final long forwardMsgId
77 | ) throws IOException {
78 | return client.messages().sendText(chatId, text, null, null, null, forwardChatId, new long[]{forwardMsgId}, null);
79 | }
80 |
81 | public MessageResponse sendFile(final SendFileRequest request) throws IOException {
82 | return client.messages().sendFile(
83 | request.getChatId(),
84 | request.getFile(),
85 | request.getCaption(),
86 | toLongArray(request.getReplyMsgId()),
87 | request.getForwardChatId(),
88 | toLongArray(request.getForwardMsgId()),
89 | request.getKeyboard()
90 | );
91 | }
92 |
93 | /**
94 | * @deprecated Use {@link BotApiClientController#sendFile(SendFileRequest)}
95 | */
96 | @Deprecated
97 | public MessageResponse sendFile(
98 | final String chatId,
99 | final File file
100 | ) throws IOException {
101 | return client.messages().sendFile(chatId, file, null, null, null, null, null);
102 | }
103 |
104 | /**
105 | * @deprecated Use {@link BotApiClientController#sendFile(SendFileRequest)}
106 | */
107 | @Deprecated
108 | public MessageResponse sendFile(
109 | final String chatId,
110 | final File file,
111 | final String caption
112 | ) throws IOException {
113 | return client.messages().sendFile(chatId, file, caption, null, null, null, null);
114 | }
115 |
116 | /**
117 | * @deprecated Use {@link BotApiClientController#sendFile(SendFileRequest)}
118 | */
119 | @Deprecated
120 | public MessageResponse replyFile(
121 | final String chatId,
122 | final File file,
123 | final long replyMsgId,
124 | final String caption
125 | ) throws IOException {
126 | return client.messages().sendFile(chatId, file, caption, new long[]{replyMsgId}, null, null, null);
127 | }
128 |
129 | /**
130 | * @deprecated Use {@link BotApiClientController#sendFile(SendFileRequest)}
131 | */
132 | @Deprecated
133 | public MessageResponse forwardFile(
134 | final String chatId,
135 | final File file,
136 | final String forwardChatId,
137 | final long forwardMsgId,
138 | final String caption
139 | ) throws IOException {
140 | return client.messages().sendFile(chatId, file, caption, null, forwardChatId, new long[]{forwardMsgId}, null);
141 | }
142 |
143 | public ApiResponse editText(final EditTextRequest request) throws IOException {
144 | return client.messages().editText(
145 | request.getChatId(),
146 | request.getMsgId(),
147 | request.getNewText(),
148 | request.getKeyboard()
149 | );
150 | }
151 |
152 | /**
153 | * @deprecated Use {@link BotApiClientController#editText(EditTextRequest)}
154 | */
155 | @Deprecated
156 | public ApiResponse editText(
157 | final String chatId,
158 | final long msgId,
159 | final String text
160 | ) throws IOException {
161 | return client.messages().editText(chatId, msgId, text, null);
162 | }
163 |
164 | public ApiResponse deleteMessage(final DeleteMessagesRequest request) throws IOException {
165 | return client.messages().deleteMessages(
166 | request.getChatId(),
167 | toLongArray(request.getMsgId())
168 | );
169 | }
170 |
171 | /**
172 | * @deprecated Use {@link BotApiClientController#deleteMessage(DeleteMessagesRequest)}
173 | */
174 | @Deprecated
175 | public ApiResponse deleteMessage(
176 | final String chatId,
177 | final long msgId
178 | ) throws IOException {
179 | return client.messages().deleteMessages(chatId, new long[] {msgId});
180 | }
181 |
182 | public ApiResponse answerCallbackQuery(final AnswerCallbackQueryRequest request) throws IOException {
183 | return client.messages().answerCallbackQuery(
184 | request.getQueryId(),
185 | request.getText(),
186 | request.getShowAlert(),
187 | request.getUrl()
188 | );
189 | }
190 |
191 | public ChatsGetAdminsResponse getChatAdmins(String chatId) throws IOException {
192 | return client.chats().getAdmins(chatId);
193 | }
194 |
195 | public ChatsGetInfoResponse getChatInfo(String chatId) throws IOException {
196 | return client.chats().getInfo(chatId);
197 | }
198 |
199 | public ApiResponse sendActions(String chatId, ChatAction... actions) throws IOException {
200 | return client.chats().sendActions(chatId, actions);
201 | }
202 |
203 | public SelfGetResponse getSelfInfo() throws IOException {
204 | return client.self().get();
205 | }
206 |
207 | private long[] toLongArray(final List longList) {
208 | if (longList == null) {
209 | return null;
210 | } else {
211 | return longList.stream().mapToLong(msgId -> msgId).toArray();
212 | }
213 | }
214 | }
215 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/BotLogger.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | public class BotLogger {
7 | private static Logger logger = LoggerFactory.getLogger(BotLogger.class);
8 | private static String BOT_TAG = "IM_BOT";
9 |
10 | public static void i(String message) {
11 | logger.info(String.format("%s %s", BOT_TAG, message));
12 | }
13 |
14 | public static void e(Exception e) {
15 | logger.error(e.getMessage(), String.format("%s %s", BOT_TAG, e.getMessage()));
16 | }
17 |
18 | public static void e(Exception e, String message) {
19 | logger.error(String.format("%s %s", BOT_TAG, message), e);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/Api.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | public interface Api {
4 | Self self();
5 | Messages messages();
6 | Chats chats();
7 | }
8 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/ApiImplementationFactory.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import com.google.gson.Gson;
4 | import okhttp3.HttpUrl;
5 | import okhttp3.MultipartBody;
6 | import okhttp3.Request;
7 | import okhttp3.RequestBody;
8 |
9 | import javax.annotation.Nonnull;
10 | import java.io.File;
11 | import java.io.IOException;
12 | import java.lang.reflect.Method;
13 | import java.lang.reflect.Proxy;
14 | import java.nio.file.Files;
15 | import java.util.List;
16 |
17 | class ApiImplementationFactory {
18 |
19 | private final Gson gson;
20 | private final RequestExecutor requestExecutor;
21 | private final HttpUrl baseUrl;
22 | private final String token;
23 |
24 | ApiImplementationFactory(
25 | @Nonnull final Gson gson,
26 | @Nonnull final RequestExecutor requestExecutor,
27 | @Nonnull final String baseUrl,
28 | @Nonnull final String token
29 | ) {
30 | this.gson = gson;
31 | this.requestExecutor = requestExecutor;
32 | this.baseUrl = HttpUrl.get(baseUrl);
33 | this.token = token;
34 | }
35 |
36 | T createImplementation(final Class clazz) {
37 | Object impl = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, (proxy, method, args) -> {
38 | final List query = new QueryBuilder(gson, method, args).build();
39 | final Request request = buildRequest(method, query);
40 | return requestExecutor.execute(request, method.getReturnType());
41 | });
42 | return clazz.cast(impl);
43 | }
44 |
45 | private Request buildRequest(final Method method, final List query) throws IOException {
46 | verifyMethod(method);
47 | GetRequest getAnnotation = method.getAnnotation(GetRequest.class);
48 | if (getAnnotation != null) {
49 | return buildGetRequest(getAnnotation.value(), query);
50 | }
51 |
52 | PostRequest postAnnotation = method.getAnnotation(PostRequest.class);
53 | if (postAnnotation != null) {
54 | return buildPostRequest(postAnnotation.value(), query);
55 | }
56 | throw new IllegalArgumentException("Request must be GET or POST");
57 | }
58 |
59 | private Request buildGetRequest(final String name, final List query) {
60 | final HttpUrl.Builder urlBuilder = baseUrl.newBuilder()
61 | .addPathSegments(name)
62 | .addQueryParameter("token", token);
63 | for (QueryParameter parameter : query) {
64 | urlBuilder.addQueryParameter(parameter.name, parameter.getValueAsString());
65 | }
66 | return new Request.Builder()
67 | .url(urlBuilder.build())
68 | .build();
69 | }
70 |
71 | private Request buildPostRequest(final String name, final List query) throws IOException {
72 | final HttpUrl url = baseUrl.newBuilder()
73 | .addPathSegments(name)
74 | .build();
75 | final MultipartBody.Builder builder = new MultipartBody.Builder()
76 | .setType(MultipartBody.FORM)
77 | .addFormDataPart("token", token);
78 | for (QueryParameter parameter : query) {
79 | if (parameter.value instanceof File) {
80 | File file = (File) parameter.value;
81 | builder.addFormDataPart(parameter.name, file.getName(), RequestBody.create(null, Files.readAllBytes(file.toPath())));
82 | } else if (parameter.value != null) {
83 | builder.addFormDataPart(parameter.name, parameter.value.toString());
84 | }
85 | }
86 | return new Request.Builder()
87 | .url(url)
88 | .post(builder.build())
89 | .build();
90 | }
91 |
92 | private static void verifyMethod(final Method method) {
93 | for (Class> exClass : method.getExceptionTypes()) {
94 | if (exClass == IOException.class) {
95 | return;
96 | }
97 | }
98 | throw new RuntimeException("Request method must throw IOException");
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/BotApi.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import com.google.gson.Gson;
4 | import okhttp3.OkHttpClient;
5 |
6 | import javax.annotation.Nonnull;
7 |
8 | public class BotApi implements Api {
9 |
10 | private final Messages messages;
11 | private final Self self;
12 | private final Chats chats;
13 |
14 | public BotApi(
15 | @Nonnull final Gson gson,
16 | @Nonnull final OkHttpClient httpClient,
17 | @Nonnull final String baseUrl,
18 | @Nonnull final String token
19 | ) {
20 | final ApiImplementationFactory factory = new ApiImplementationFactory(
21 | gson,
22 | new OkHttpRequestExecutor(httpClient),
23 | baseUrl,
24 | token
25 | );
26 |
27 | messages = factory.createImplementation(Messages.class);
28 | self = factory.createImplementation(Self.class);
29 | chats = factory.createImplementation(Chats.class);
30 | }
31 |
32 | @Override
33 | public Self self() {
34 | return self;
35 | }
36 |
37 | @Override
38 | public Messages messages() {
39 | return messages;
40 | }
41 |
42 | @Override
43 | public Chats chats() {
44 | return chats;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/Chats.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import ru.mail.im.botapi.entity.ChatAction;
4 | import ru.mail.im.botapi.response.ApiResponse;
5 | import ru.mail.im.botapi.response.ChatsGetAdminsResponse;
6 | import ru.mail.im.botapi.response.ChatsGetInfoResponse;
7 |
8 | import java.io.IOException;
9 |
10 | public interface Chats {
11 |
12 | @GetRequest("chats/sendActions")
13 | ApiResponse sendActions(@RequestParam("chatId") final String chatId,
14 | @RequestParam("actions") final ChatAction... actions) throws IOException;
15 |
16 | @GetRequest("chats/getInfo")
17 | ChatsGetInfoResponse getInfo(@RequestParam("chatId") final String chatId) throws IOException;
18 |
19 | @GetRequest("chats/getAdmins")
20 | ChatsGetAdminsResponse getAdmins(@RequestParam("chatId") final String chatId) throws IOException;
21 | }
22 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/Events.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import ru.mail.im.botapi.response.ApiResponse;
4 |
5 | import java.io.IOException;
6 |
7 | public interface Events {
8 |
9 | @GetRequest("events/get")
10 | ApiResponse fetchEvents() throws IOException;
11 | }
12 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/GetRequest.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | @Retention(RetentionPolicy.RUNTIME)
9 | @Target(ElementType.METHOD)
10 | @interface GetRequest {
11 | String value();
12 | }
13 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/Messages.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import ru.mail.im.botapi.api.entity.InlineKeyboardButton;
4 | import ru.mail.im.botapi.response.ApiResponse;
5 | import ru.mail.im.botapi.response.MessageResponse;
6 |
7 | import java.io.File;
8 | import java.io.IOException;
9 | import java.util.List;
10 |
11 | public interface Messages {
12 |
13 | @GetRequest("messages/sendText")
14 | MessageResponse sendText(
15 | @RequestParam("chatId") final String chatId,
16 | @RequestParam("text") final String text,
17 | @RequestParam("format") final String format,
18 | @RequestParam("parseMode") final String parseMode,
19 | @RequestParam("replyMsgId") final long[] replyMsgId,
20 | @RequestParam("forwardChatId") final String forwardChatId,
21 | @RequestParam("forwardMsgId") final long[] forwardMsgId,
22 | @RequestParam("inlineKeyboardMarkup") final List> keyboard
23 | ) throws IOException;
24 |
25 | @PostRequest("messages/sendFile")
26 | MessageResponse sendFile(
27 | @RequestParam("chatId") final String chatId,
28 | @RequestParam("file") final File file,
29 | @RequestParam("caption") String caption,
30 | @RequestParam("replyMsgId") final long[] replyMsgId,
31 | @RequestParam("forwardChatId") final String forwardChatId,
32 | @RequestParam("forwardMsgId") final long[] forwardMsgId,
33 | @RequestParam("inlineKeyboardMarkup") final List> keyboard
34 | ) throws IOException;
35 |
36 | @GetRequest("messages/editText")
37 | ApiResponse editText(
38 | @RequestParam("chatId") final String chatId,
39 | @RequestParam("msgId") final long msgId,
40 | @RequestParam("text") final String newText,
41 | @RequestParam("inlineKeyboardMarkup") final List> keyboard
42 | ) throws IOException;
43 |
44 |
45 | @GetRequest("messages/deleteMessages")
46 | ApiResponse deleteMessages(
47 | @RequestParam("chatId") final String chatId,
48 | @RequestParam("msgId") final long[] msgId
49 | ) throws IOException;
50 |
51 | @GetRequest("messages/answerCallbackQuery")
52 | ApiResponse answerCallbackQuery(
53 | @RequestParam("queryId") final String queryId,
54 | @RequestParam("text") final String text,
55 | @RequestParam("showAlert") final Boolean showAlert,
56 | @RequestParam("url") final String url
57 | ) throws IOException;
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/OkHttpRequestExecutor.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 | import okhttp3.OkHttpClient;
6 | import okhttp3.Request;
7 | import okhttp3.Response;
8 | import okhttp3.ResponseBody;
9 | import ru.mail.im.botapi.BotLogger;
10 | import ru.mail.im.botapi.entity.ChatType;
11 | import ru.mail.im.botapi.json.ChatTypeGsonDeserializer;
12 |
13 | import java.io.IOException;
14 |
15 | class OkHttpRequestExecutor implements RequestExecutor {
16 |
17 | private final Gson gson = new GsonBuilder()
18 | .registerTypeAdapter(ChatType.class, new ChatTypeGsonDeserializer())
19 | .create();
20 |
21 | private OkHttpClient httpClient;
22 |
23 | OkHttpRequestExecutor(final OkHttpClient httpClient) {
24 | this.httpClient = httpClient;
25 | }
26 |
27 | @Override
28 | public T execute(final Request request, final Class responseClass) throws IOException {
29 | BotLogger.i("request:" + request.url());
30 | try (Response response = httpClient.newCall(request).execute()) {
31 | String message = response.message();
32 | BotLogger.i("response message:" + message);
33 | if (!response.isSuccessful()) {
34 | throw new IOException("Bad HTTP status " + response.code());
35 | }
36 | final ResponseBody body = response.body();
37 | if (body == null) {
38 | throw new NullPointerException("Response body is null");
39 | }
40 | String json = body.string() ;
41 | BotLogger.i("response body:" + json);
42 | return gson.fromJson(json, responseClass);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/PostRequest.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | @Retention(RetentionPolicy.RUNTIME)
9 | @Target(ElementType.METHOD)
10 | @interface PostRequest {
11 | String value();
12 | }
13 |
--------------------------------------------------------------------------------
/library/src/main/java/ru/mail/im/botapi/api/QueryBuilder.java:
--------------------------------------------------------------------------------
1 | package ru.mail.im.botapi.api;
2 |
3 | import com.google.gson.Gson;
4 |
5 | import java.lang.annotation.Annotation;
6 | import java.lang.reflect.Array;
7 | import java.lang.reflect.Method;
8 | import java.util.ArrayList;
9 | import java.util.Collections;
10 | import java.util.List;
11 |
12 | class QueryBuilder {
13 | private final Gson gson;
14 | private final Method method;
15 | private final Object[] args;
16 |
17 | QueryBuilder(final Gson gson, final Method method, final Object[] args) {
18 | this.gson = gson;
19 | this.method = method;
20 | this.args = args;
21 | }
22 |
23 | List build() {
24 | if (args == null) {
25 | return Collections.emptyList();
26 | }
27 | final List result = new ArrayList<>(args.length);
28 | for (int i = 0; i < args.length; i++) {
29 | final String name = getParamName(i);
30 | for (Object value : getParamValues(i)) {
31 | if (value != null) {
32 | result.add(new QueryParameter(gson, name, value));
33 | }
34 | }
35 | }
36 | return result;
37 | }
38 |
39 | private String getParamName(final int index) {
40 | final Annotation[] annotations = method.getParameterAnnotations()[index];
41 | for (Annotation annotation : annotations) {
42 | if (annotation instanceof RequestParam) {
43 | return ((RequestParam) annotation).value();
44 | }
45 | }
46 | throw new IllegalArgumentException("Parameter with index " + index + " was not annotated with @RequestParam");
47 | }
48 |
49 | private List