Move separate commits (#157)

* Update HOWTO.md (#155)

- add video edition of this howto, only a draft
- add two FAQ's

* Update license to MIT

* Update HOWTO.md (#155)

- add video edition of this howto, only a draft
- add two FAQ's

* Update license to MIT

* Migrate to separate modules

* Move to separate modules

* Move to separate modules

* Move to separate modules
This commit is contained in:
Ruben Bermudez 2016-11-17 02:41:12 +01:00 committed by GitHub
parent e01925a389
commit 0c03ab093f
185 changed files with 6599 additions and 6701 deletions

View File

@ -1,7 +1,7 @@
language: java
jdk:
- oraclejdk8
install: mvn install -DskipTests -Dgpg.skip
install: mvn install -Dgpg.skip
script: mvn clean compile
notifications:
webhooks:

914
Bots.ipr Normal file
View File

@ -0,0 +1,914 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="telegrambots" />
<module name="telegrambotsmeta" />
</profile>
<profile name="Annotation profile for Bots" enabled="true">
<sourceOutputDir name="../telegrambots/target/generated-sources/annotations" />
<sourceTestOutputDir name="../telegrambots/target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="telegrambots (1)" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="Bots" target="1.5" />
<module name="telegrambots" target="1.8" />
<module name="telegrambotsmeta" target="1.8" />
</bytecodeTargetLevel>
</component>
<component name="Encoding" defaultCharsetForPropertiesFiles="UTF-8">
<file url="file://$PROJECT_DIR$/telegrambots" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/telegrambotsmeta" charset="UTF-8" />
<file url="PROJECT" charset="UTF-8" />
</component>
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<option name="myLocal" value="true" />
<inspection_tool class="JSHint" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="JSLint" enabled="true" level="ERROR" enabled_by_default="true" />
</profile>
<version value="1.0" />
</component>
<component name="JSHintConfiguration" version="2.6.3" use-config-file="false">
<option asi="false" />
<option bitwise="false" />
<option boss="false" />
<option browser="true" />
<option camelcase="true" />
<option couch="false" />
<option curly="true" />
<option debug="false" />
<option devel="false" />
<option dojo="false" />
<option eqeqeq="true" />
<option eqnull="false" />
<option es3="false" />
<option esnext="false" />
<option evil="false" />
<option expr="false" />
<option forin="true" />
<option freeze="false" />
<option funcscope="false" />
<option gcl="false" />
<option globalstrict="false" />
<option immed="false" />
<option iterator="false" />
<option jquery="false" />
<option lastsemic="false" />
<option latedef="true" />
<option laxbreak="false" />
<option laxcomma="false" />
<option loopfunc="false" />
<option maxerr="50" />
<option maxlen="80" />
<option mootools="false" />
<option moz="false" />
<option multistr="false" />
<option newcap="false" />
<option noarg="true" />
<option node="false" />
<option noempty="true" />
<option nomen="false" />
<option nonbsp="true" />
<option nonew="true" />
<option nonstandard="false" />
<option notypeof="false" />
<option noyield="false" />
<option onevar="false" />
<option passfail="false" />
<option phantom="false" />
<option plusplus="false" />
<option proto="false" />
<option prototypejs="false" />
<option quotmark="false" />
<option rhino="false" />
<option scripturl="false" />
<option shadow="false" />
<option smarttabs="false" />
<option strict="true" />
<option sub="false" />
<option supernew="false" />
<option trailing="true" />
<option undef="true" />
<option unused="true" />
<option validthis="false" />
<option white="false" />
<option worker="false" />
<option wsh="false" />
<option yui="false" />
</component>
<component name="JSLintConfiguration" json="true">
<option maxerr="50" />
<option maxlen="80" />
<option white="true" />
</component>
<component name="JsBowerSettings">
<exe-path>/usr/local/bin/bower</exe-path>
<config-path />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
<component name="ProjectCodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS">
<value />
</option>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="GoogleStyle" />
</component>
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Bots.iml" filepath="$PROJECT_DIR$/Bots.iml" />
<module fileurl="file://$PROJECT_DIR$/telegrambots/telegrambots.iml" filepath="$PROJECT_DIR$/telegrambots/telegrambots.iml" />
<module fileurl="file://$PROJECT_DIR$/telegrambotsmeta/telegrambotsmeta.iml" filepath="$PROJECT_DIR$/telegrambotsmeta/telegrambotsmeta.iml" />
</modules>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="PropertiesComponent">
<property name="GoToClass.includeLibraries" value="false" />
<property name="GoToClass.toSaveIncludeLibraries" value="false" />
<property name="GoToFile.includeJavaFiles" value="false" />
<property name="MemberChooser.sorted" value="false" />
<property name="MemberChooser.showClasses" value="true" />
<property name="MemberChooser.copyJavadoc" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/.." />
<property name="options.lastSelected" value="File.Encoding" />
<property name="options.splitter.main.proportions" value="0.3" />
<property name="options.splitter.details.proportions" value="0.2" />
<property name="settings.editor.selected.configurable" value="configurable.group.appearance" />
<property name="settings.editor.splitter.proportion" value="0.2" />
</component>
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
<component name="libraryTable">
<library name="com.google.inject:guice:4.1.0" type="repository">
<properties maven-id="com.google.inject:guice:4.1.0" />
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/inject/guice/4.1.0/guice-4.1.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/aopalliance/aopalliance/1.0/aopalliance-1.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/com/google/guava/guava/19.0/guava-19.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/google/inject/guice/4.1.0/guice-4.1.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/inject/guice/4.1.0/guice-4.1.0-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: aopalliance:aopalliance:1.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/aopalliance/aopalliance/1.0/aopalliance-1.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/aopalliance/aopalliance/1.0/aopalliance-1.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/aopalliance/aopalliance/1.0/aopalliance-1.0-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.8.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-annotations/2.8.4/jackson-annotations-2.8.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-annotations/2.8.4/jackson-annotations-2.8.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-annotations/2.8.4/jackson-annotations-2.8.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-core/2.8.4/jackson-core-2.8.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-core/2.8.4/jackson-core-2.8.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-core/2.8.4/jackson-core-2.8.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-databind/2.8.4/jackson-databind-2.8.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-databind/2.8.4/jackson-databind-2.8.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-databind/2.8.4/jackson-databind-2.8.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:2.5.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-base/2.5.4/jackson-jaxrs-base-2.5.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-base/2.5.4/jackson-jaxrs-base-2.5.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-base/2.5.4/jackson-jaxrs-base-2.5.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.5.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-json-provider/2.5.4/jackson-jaxrs-json-provider-2.5.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-json-provider/2.5.4/jackson-jaxrs-json-provider-2.5.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-json-provider/2.5.4/jackson-jaxrs-json-provider-2.5.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.5.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/module/jackson-module-jaxb-annotations/2.5.4/jackson-module-jaxb-annotations-2.5.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/module/jackson-module-jaxb-annotations/2.5.4/jackson-module-jaxb-annotations-2.5.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/module/jackson-module-jaxb-annotations/2.5.4/jackson-module-jaxb-annotations-2.5.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.google.guava:guava:19.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/guava/guava/19.0/guava-19.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/google/guava/guava/19.0/guava-19.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/guava/guava/19.0/guava-19.0-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.google.inject:guice:4.1.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/inject/guice/4.1.0/guice-4.1.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/google/inject/guice/4.1.0/guice-4.1.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/inject/guice/4.1.0/guice-4.1.0-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.sun.jersey:jersey-bundle:1.19.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-bundle/1.19.3/jersey-bundle-1.19.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-bundle/1.19.3/jersey-bundle-1.19.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-bundle/1.19.3/jersey-bundle-1.19.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.sun.jersey:jersey-core:1.19.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-core/1.19.3/jersey-core-1.19.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-core/1.19.3/jersey-core-1.19.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-core/1.19.3/jersey-core-1.19.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.sun.jersey:jersey-grizzly2-servlet:1.19.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-grizzly2-servlet/1.19.3/jersey-grizzly2-servlet-1.19.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-grizzly2-servlet/1.19.3/jersey-grizzly2-servlet-1.19.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-grizzly2-servlet/1.19.3/jersey-grizzly2-servlet-1.19.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.sun.jersey:jersey-grizzly2:1.19.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-grizzly2/1.19.3/jersey-grizzly2-1.19.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-grizzly2/1.19.3/jersey-grizzly2-1.19.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-grizzly2/1.19.3/jersey-grizzly2-1.19.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.sun.jersey:jersey-server:1.19.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-server/1.19.3/jersey-server-1.19.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-server/1.19.3/jersey-server-1.19.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-server/1.19.3/jersey-server-1.19.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: com.sun.jersey:jersey-servlet:1.19.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-servlet/1.19.3/jersey-servlet-1.19.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-servlet/1.19.3/jersey-servlet-1.19.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/sun/jersey/jersey-servlet/1.19.3/jersey-servlet-1.19.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: commons-codec:commons-codec:1.9">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/commons-codec/commons-codec/1.9/commons-codec-1.9.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/commons-codec/commons-codec/1.9/commons-codec-1.9-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/commons-codec/commons-codec/1.9/commons-codec-1.9-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: commons-io:commons-io:2.5">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/commons-io/commons-io/2.5/commons-io-2.5.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/commons-io/commons-io/2.5/commons-io-2.5-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/commons-io/commons-io/2.5/commons-io-2.5-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: commons-logging:commons-logging:1.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/commons-logging/commons-logging/1.2/commons-logging-1.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/commons-logging/commons-logging/1.2/commons-logging-1.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/commons-logging/commons-logging/1.2/commons-logging-1.2-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: javax.annotation:javax.annotation-api:1.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: javax.inject:javax.inject:1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: javax.servlet:javax.servlet-api:3.0.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: javax.validation:validation-api:1.1.0.Final">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: javax.ws.rs:javax.ws.rs-api:2.0.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/ws/rs/javax.ws.rs-api/2.0.1/javax.ws.rs-api-2.0.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/ws/rs/javax.ws.rs-api/2.0.1/javax.ws.rs-api-2.0.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/ws/rs/javax.ws.rs-api/2.0.1/javax.ws.rs-api-2.0.1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: javax.ws.rs:jsr311-api:1.1.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/ws/rs/jsr311-api/1.1.1/jsr311-api-1.1.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/ws/rs/jsr311-api/1.1.1/jsr311-api-1.1.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/ws/rs/jsr311-api/1.1.1/jsr311-api-1.1.1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: junit:junit:4.12">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.12/junit-4.12.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.12/junit-4.12-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/junit/junit/4.12/junit-4.12-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.apache.httpcomponents:httpclient:4.5.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpclient/4.5.2/httpclient-4.5.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpclient/4.5.2/httpclient-4.5.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpclient/4.5.2/httpclient-4.5.2-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.apache.httpcomponents:httpcore:4.4.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpcore/4.4.4/httpcore-4.4.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpcore/4.4.4/httpcore-4.4.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpcore/4.4.4/httpcore-4.4.4-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.apache.httpcomponents:httpmime:4.5.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpmime/4.5.2/httpmime-4.5.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpmime/4.5.2/httpmime-4.5.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpmime/4.5.2/httpmime-4.5.2-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.grizzly:grizzly-framework:2.3.23">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.23/grizzly-framework-2.3.23.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.23/grizzly-framework-2.3.23-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-framework/2.3.23/grizzly-framework-2.3.23-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.grizzly:grizzly-http-server:2.3.23">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.23/grizzly-http-server-2.3.23.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.23/grizzly-http-server-2.3.23-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-server/2.3.23/grizzly-http-server-2.3.23-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.grizzly:grizzly-http-servlet:2.2.16">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-servlet/2.2.16/grizzly-http-servlet-2.2.16.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-servlet/2.2.16/grizzly-http-servlet-2.2.16-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http-servlet/2.2.16/grizzly-http-servlet-2.2.16-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.grizzly:grizzly-http:2.3.23">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.23/grizzly-http-2.3.23.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.23/grizzly-http-2.3.23-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/grizzly/grizzly-http/2.3.23/grizzly-http-2.3.23-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.hk2.external:aopalliance-repackaged:2.5.0-b05">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/external/aopalliance-repackaged/2.5.0-b05/aopalliance-repackaged-2.5.0-b05.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/external/aopalliance-repackaged/2.5.0-b05/aopalliance-repackaged-2.5.0-b05-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/external/aopalliance-repackaged/2.5.0-b05/aopalliance-repackaged-2.5.0-b05-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.hk2.external:javax.inject:2.5.0-b05">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/external/javax.inject/2.5.0-b05/javax.inject-2.5.0-b05.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/external/javax.inject/2.5.0-b05/javax.inject-2.5.0-b05-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/external/javax.inject/2.5.0-b05/javax.inject-2.5.0-b05-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.hk2:hk2-api:2.5.0-b05">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-api/2.5.0-b05/hk2-api-2.5.0-b05.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-api/2.5.0-b05/hk2-api-2.5.0-b05-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-api/2.5.0-b05/hk2-api-2.5.0-b05-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.hk2:hk2-locator:2.5.0-b05">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-locator/2.5.0-b05/hk2-locator-2.5.0-b05.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-locator/2.5.0-b05/hk2-locator-2.5.0-b05-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-locator/2.5.0-b05/hk2-locator-2.5.0-b05-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.hk2:hk2-utils:2.5.0-b05">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-utils/2.5.0-b05/hk2-utils-2.5.0-b05.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-utils/2.5.0-b05/hk2-utils-2.5.0-b05-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/hk2-utils/2.5.0-b05/hk2-utils-2.5.0-b05-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.hk2:osgi-resource-locator:1.0.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/osgi-resource-locator/1.0.1/osgi-resource-locator-1.0.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/osgi-resource-locator/1.0.1/osgi-resource-locator-1.0.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/hk2/osgi-resource-locator/1.0.1/osgi-resource-locator-1.0.1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.bundles.repackaged:jersey-guava:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.24/jersey-guava-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.24/jersey-guava-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.24/jersey-guava-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.24/jersey-container-grizzly2-http-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.24/jersey-container-grizzly2-http-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-http/2.24/jersey-container-grizzly2-http-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-servlet:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-servlet/2.24/jersey-container-grizzly2-servlet-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-servlet/2.24/jersey-container-grizzly2-servlet-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-grizzly2-servlet/2.24/jersey-container-grizzly2-servlet-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.containers:jersey-container-servlet-core:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-servlet-core/2.24/jersey-container-servlet-core-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-servlet-core/2.24/jersey-container-servlet-core-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-servlet-core/2.24/jersey-container-servlet-core-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.containers:jersey-container-servlet:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-servlet/2.24/jersey-container-servlet-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-servlet/2.24/jersey-container-servlet-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/containers/jersey-container-servlet/2.24/jersey-container-servlet-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.core:jersey-client:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.24/jersey-client-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.24/jersey-client-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-client/2.24/jersey-client-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.core:jersey-common:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.24/jersey-common-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.24/jersey-common-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-common/2.24/jersey-common-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.core:jersey-server:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.24/jersey-server-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.24/jersey-server-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/core/jersey-server/2.24/jersey-server-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.24/jersey-entity-filtering-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.24/jersey-entity-filtering-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/ext/jersey-entity-filtering/2.24/jersey-entity-filtering-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.24/jersey-media-jaxb-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.24/jersey-media-jaxb-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-jaxb/2.24/jersey-media-jaxb-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.media:jersey-media-json-jackson:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.24/jersey-media-json-jackson-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.24/jersey-media-json-jackson-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/media/jersey-media-json-jackson/2.24/jersey-media-json-jackson-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-grizzly2:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/test-framework/providers/jersey-test-framework-provider-grizzly2/2.24/jersey-test-framework-provider-grizzly2-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/test-framework/providers/jersey-test-framework-provider-grizzly2/2.24/jersey-test-framework-provider-grizzly2-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/test-framework/providers/jersey-test-framework-provider-grizzly2/2.24/jersey-test-framework-provider-grizzly2-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.glassfish.jersey.test-framework:jersey-test-framework-core:2.24">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/test-framework/jersey-test-framework-core/2.24/jersey-test-framework-core-2.24.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/test-framework/jersey-test-framework-core/2.24/jersey-test-framework-core-2.24-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/glassfish/jersey/test-framework/jersey-test-framework-core/2.24/jersey-test-framework-core-2.24-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.hamcrest:hamcrest-core:1.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.javassist:javassist:3.20.0-GA">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/javassist/javassist/3.20.0-GA/javassist-3.20.0-GA.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/javassist/javassist/3.20.0-GA/javassist-3.20.0-GA-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/javassist/javassist/3.20.0-GA/javassist-3.20.0-GA-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.json:json:20160810">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20160810/json-20160810.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20160810/json-20160810-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/json/json/20160810/json-20160810-sources.jar!/" />
</SOURCES>
</library>
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>

203
HOWTO.md
View File

@ -1,203 +0,0 @@
So, you just wanna program your own Telegram bot with @rubenlagus library TelegramBots? Then I'm going to show you how to start ;)
##### Table of Contents
[Preparations](#preparations)
[Let's code!](#lets_code)
[FAQ](#faq)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1. [How to get picture?](#question_how_to_get_picture)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2. [How to send photos?](#question_how_to_send_photos)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3. [How to use custom keyboards?](#question_how_to_use_custom_keyboards)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;4. [How can I compile my project?](#question_how_to_compile)
<a name="preparations"/>
## Preparations
First you need to download the latest .jar from the Release site [here](https://github.com/rubenlagus/TelegramBots/releases). You can choose between Jar with or without dependencies. If you don't know which one to choose, we recommend to download the full jar with all dependencies ;)
Next, you need to integrate it into your project.
Create a new project for your bot, in the example below we are showing you how to do it in eclipse. But of course, you are free to code in whatever IDE you want ;)
If you don't know how to include a external .jar into your Eclipse project, maybe [this](https://www.youtube.com/watch?v=VWnfHkBgO1I) video is helpful for you
You can use it with Maven or Gradle directly from Central repository, just this to your *pom.xml* file:
```xml
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>2.4.0</version>
</dependency>
```
You can also find it in a different repository, just in case, search [here](https://jitpack.io/#rubenlagus/TelegramBots).
<a name="lets_code"/>
## Let's code!
Create a new class that extends one of the following
```TelegramLongPollingBot``` -> bot is asking Telegram servers continuously if new updates are available
```TelegramWebhookBot``` -> our bot is "called" from Telegram servers when updates are available
```TelegramLongPollingCommandBot``` -> simply like TelegramLongPollingBot, but based around the idea of Commands
Due to the fact that the TelegramLongPollingBot is a little bit less complicated than the others, we are going to work with him in this example.
Extend ```TelegramLongPollingBot``` with one of your own classes. If we want that the bot can work normally, we must implement the following methods: ```getBotUsername():String```, ```getBotToken():String``` and ```onUpdateReceived(update: Update)```
The first two methods are really easy to implement. Just create a new class that contains all the information for the bot (username, token and maybe in the future some database information)
At the end it could look like this:
```java
public class BotConfig {
public static final String BOT_USERNAME = "echoBot";
public static final String BOT_TOKEN = "{you secret bot token that you got from BotFather}";
}
```
After it, return these static variables like this one:
```java
@Override
public String getBotToken() {
return BotConfig.BOT_TOKEN;
}
```
The last method could look like this:
```java
@Override
public void onUpdateReceived(Update update) {
//check if the update has a message
if(update.hasMessage()){
Message message = update.getMessage();
//check if the message has text. it could also contain for example a location ( message.hasLocation() )
if(message.hasText()){
//create an object that contains the information to send back the message
SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId().toString()); //who should get from the message the sender that sent it.
sendMessageRequest.setText("you said: " + message.getText());
try {
sendMessage(sendMessageRequest); //at the end, so some magic and send the message ;)
} catch (TelegramApiException e) {
//do some error handling
}
}
}
}
```
The principle is rather easy, we have an ```update```, we see that it contains a text -> we create a Send*** object, fill it up with all necessary infos (user/chatId, text) and fire it up
If you want to send also other types of media (such as photos or audio), then check out our FAQ at the end if this HOWTO. Also please check out the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It contains useful information on how to use the lib from @rubenlagus.
If you have questions that are not handled here or in the example repo, than feel free to open a new Issue :P
In any case, you can reach us at [our Telegram group chat](https://telegram.me/JavaBotsApi) ;)
But to be in context: our bot is not ready, yet. It lacks a way to tell the library that we have a super cool new UpdateHandler written, you remember? 😏
```java
public static void main(String[] args) {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new MyProjectHandler());
} catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e);
}
}
```
<a name="faq"/>
## FAQ
Question: <a name="question_how_to_get_picture"/>
<b>How to get a picture?</b>
Answer: A ```onUpdateReceived()``` Method that just downloads every Photo that users send to the bot could look like this:
```java
@Override
public void onUpdateReceived(Update update) {
//check if the update has a message
if (update.hasMessage()) {
Message message = update.getMessage();
//check if we got some photos
if (message.getPhoto() != null) {
/*
* Just save our received photos in a list. At this point, we do not really have the photos. We have just their id.
* And with their id's we can download them from Telegram servers
*/
for (int i = 0; i < photos.size(); i++) {
GetFile getFileRequest = new GetFile();
getFileRequest.setFileId(photos.get(i).getFileId());
try {
//we send a request with our fileId to get our filePath.
File file = getFile(getFileRequest);
/*
* After that, we can now start to save them on our local machine.
* Please have a look on the API specification, on how to download the files with their filepaths you just got in the code above
* https://core.telegram.org/bots/api#file
*
* Just replace <file_path> with File.getFilePath();
*/
// In this example, we just print here the filePaths
System.out.println(file.getFilePath());
} catch (TelegramApiException e) {
//TODO: so some error handling
}
}
}
}
}
```
Question: <a name="question_how_to_send_photos"/>
<b>How to send photos?</b>
Answer:
```java
@Override
public void onUpdateReceived(Update update) {
//check if the update has a message
if(update.hasMessage()){
Message message = update.getMessage();
//check if the message has text. it could also contain for example a location ( message.hasLocation() )
if(message.hasText()){
if(message.getText().equals("/wiki")){
SendPhoto sendPhotoRequest = new SendPhoto();
sendPhotoRequest.setChatId(message.getChatId().toString());
//path: String, photoName: String
sendPhotoRequest.setNewPhoto("/home/marcel/Downloads/potd_wikipedia.jpg", "Good Friday.jpg"); //
try {
sendPhoto(sendPhotoRequest);
} catch (TelegramApiException e) {
/*
* Do some error handling
* e.printStackTrace();
*/
}
}
}
}
}
```
This method uploads the photo every time the user send the bot /wiki. Telegram stores the files we upload on their server. And if next time someone wants to retrieve THE SAME photo we uploaded some time ago, you should use instead of SendPhoto.setNewPhoto() the SendPhoto.setPhoto() method. This method has just one parameter, file_id.
Question: <a name="question_how_to_use_custom_keyboards"/>
<b>How to use custom keyboards?</b>
Answer: You can look at the [source code](https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java) for [@Weatherbot](https://telegram.me/weatherbot) in the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It should contain all necessary information about using custom keyboards.
<a name="question_how_to_compile"/>
Question: <b>How can I compile my project?</b>
Answer: This is just one way, how you can compile it (here with maven). The example below below is compiling the TelegramBotsExample repo.
[![asciicast](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj.png)](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj)

696
LICENSE
View File

@ -1,675 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
MIT License
Copyright (c) 2016 Ruben Bermudez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,9 +1,11 @@
# Telegram Bot Java Library
[![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi)
[![Build Status](https://travis-ci.org/rubenlagus/TelegramBots.svg?branch=master)](https://travis-ci.org/rubenlagus/TelegramBots)
[![Jitpack](https://jitpack.io/v/rubenlagus/TelegramBots.svg)](https://jitpack.io/#rubenlagus/TelegramBots)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.telegram/telegrambots/badge.svg)](http://mvnrepository.com/artifact/org.telegram/telegrambots)
[![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi)
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/rubenlagus/TelegramBots/blob/master/LICENSE)
A simple to use library to create Telegram Bots in Java
## Contributions
@ -24,12 +26,12 @@ Just import add the library to your project with one of these options:
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>2.4.0</version>
<version>2.4.1</version>
</dependency>
```
2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/v2.4.0)
3. Download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.4.0)
2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/v2.4.1)
3. Download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.4.1)
In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`.
@ -87,16 +89,24 @@ This library use [Telegram bot API](https://core.telegram.org/bots), you can fin
Feel free to create issues [here](https://github.com/rubenlagus/TelegramBots/issues) as you need or join the [chat](https://telegram.me/JavaBotsApi)
## License
MIT License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Copyright (c) 2016 Ruben Bermudez
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,10 @@
### <a id="2.4.1"></a>2.4.1 ###
1. Split library in two modules to allow custom implementations.
2. Use [Guice](https://github.com/google/guice) for dependency injection.
3. Use [Jackson](https://github.com/FasterXML/jackson) for json (de)serialization.
4. Added extra validation to methods before performing requests.
5. BotOptions has been renamed ot DefaultBotOptions. It allows now to set number of threads for async methods execution and the complete `RequestConfig` for customization purpose.
6. Added convenient method for `setChatId` using just a `Long` value instead of an String.
7. Moved to MIT license
**[[How to update to version 2.4.1|How-To-Update#2.4.1]]**

View File

@ -0,0 +1,5 @@
* [Terminated by other long poll or webhook](#terminted_by_other)
## <a id="terminted_by_other"></a>Terminated by other long poll or webhook ##
It means that you have already a running instance of your bot. To solve it, close all running ones and then you can start a new instance.

180
TelegramBots.wiki/FAQ.md Normal file
View File

@ -0,0 +1,180 @@
* [How to get picture?](#how_to_get_picture)
* [How to send photos?](#how_to_send_photos)
* [How to use custom keyboards?](#how_to_use_custom_keyboards)
* [How can I run my bot?](#how_to_host)
* [How can I compile my project?](#how_to_compile)
## <a id="how_to_get_picture"></a>How to download photo? ##
To download a picture (or any other file), you will need the `file_path` of the file. Let start by finding the photo we want to download, the following method will extract the `PhotoSize` from a photo sent to the bot (in our case, we are taken the bigger size of those provided):
```java
public PhotoSize getPhoto(Update update) {
// Check that the update contains a message and the message has a photo
if (update.hasMessage() && update.getMessage().hasPhoto()) {
// When receiving a photo, you usually get different sizes of it
List<PhotoSize> photos = update.getMessage().getPhoto();
// We fetch the bigger photo
return photos.stream()
.sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
.findFirst()
.orElse(null);
}
// Return null if not found
return null;
}
```
Once we have the *photo* we have to options: The `file_path` is already present or we need to get it, the following method will handle both of them and return the final `file_path`:
```java
public String getFilePath(PhotoSize photo) {
Objects.requireNonNull(photo);
if (photo.hasFilePath()) { // If the file_path is already present, we are done!
return photo.getFilePath();
} else { // If not, let find it
// We create a GetFile method and set the file_id from the photo
GetFile getFileMethod = new GetFile();
getFileMethod.setFileId(photo.getFileId());
try {
// We execute the method using AbsSender::getFile method.
File file = getFile(getFileMethod);
// We now have the file_path
return file.getFilePath();
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
return null; // Just in case
}
```
Now that we have the `file_path` we can download it:
```java
public java.io.File downloadPhotoByFilePath(String filePath) {
try {
// Download the file calling AbsSender::downloadFile method
return downloadFile(filePath);
} catch (TelegramApiException e) {
e.printStackTrace();
}
return null;
}
```
The returned `java.io.File` object will be your photo
## <a id="how_to_send_photos"></a>How to send photos? ##
There are several method to send a photo to an user using `sendPhoto` method: With a `file_id`, with an `url` or uploading the file. In this example, we assume that we already have the *chat_id* where we want to send the photo:
```java
public void sendImageFromUrl(String url, String chatId) {
// Create send method
SendPhoto sendPhotoRequest = new SendPhoto();
// Set destination chat id
sendPhotoRequest.setChatId(chatId);
// Set the photo url as a simple photo
sendPhotoRequest.setPhoto(url);
try {
// Execute the method
sendPhoto(sendPhotoRequest);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public void sendImageFromFileId(String fileId, String chatId) {
// Create send method
SendPhoto sendPhotoRequest = new SendPhoto();
// Set destination chat id
sendPhotoRequest.setChatId(chatId);
// Set the photo url as a simple photo
sendPhotoRequest.setPhoto(fileId);
try {
// Execute the method
sendPhoto(sendPhotoRequest);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public void sendImageUploadingAFile(String filePath, String chatId) {
// Create send method
SendPhoto sendPhotoRequest = new SendPhoto();
// Set destination chat id
sendPhotoRequest.setChatId(chatId);
// Set the photo file as a new photo (You can also use InputStream with a method overload)
sendPhotoRequest.setNewPhoto(new File(filePath));
try {
// Execute the method
sendPhoto(sendPhotoRequest);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
```
## <a id="how_to_use_custom_keyboards"></a>How to use custom keyboards? ##
Custom keyboards can be appended to messages using the `setReplyMarkup`. In this example, we will build a simple [ReplyKeyboardMarkup](https://core.telegram.org/bots/api#replykeyboardmarkup) with two rows and three buttons per row, but you can also use other types like [ReplyKeyboardHide](https://core.telegram.org/bots/api#replykeyboardhide), [ForceReply](https://core.telegram.org/bots/api#forcereply) or [InlineKeyboardMarkup](https://core.telegram.org/bots/api#inlinekeyboardmarkup):
```java
public void sendCustomKeyboard(String chatId) {
SendMessage message = new SendMessage();
message.setChatId(chatId);
message.setText("Custom message text");
// Create ReplyKeyboardMarkup object
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
// Create the keyboard (list of keyboard rows)
List<KeyboardRow> keyboard = new ArrayList<>();
// Create a keyboard row
KeyboardRow row = new KeyboardRow();
// Set each button, you can also use KeyboardButton objects if you need something else than text
row.add("Row 1 Button 1");
row.add("Row 1 Button 2");
row.add("Row 1 Button 3");
// Add the first row to the keyboard
keyboard.add(row);
// Create another keyboard row
row = new KeyboardRow();
// Set each button for the second line
row.add("Row 2 Button 1");
row.add("Row 2 Button 2");
row.add("Row 2 Button 3");
// Add the second row to the keyboard
keyboard.add(row);
// Set the keyboard to the markup
keyboardMarkup.setKeyboard(keyboard);
// Add it to the message
message.setReplyMarkup(keyboardMarkup);
try {
// Send the message
sendMessage(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
```
## <a id="how_to_host"></a>How can I run my bot? ##
You don't need to spend a lot of money into hosting your own telegram bot. Basically, there are two options around how to host:
1. Hosting on your own hardware. It can be a Mini-PC like a Raspberry Pi. The costs for the hardware (~35€) and annual costs for power (~7-8€) are low. Keep in mind that your internet connection might be limited and a Mini-Pc is not ideal for a large users base.
2. Run your bot in a Virtual Server/dedicated root server. There are many hosters out there that are providing cheap servers that fit your needs. The cheapest one should be openVZ-Containers or a KVM vServer. Example providers are [Hetzner](https://www.hetzner.de/ot/), [DigitalOcean](https://www.digitalocean.com/), (are providing systems that have a high availability but cost's a bit more) and [OVH](https://ovh.com)
## <a id="how_to_compile"></a>How can I compile my project? ##
This is just one way, how you can compile it (here with maven). The example below below is compiling the TelegramBotsExample repo.
[![asciicast](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj.png)](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj)

View File

@ -0,0 +1,174 @@
So, you just wanna program your own Telegram bot with TelegramBots? Let's see the fast version.
## Grab the library
First you need ot get the library and add it to your project. There are few possibilities for this:
1. If you use [Maven](https://maven.apache.org/), [Gradle](https://gradle.org/), etc; you should be able to import the dependency directly from [Maven Central Repository](http://mvnrepository.com/artifact/org.telegram/telegrambots). For example:
* With **Maven**:
```xml
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>2.4.1</version>
</dependency>
```
* With **Gradle**:
```groovy
compile group: 'org.telegram', name: 'telegrambots', version: '2.4.1'
```
2. Don't like **Maven Central Repository**? It can also be taken from [Jitpack](https://jitpack.io/#rubenlagus/TelegramBots).
3. Import the library *.jar* direclty to your project. You can find it [here](https://github.com/rubenlagus/TelegramBots/releases), don't forget to take last version, it usually is a good idea. Depending on the IDE you are using, the process to add a library is different, here is a video that may help with [Intellij](https://www.youtube.com/watch?v=NZaH4tjwMYg) or [Eclipse](https://www.youtube.com/watch?v=VWnfHkBgO1I)
## Build our first bot
Now that we have the library, we can start coding. There are few steps to follow, in this tutorial (for the sake of simplicity), we are going to build a [Long Polling Bot](http://en.wikipedia.org/wiki/Push_technology#Long_polling):
1. **Create your actual bot:**
The class must extends `TelegramLongPollingBot` and implement necessary methods:
```java
public class MyAmazingBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// TODO
}
@Override
public String getBotUsername() {
// TODO
return null;
}
@Override
public String getBotToken() {
// TODO
return null;
}
}
```
* `getBotUsermane()`: This method must always return your **Bot username**. May look like:
```java
@Override
public String getBotUsername() {
return "myamazingbot";
}
```
* `getBotToken()`: This method must always return your **Bot Token** (If you don't know it, you may want to talk with [@BotFather](https://telegram.me/BotFather)). May look like:
```java
@Override
public String getBotToken() {
return "123456789:qwertyuioplkjhgfdsazxcvbnm";
}
```
* `onUpdateReceived`: This method will be called when an [Update](https://core.telegram.org/bots/api#update) is received by your bot. In this example, this method will just read messages and echo the same text:
```java
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message has text
if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields
.setChatId(update.getMessage().getChatId())
.setText(update.getMessage().getText());
try {
sendMessage(message); // Call method to send the message
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
```
2. **Instantiate `TelegramBotsApi` and register our new bot:**
For this part, we need to actually perform 3 steps: _Initialize Api Context_, _Instantiate Telegram Api_ and _Register our Bot_. In this tutorial, we are going to make it in our `main` method:
```java
public class Main {
public static void main(String[] args) {
// TODO Initialize Api Context
// TODO Instantiate Telegram Bots API
// TODO Register our bot
}
}
```
* **Initialize Api Context**: This can be easily done calling the only method present in `ApiContextInitializer`:
```java
public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();
// TODO Instantiate Telegram Bots API
// TODO Register our bot
}
}
```
* **Instantiate Telegram Bots API**: Easy as well, just create a new instance. Remember that a single instance can handle different bots but each bot can run only once (Telegram doesn't support concurrent calls to `GetUpdates`):
```java
public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
// TODO Register our bot
}
}
```
* **Register our bot**: Now we need to register a new instance of our previously created bot class in the api:
```java
public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
try {
botsApi.registerBot(new MyAmazingBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
```
3. **Play with your bot:**
Done, now you just need to run this `main` method and your Bot should start working.

View File

@ -0,0 +1 @@
Welcome to the TelegramBots wiki. Use the sidebar on the right. If you're not sure what to look at, why not take a look at the [[Getting Started|Getting-Started]] guide?

View File

@ -0,0 +1,10 @@
### <a id="2.4.1"></a>To version 2.4.1 ###
1. Replace `BotOptions` by `DefaultBotOptions`.
2. At the beginning of your program (before creating your `TelegramBotsApi` instance, add the following line:
```java
ApiContextInitializer.init();
```
3. **Deprecated** (will be removed in next version):
* `org.telegram.telegrambots.bots.BotOptions`. Use `org.telegram.telegrambots.bots.DefaultBotOptions` instead.
* `getPersonal` from `AnswerInlineQuery`. Use `isPersonal` instead.
* `FILEBASEURL` from `File`. Use `getFileUrl` instead.

View File

@ -0,0 +1 @@
[Telegram Bots Library Wiki](https://github.com/rubenlagus/TelegramBots) for contributions, make a pull request again [Telegram.wiki module](https://github.com/rubenlagus/TelegramBots/tree/dev/TelegramBots.wiki)

View File

@ -0,0 +1,6 @@
* Users guide
* [[Getting Started]]
* [[Errors Handling]]
* [[FAQ]]
* [[Changelog]]
* [[How To Update]]

View File

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="20">
<linearGradient id="b" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<mask id="a">
<rect width="100" height="20" rx="3" fill="#fff"/>
</mask>
<g mask="url(#a)">
<path fill="#555" d="M0 0h34v20H0z"/>
<path fill="#54a9eb" d="M34 0h68v20H34z"/>
<path fill="url(#b)" d="M0 0h92v20H0z"/>
</g>
<g fill="#fff" text-anchor="middle"
font-family="HelveticaNeue-Light,Helvetica Neue Light, Helvetica Light,Helvetica,Arial,Verdana,sans-serif"
font-size="11" color="#fff" font-weight="bold">
<text x="16" y="15" fill="#010101" fill-opacity=".3">chat</text>
<text x="16" y="14">chat</text>
<text x="67" y="15" fill="#010101" fill-opacity=".3">on telegram</text>
<text x="67" y="14">on telegram</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1012 B

255
pom.xml
View File

@ -1,254 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>2.4.0</version>
<artifactId>Bots</artifactId>
<packaging>pom</packaging>
<version>2.4.1</version>
<name>Telegram Bots</name>
<url>https://github.com/rubenlagus/TelegramBots</url>
<description>Easy to use library to create Telegram Bots</description>
<issueManagement>
<url>https://github.com/rubenlagus/TelegramBots/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<scm>
<url>https://github.com/rubenlagus/TelegramBots</url>
<connection>scm:git:git://github.com/rubenlagus/TelegramBots.git</connection>
<developerConnection>scm:git:git@github.com:rubenlagus/TelegramBots.git</developerConnection>
</scm>
<developers>
<developer>
<email>rberlopez@gmail.com</email>
<name>Ruben Bermudez</name>
<url>https://github.com/rubenlagus</url>
<id>rubenlagus</id>
</developer>
</developers>
<modules>
<module>telegrambots</module>
<module>telegrambots-meta</module>
</modules>
<licenses>
<license>
<name>GNU General Public License (GPL)</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<jersey.version>2.23.2</jersey.version>
<jerseybundle.version>1.19.2</jerseybundle.version>
<httpcompontents.version>4.5.2</httpcompontents.version>
<json.version>20160810</json.version>
<jackson.version>2.7.4</jackson.version>
<commons.version>2.5</commons.version>
<maven.deploy.skip>true</maven.deploy.skip>
<bots.version>2.4.1</bots.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>${jerseybundle.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2-servlet</artifactId>
<version>${jerseybundle.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpcompontents.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpcompontents.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.version}</version>
</dependency>
</dependencies>
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>clean-project</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>true</createDependencyReducedPom>
<artifactSet>
<includes>
<include>org.apache.httpcomponents:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>org.apache.http</pattern>
<shadedPattern>embedded.org.apache.http</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
-->
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -1,14 +0,0 @@
package org.telegram.telegrambots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Constants needed for Telegram Bots API
* @date 20 of June of 2015
*/
public class Constants {
public static final String BASEURL = "https://api.telegram.org/bot";
public static final int GETUPDATESTIMEOUT = 50;
public static final String RESPONSEFIELDOK = "ok";
public static final String RESPONSEFIELDRESULT = "result";
}

View File

@ -1,183 +0,0 @@
package org.telegram.telegrambots;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.bots.BotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.bots.TelegramWebhookBot;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.updatesreceivers.BotSession;
import org.telegram.telegrambots.updatesreceivers.Webhook;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Bots manager
* @date 14 of January of 2016
*/
public class TelegramBotsApi {
private static final int SOCKET_TIMEOUT = 75 * 1000;
private static final String webhookUrlFormat = "{0}callback/";
private boolean useWebhook; ///< True to enable webhook usage
private Webhook webhook; ///< Webhook instance
private String extrenalUrl; ///< External url of the bots
private String pathToCertificate; ///< Path to public key certificate
/**
*
*/
public TelegramBotsApi() {
}
/**
*
* @param keyStore KeyStore for the server
* @param keyStorePassword Key store password for the server
* @param externalUrl External base url for the webhook
* @param internalUrl Internal base url for the webhook
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiRequestException {
if (externalUrl == null || externalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty");
}
if (internalUrl == null || internalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty");
}
this.useWebhook = true;
this.extrenalUrl = fixExternalUrl(externalUrl);
webhook = new Webhook(keyStore, keyStorePassword, internalUrl);
webhook.startServer();
}
/**
*
* @param keyStore KeyStore for the server
* @param keyStorePassword Key store password for the server
* @param externalUrl External base url for the webhook
* @param internalUrl Internal base url for the webhook
* @param pathToCertificate Full path until .pem public certificate keys
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiRequestException {
if (externalUrl == null || externalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty");
}
if (internalUrl == null || internalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty");
}
this.useWebhook = true;
this.extrenalUrl = fixExternalUrl(externalUrl);
this.pathToCertificate = pathToCertificate;
webhook = new Webhook(keyStore, keyStorePassword, internalUrl);
webhook.startServer();
}
/**
* Register a bot. The Bot Session is started immediately, and may be disconnected by calling close.
* @param bot the bot to register
*/
public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiRequestException {
setWebhook(bot.getBotToken(), null, bot.getOptions());
return new BotSession(bot.getBotToken(), bot, bot.getOptions());
}
/**
* Register a bot in the api that will receive updates using webhook method
* @param bot Bot to register
*/
public void registerBot(TelegramWebhookBot bot) throws TelegramApiRequestException {
if (useWebhook) {
webhook.registerWebhook(bot);
setWebhook(bot.getBotToken(), bot.getBotPath(), bot.getOptions());
}
}
private static String fixExternalUrl(String externalUrl) {
if (externalUrl != null && !externalUrl.endsWith("/")) {
externalUrl = externalUrl + "/";
}
return MessageFormat.format(webhookUrlFormat, externalUrl);
}
/**
* Set webhook or remove it if necessary
* @param webHookURL Webhook url or empty is removing it
* @param botToken Bot token
* @param publicCertificatePath Path to certificate public key
* @param options Bot options
* @throws TelegramApiRequestException If any error occurs setting the webhook
*/
private static void setWebhook(String webHookURL, String botToken,
String publicCertificatePath, BotOptions options) throws TelegramApiRequestException {
try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) {
String url = Constants.BASEURL + botToken + "/" + SetWebhook.PATH;
RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build())
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectTimeout(SOCKET_TIMEOUT)
.setConnectionRequestTimeout(SOCKET_TIMEOUT);
if (options.hasProxy()) {
configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort()));
}
HttpPost httppost = new HttpPost(url);
httppost.setConfig(configBuilder.build());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, webHookURL);
if (publicCertificatePath != null) {
File certificate = new File(publicCertificatePath);
if (certificate.exists()) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName());
}
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) {
throw new TelegramApiRequestException(webHookURL == null ? "Error removing old webhook" : "Error setting webhook", jsonObject);
}
}
} catch (JSONException e) {
throw new TelegramApiRequestException("Error deserializing setWebhook method response", e);
} catch (IOException e) {
throw new TelegramApiRequestException("Error executing setWebook method", e);
}
}
/**
* Set the webhook or remove it if necessary
* @param botToken Bot token
* @param urlPath Url for the webhook or null to remove it
* @param botOptions Bot Options
*/
private void setWebhook(String botToken, String urlPath, BotOptions botOptions) throws TelegramApiRequestException {
if (botToken == null) {
throw new TelegramApiRequestException("Parameter botToken can not be null");
}
String completeExternalUrl = urlPath == null ? "" : extrenalUrl + urlPath;
setWebhook(completeExternalUrl, botToken, pathToCertificate, botOptions);
}
}

View File

@ -1,14 +0,0 @@
package org.telegram.telegrambots.api.interfaces;
import com.fasterxml.jackson.databind.JsonSerializable;
import java.io.Serializable;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief An object of Telegram Bots Api
* @date 07 of September of 2015
*/
public interface IBotApiObject extends JsonSerializable, Serializable {
}

View File

@ -1,18 +0,0 @@
package org.telegram.telegrambots.api.interfaces;
import org.json.JSONObject;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Add conversion to JSON object
* @date 08 of September of 2015
*/
public interface IToJson {
/**
* Convert to json object
* @return JSONObject created in the conversion
*/
JSONObject toJson();
}

View File

@ -1,29 +0,0 @@
package org.telegram.telegrambots.api.methods;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Types of actions for SendChatAction method.
* @date 20 of June of 2016
*/
public enum ActionType {
TYPING("typing"),
RECORDVIDEO("record_video"),
RECORDAUDIO("record_audio"),
UPLOADPHOTO("upload_photo"),
UPLOADVIDEO("upload_video"),
UPLOADAUDIO("upload_audio"),
UPLOADDOCUMENT("upload_document"),
FINDLOCATION("find_location");
private String text;
ActionType(String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}

View File

@ -1,32 +0,0 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.databind.JsonSerializable;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IToJson;
import org.telegram.telegrambots.api.interfaces.Validable;
import java.io.Serializable;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief A method of Telegram Bots Api that is fully supported in json format
* @date 07 of September of 2015
*/
public abstract class BotApiMethod<T extends Serializable> implements JsonSerializable, IToJson, Validable {
protected static final String METHOD_FIELD = "method";
/**
* Getter for method path (that is the same as method name)
* @return Method path
*/
public abstract String getPath();
/**
* Deserialize a json answer to the response type to a method
* @param answer Json answer received
* @return Answer for the method
*/
public abstract T deserializeResponse(JSONObject answer);
}

View File

@ -1,59 +0,0 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief A simple method for testing your bot's auth token. Requires no parameters.
* Returns basic information about the bot in form of a User object
* @date 20 of June of 2015
*/
public class GetMe extends BotApiMethod<User> {
public static final String PATH = "getme";
@Override
public JSONObject toJson() {
return new JSONObject();
}
@Override
public String getPath() {
return PATH;
}
@Override
public User deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new User(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
}
return null;
}
@Override
public void validate() throws TelegramApiValidationException {
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

View File

@ -1,70 +0,0 @@
package org.telegram.telegrambots.api.methods.updates;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.WebhookInfo;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 2.4
* @brief Use this method to get current webhook status.
* Requires no parameters.
* On success, returns a WebhookInfo object.
* Will throw an error, if the bot is using getUpdates.
*
* @date 12 of August of 2016
*/
public class GetWebhookInfo extends BotApiMethod<WebhookInfo> {
public static final String PATH = "getwebhookinfo";
public GetWebhookInfo() {
}
@Override
public String toString() {
return "GetWebhookInfo{}";
}
@Override
public String getPath() {
return PATH;
}
@Override
public WebhookInfo deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new WebhookInfo(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
}
return null;
}
@Override
public void validate() throws TelegramApiValidationException {
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
return new JSONObject();
}
}

View File

@ -1,58 +0,0 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object contains information about one member of the chat.
* @date 20 of May of 2016
*/
public class ChatMember implements IBotApiObject {
private static final String USER_FIELD = "user";
private static final String STATUS_FIELD = "status";
private User user; ///< Information about the user
private String status; ///< The member's status in the chat. Can be creator, administrator, member, left or kicked
public ChatMember(JSONObject object) {
user = new User(object.getJSONObject(USER_FIELD));
status = object.getString(STATUS_FIELD);
}
public User getUser() {
return user;
}
public String getStatus() {
return status;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeObjectField(USER_FIELD, user);
gen.writeStringField(STATUS_FIELD, status);
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "ChatMember{" +
"user=" + user +
", status='" + status + '\'' +
'}';
}
}

View File

@ -1,67 +0,0 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a point on the map.
* @date 20 of June of 2015
*/
public class Location implements IBotApiObject {
private static final String LONGITUDE_FIELD = "longitude";
private static final String LATITUDE_FIELD = "latitude";
@JsonProperty(LONGITUDE_FIELD)
private Double longitude; ///< Longitude as defined by sender
@JsonProperty(LATITUDE_FIELD)
private Double latitude; ///< Latitude as defined by sender
public Location() {
super();
}
public Location(JSONObject jsonObject) {
super();
this.longitude = jsonObject.getDouble(LONGITUDE_FIELD);
this.latitude = jsonObject.getDouble(LATITUDE_FIELD);
}
public Double getLongitude() {
return longitude;
}
public Double getLatitude() {
return latitude;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(LONGITUDE_FIELD, longitude);
gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Location{" +
"longitude=" + longitude +
", latitude=" + latitude +
'}';
}
}

View File

@ -1,91 +0,0 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represent a user's profile pictures.
* @date 22 of June of 2015
*/
public class UserProfilePhotos implements IBotApiObject {
private static final String TOTALCOUNT_FIELD = "total_count";
private static final String PHOTOS_FIELD = "photos";
@JsonProperty(TOTALCOUNT_FIELD)
private Integer totalCount; ///< Total number of profile pictures the target user has
@JsonProperty(PHOTOS_FIELD)
private List<List<PhotoSize>> photos; ///< Requested profile pictures (in up to 4 sizes each)
public UserProfilePhotos() {
super();
}
public UserProfilePhotos(JSONObject jsonObject) {
super();
this.totalCount = jsonObject.getInt(TOTALCOUNT_FIELD);
if (totalCount > 0) {
this.photos = new ArrayList<>();
JSONArray photos = jsonObject.getJSONArray(PHOTOS_FIELD);
for (int i = 0; i < photos.length(); i++) {
JSONArray innerArray = photos.getJSONArray(i);
List<PhotoSize> innerPhotos = new ArrayList<>();
for (int j = 0; j < innerArray.length(); j++) {
innerPhotos.add(new PhotoSize(innerArray.getJSONObject(j)));
}
this.photos.add(innerPhotos);
}
}
}
public Integer getTotalCount() {
return totalCount;
}
public List<List<PhotoSize>> getPhotos() {
return photos;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(TOTALCOUNT_FIELD, totalCount);
if (totalCount > 0) {
gen.writeArrayFieldStart(PHOTOS_FIELD);
for (List<PhotoSize> photoSizeList : photos) {
gen.writeStartArray();
for (PhotoSize photoSize: photoSizeList) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
}
gen.writeEndArray();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "UserProfilePhotos{" +
"totalCount=" + totalCount +
", photos=" + photos +
'}';
}
}

View File

@ -1,67 +0,0 @@
/*
* This file is part of TelegramBots.
*
* TelegramBots is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TelegramBots is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TelegramBots. If not, see <http://www.gnu.org/licenses/>.
*/
package org.telegram.telegrambots.api.objects.games;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 2.4
* @brief A placeholder, currently holds no information. Use BotFather to set up your game.
* @date 16 of September of 2016
*/
public class CallbackGame implements IBotApiObject {
private final JSONObject content;
public CallbackGame(JSONObject object) {
super();
content = object;
}
public JSONObject getContent() {
return content;
}
public String getContentText() {
return content.toString();
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeObject(content);
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "CallbackGame{" +
"content=" + content +
'}';
}
}

View File

@ -1,35 +0,0 @@
package org.telegram.telegrambots.bots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Configurations for the Bot
* @date 21 of July of 2016
*/
public class BotOptions {
private String proxyHost;
private int proxyPort;
public BotOptions() {
}
public String getProxyHost() {
return proxyHost;
}
public int getProxyPort() {
return proxyPort;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public boolean hasProxy() {
return proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0;
}
}

View File

@ -1,18 +0,0 @@
package org.telegram.telegrambots.bots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Base abstract class for a bot that will get updates using
* <a href="https://core.telegram.org/bots/api#getupdates">long-polling</a> method
* @date 14 of January of 2016
*/
public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot {
public TelegramLongPollingBot() {
this(new BotOptions());
}
public TelegramLongPollingBot(BotOptions options) {
super(options);
}
}

View File

@ -1,18 +0,0 @@
package org.telegram.telegrambots.bots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Base abstract class for a bot that will receive updates using a
* <a href="https://core.telegram.org/bots/api#setwebhook">webhook</a>
* @date 14 of January of 2016
*/
public abstract class TelegramWebhookBot extends AbsSender implements ITelegramWebhookBot {
public TelegramWebhookBot() {
this(new BotOptions());
}
public TelegramWebhookBot(BotOptions options) {
super(options);
}
}

197
telegrambots-meta/pom.xml Normal file
View File

@ -0,0 +1,197 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-meta</artifactId>
<version>2.4.1</version>
<packaging>jar</packaging>
<name>Telegram Bots Meta</name>
<url>https://github.com/rubenlagus/TelegramBots</url>
<description>Easy to use library to create Telegram Bots</description>
<issueManagement>
<url>https://github.com/rubenlagus/TelegramBots/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<scm>
<url>https://github.com/rubenlagus/TelegramBots</url>
<connection>scm:git:git://github.com/rubenlagus/TelegramBots.git</connection>
<developerConnection>scm:git:git@github.com:rubenlagus/TelegramBots.git</developerConnection>
</scm>
<developers>
<developer>
<email>rberlopez@gmail.com</email>
<name>Ruben Bermudez</name>
<url>https://github.com/rubenlagus</url>
<id>rubenlagus</id>
</developer>
</developers>
<licenses>
<license>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<guice.version>4.1.0</guice.version>
<jackson.version>2.8.5</jackson.version>
<json.version>20160810</json.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>clean-project</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,14 @@
package org.telegram.telegrambots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Constants needed for Telegram Bots API
* @date 20 of June of 2015
*/
public class ApiConstants {
public static final String BASE_URL = "https://api.telegram.org/bot";
public static final int GETUPDATES_TIMEOUT = 50;
public static final String RESPONSE_FIELD_OK = "ok";
public static final String RESPONSE_FIELD_RESULT = "result";
}

View File

@ -0,0 +1,64 @@
package org.telegram.telegrambots;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import org.telegram.telegrambots.logging.BotLogger;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
/**
* @author Ruben Bermudez
* @version 1.0
*/
public class ApiContext {
private static final Object lock = new Object();
private static Injector INJECTOR;
private static Map<Class, Class> bindings = new HashMap<>();
private static Map<Class, Class> singletonBindings = new HashMap<>();
public static <T> T getInstance(Class<T> type) {
return getInjector().getInstance(type);
}
public static <T, S extends T> void register(Class<T> type, Class<S> implementation) {
if (bindings.containsKey(type)) {
BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
}
bindings.put(type, implementation);
}
public static <T, S extends T> void registerSingleton(Class<T> type, Class<S> implementation) {
if (singletonBindings.containsKey(type)) {
BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
}
singletonBindings.put(type, implementation);
}
private static Injector getInjector() {
if (INJECTOR == null) {
synchronized (lock) {
if (INJECTOR == null) {
INJECTOR = Guice.createInjector(new ApiModule());
}
}
}
return INJECTOR;
}
private static class ApiModule extends AbstractModule {
@Override
protected void configure() {
for (Map.Entry<Class, Class> binding : bindings.entrySet()) {
bind(binding.getKey()).to(binding.getValue());
}
for (Map.Entry<Class, Class> binding : singletonBindings.entrySet()) {
bind(binding.getKey()).to(binding.getValue()).in(Singleton.class);
}
}
}
}

View File

@ -0,0 +1,108 @@
package org.telegram.telegrambots;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.generics.BotSession;
import org.telegram.telegrambots.generics.LongPollingBot;
import org.telegram.telegrambots.generics.Webhook;
import org.telegram.telegrambots.generics.WebhookBot;
import java.text.MessageFormat;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Bots manager
* @date 14 of January of 2016
*/
public class TelegramBotsApi {
private static final String webhookUrlFormat = "{0}callback/";
private boolean useWebhook; ///< True to enable webhook usage
private Webhook webhook; ///< Webhook instance
private String extrenalUrl; ///< External url of the bots
private String pathToCertificate; ///< Path to public key certificate
/**
*
*/
public TelegramBotsApi() {
}
/**
*
* @param keyStore KeyStore for the server
* @param keyStorePassword Key store password for the server
* @param externalUrl External base url for the webhook
* @param internalUrl Internal base url for the webhook
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiRequestException {
if (externalUrl == null || externalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty");
}
if (internalUrl == null || internalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty");
}
this.useWebhook = true;
this.extrenalUrl = fixExternalUrl(externalUrl);
webhook = ApiContext.getInstance(Webhook.class);
webhook.setInternalUrl(internalUrl);
webhook.setKeyStore(keyStore, keyStorePassword);
webhook.startServer();
}
/**
*
* @param keyStore KeyStore for the server
* @param keyStorePassword Key store password for the server
* @param externalUrl External base url for the webhook
* @param internalUrl Internal base url for the webhook
* @param pathToCertificate Full path until .pem public certificate keys
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiRequestException {
if (externalUrl == null || externalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty");
}
if (internalUrl == null || internalUrl.isEmpty()) {
throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty");
}
this.useWebhook = true;
this.extrenalUrl = fixExternalUrl(externalUrl);
this.pathToCertificate = pathToCertificate;
webhook = ApiContext.getInstance(Webhook.class);
webhook.setInternalUrl(internalUrl);
webhook.setKeyStore(keyStore, keyStorePassword);
webhook.startServer();
}
/**
* Register a bot. The Bot Session is started immediately, and may be disconnected by calling close.
* @param bot the bot to register
*/
public BotSession registerBot(LongPollingBot bot) throws TelegramApiRequestException {
bot.clearWebhook();
BotSession session = ApiContext.getInstance(BotSession.class);
session.setToken(bot.getBotToken());
session.setOptions(bot.getOptions());
session.setCallback(bot);
session.start();
return session;
}
/**
* Register a bot in the api that will receive updates using webhook method
* @param bot Bot to register
*/
public void registerBot(WebhookBot bot) throws TelegramApiRequestException {
if (useWebhook) {
webhook.registerWebhook(bot);
bot.setWebhook(extrenalUrl + bot.getBotPath(), pathToCertificate);
}
}
private static String fixExternalUrl(String externalUrl) {
if (externalUrl != null && !externalUrl.endsWith("/")) {
externalUrl = externalUrl + "/";
}
return MessageFormat.format(webhookUrlFormat, externalUrl);
}
}

View File

@ -0,0 +1,16 @@
package org.telegram.telegrambots.api.interfaces;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
/**
* @author Ruben Bermudez
* @version 1.0
* An object from the Bots API received from Telegram Servers
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public interface BotApiObject extends Serializable {
}

View File

@ -0,0 +1,18 @@
package org.telegram.telegrambots.api.interfaces;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.io.Serializable;
/**
* @author Ruben Bermudez
* @version 1.0
* An object used in the Bots API to answer updates
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public interface InputBotApiObject extends Serializable {
}

View File

@ -0,0 +1,55 @@
package org.telegram.telegrambots.api.methods;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Types of actions for SendChatAction method.
* @date 20 of June of 2016
*/
public enum ActionType {
TYPING("typing"),
RECORDVIDEO("record_video"),
RECORDAUDIO("record_audio"),
UPLOADPHOTO("upload_photo"),
UPLOADVIDEO("upload_video"),
UPLOADAUDIO("upload_audio"),
UPLOADDOCUMENT("upload_document"),
FINDLOCATION("find_location");
private String text;
ActionType(String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
public static ActionType get(String text) {
if (text == null) {
return null;
}
switch (text) {
case "typing":
return TYPING;
case "record_video":
return RECORDVIDEO;
case "record_audio":
return RECORDAUDIO;
case "upload_photo":
return UPLOADPHOTO;
case "upload_video":
return UPLOADVIDEO;
case "upload_audio":
return UPLOADAUDIO;
case "upload_document":
return UPLOADDOCUMENT;
case "find_location":
return FINDLOCATION;
default:
return null;
}
}
}

View File

@ -1,12 +1,10 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
@ -37,13 +35,13 @@ public class AnswerCallbackQuery extends BotApiMethod<Boolean> {
private String text; ///< Optional Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters
@JsonProperty(SHOWALERT_FIELD)
private Boolean showAlert; ///< Optional. If true, an alert will be shown by the client instead of a notificaiton at the top of the chat screen. Defaults to false.
@JsonProperty(URL_FIELD)
/**
* Optional. URL that will be opened by the user's client.
* If you have created a Game and accepted the conditions via @Botfather,
* specify the URL that opens your game. Otherwise you may use links
* InlineQueryResultGamelike telegram.me/your_bot?start=XXXX that open your bot with a parameter.
*/
@JsonProperty(URL_FIELD)
private String url;
public AnswerCallbackQuery() {
@ -54,8 +52,9 @@ public class AnswerCallbackQuery extends BotApiMethod<Boolean> {
return this.callbackQueryId;
}
public void setCallbackQueryId(String callbackQueryId) {
public AnswerCallbackQuery setCallbackQueryId(String callbackQueryId) {
this.callbackQueryId = callbackQueryId;
return this;
}
public String getText() {
@ -86,32 +85,23 @@ public class AnswerCallbackQuery extends BotApiMethod<Boolean> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CALLBACKQUERYID_FIELD, callbackQueryId);
if (text != null) {
jsonObject.put(TEXT_FIELD, text);
}
if (showAlert != null) {
jsonObject.put(SHOWALERT_FIELD, showAlert);
}
if (url != null) {
jsonObject.put(URL_FIELD, url);
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getBoolean(Constants.RESPONSEFIELDRESULT);
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error answering callback query", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -121,29 +111,6 @@ public class AnswerCallbackQuery extends BotApiMethod<Boolean> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CALLBACKQUERYID_FIELD, callbackQueryId);
if (text != null) {
gen.writeStringField(TEXT_FIELD, text);
}
if (showAlert != null) {
gen.writeBooleanField(SHOWALERT_FIELD, showAlert);
}
if (url != null) {
gen.writeStringField(URL_FIELD, url);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "AnswerCallbackQuery{" +

View File

@ -1,23 +1,22 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.objects.inlinequery.result.InlineQueryResult;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Use this method to send answers to an inline query. On success, True is returned.
* @date 01 of January of 2016
* Use this method to send answers to an inline query. On success, True is returned.
*/
public class AnswerInlineQuery extends BotApiMethod<Boolean> {
public static final String PATH = "answerInlineQuery";
@ -29,12 +28,20 @@ public class AnswerInlineQuery extends BotApiMethod<Boolean> {
private static final String NEXTOFFSET_FIELD = "next_offset";
private static final String SWITCH_PM_TEXT_FIELD = "switch_pm_text";
private static final String SWITCH_PM_PARAMETER_FIELD = "switch_pm_parameter";
@JsonProperty(INLINEQUERYID_FIELD)
private String inlineQueryId; ///< Unique identifier for answered query
@JsonProperty(RESULTS_FIELD)
private List<InlineQueryResult> results; ///< A JSON-serialized array of results for the inline query
@JsonProperty(CACHETIME_FIELD)
private Integer cacheTime; ///< Optional The maximum amount of time the result of the inline query may be cached on the server
@JsonProperty(ISPERSONAL_FIELD)
private Boolean isPersonal; ///< Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query
@JsonProperty(NEXTOFFSET_FIELD)
private String nextOffset; ///< Optional. Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you dont support pagination. Offset length cant exceed 64 bytes.
@JsonProperty(SWITCH_PM_TEXT_FIELD)
private String switchPmText; ///< Optional. If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter
@JsonProperty(SWITCH_PM_PARAMETER_FIELD)
private String switchPmParameter; ///< Optional. Parameter for the start message sent to the bot when user presses the switch button
public AnswerInlineQuery() {
@ -59,6 +66,12 @@ public class AnswerInlineQuery extends BotApiMethod<Boolean> {
return this;
}
@JsonIgnore
public AnswerInlineQuery setResults(InlineQueryResult... results) {
this.results = Arrays.asList(results);
return this;
}
public Integer getCacheTime() {
return cacheTime;
}
@ -68,10 +81,16 @@ public class AnswerInlineQuery extends BotApiMethod<Boolean> {
return this;
}
@Deprecated
@JsonIgnore
public Boolean getPersonal() {
return isPersonal;
}
public Boolean isPersonal() {
return isPersonal;
}
public AnswerInlineQuery setPersonal(Boolean personal) {
isPersonal = personal;
return this;
@ -118,77 +137,23 @@ public class AnswerInlineQuery extends BotApiMethod<Boolean> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(INLINEQUERYID_FIELD, inlineQueryId);
JSONArray JSONResults = new JSONArray();
for (InlineQueryResult result: results) {
JSONResults.put(result.toJson());
}
jsonObject.put(RESULTS_FIELD, JSONResults);
if (cacheTime != null) {
jsonObject.put(CACHETIME_FIELD, cacheTime);
}
if (isPersonal != null) {
jsonObject.put(ISPERSONAL_FIELD, isPersonal);
}
if (nextOffset != null) {
jsonObject.put(NEXTOFFSET_FIELD, nextOffset);
}
if (switchPmText != null) {
jsonObject.put(SWITCH_PM_TEXT_FIELD, switchPmText);
}
if (switchPmParameter != null) {
jsonObject.put(SWITCH_PM_PARAMETER_FIELD, switchPmParameter);
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getBoolean(Constants.RESPONSEFIELDRESULT);
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error answering inline query", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeArrayFieldStart(RESULTS_FIELD);
for (InlineQueryResult result: results) {
gen.writeObject(result);
}
gen.writeEndArray();
if (cacheTime != null) {
gen.writeNumberField(CACHETIME_FIELD, cacheTime);
}
if (isPersonal != null) {
gen.writeBooleanField(ISPERSONAL_FIELD, isPersonal);
}
if (nextOffset != null) {
gen.writeStringField(NEXTOFFSET_FIELD, nextOffset);
}
if (switchPmText != null) {
gen.writeStringField(SWITCH_PM_TEXT_FIELD, switchPmText);
}
if (switchPmParameter != null) {
gen.writeStringField(SWITCH_PM_PARAMETER_FIELD, switchPmParameter);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -0,0 +1,26 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
/**
* @author Ruben Bermudez
* @version 1.0
*
* A method of Telegram Bots Api that is fully supported in json format
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public abstract class BotApiMethod<T extends Serializable> extends PartialBotApiMethod<T> {
protected static final String METHOD_FIELD = "method";
/**
* Getter for method path (that is the same as method name)
* @return Method path
*/
@JsonProperty(METHOD_FIELD)
public abstract String getMethod();
}

View File

@ -1,15 +1,15 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -24,8 +24,12 @@ public class ForwardMessage extends BotApiMethod<Message> {
private static final String FROMCHATID_FIELD = "from_chat_id";
private static final String MESSAGEID_FIELD = "message_id";
private static final String DISABLENOTIFICATION_FIELD = "disable_notification";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels)
@JsonProperty(FROMCHATID_FIELD)
private String fromChatId; ///< Unique identifier for the chat where the original message was sent User or GroupChat id
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId; ///< Unique message identifier
/**
* Optional. Sends the message silently.
@ -33,6 +37,7 @@ public class ForwardMessage extends BotApiMethod<Message> {
* Android users will receive a notification with no sound.
* Other apps coming soon
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
public ForwardMessage() {
@ -48,6 +53,12 @@ public class ForwardMessage extends BotApiMethod<Message> {
return this;
}
public ForwardMessage setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getFromChatId() {
return fromChatId;
}
@ -94,47 +105,23 @@ public class ForwardMessage extends BotApiMethod<Message> {
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(FROMCHATID_FIELD, fromChatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
if (disableNotification != null) {
gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(FROMCHATID_FIELD, fromChatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
if (disableNotification != null) {
jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification);
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error forwarding message", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override

View File

@ -1,12 +1,11 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.objects.File;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
@ -27,6 +26,8 @@ public class GetFile extends BotApiMethod<File> {
public static final String PATH = "getFile";
private static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< File identifier to get info about
public GetFile() {
@ -50,37 +51,23 @@ public class GetFile extends BotApiMethod<File> {
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FILEID_FIELD, fileId);
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public File deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new File(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public File deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<File> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<File>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting file", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override

View File

@ -0,0 +1,50 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief A simple method for testing your bot's auth token. Requires no parameters.
* Returns basic information about the bot in form of a User object
* @date 20 of June of 2015
*/
public class GetMe extends BotApiMethod<User> {
public static final String PATH = "getme";
public GetMe() {
super();
}
@Override
public String getMethod() {
return PATH;
}
@Override
public User deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<User> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<User>>() {
});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting me", result);
}
} catch (IOException e2) {
throw new TelegramApiRequestException("Unable to deserialize response", e2);
}
}
@Override
public void validate() throws TelegramApiValidationException {
}
}

View File

@ -1,12 +1,11 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.objects.UserProfilePhotos;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
@ -23,21 +22,24 @@ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
private static final String USERID_FIELD = "user_id";
private static final String OFFSET_FIELD = "offset";
private static final String LIMIT_FIELD = "limit";
@JsonProperty(USERID_FIELD)
private Integer userId; ///< Unique identifier of the target user
/**
* Sequential number of the first photo to be returned. By default, all photos are returned.
*/
@JsonProperty(OFFSET_FIELD)
private Integer offset;
/**
* Optional. Limits the number of photos to be retrieved. Values between 1100 are accepted. Defaults to 100.
*/
@JsonProperty(LIMIT_FIELD)
private Integer limit;
public GetUserProfilePhotos() {
super();
}
public Integer getUserId() {
return userId;
}
@ -66,27 +68,23 @@ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(USERID_FIELD, userId);
jsonObject.put(OFFSET_FIELD, offset);
if (limit != null) {
jsonObject.put(LIMIT_FIELD, limit);
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public UserProfilePhotos deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new UserProfilePhotos(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public UserProfilePhotos deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<UserProfilePhotos> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<UserProfilePhotos>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting user profile photos", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -99,24 +97,6 @@ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeNumberField(USERID_FIELD, userId);
gen.writeNumberField(OFFSET_FIELD, offset);
if (limit != null) {
gen.writeNumberField(LIMIT_FIELD, limit);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "GetUserProfilePhotos{" +

View File

@ -0,0 +1,26 @@
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.telegram.telegrambots.api.interfaces.Validable;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import java.io.Serializable;
/**
* @author Ruben Bermudez
* @version 1.0
* Api method that can't be use completely as Json
*/
public abstract class PartialBotApiMethod<T extends Serializable> implements Validable {
@JsonIgnore
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* Deserialize a json answer to the response type to a method
* @param answer Json answer received
* @return Answer for the method
*/
public abstract T deserializeResponse(String answer) throws TelegramApiRequestException;
}

View File

@ -16,19 +16,18 @@
*/
package org.telegram.telegrambots.api.methods.games;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.games.GameHighScore;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -52,12 +51,17 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
private static final String INLINE_MESSAGE_ID_FIELD = "inline_message_id";
private static final String USER_ID_FIELD = "user_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Optional Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername)
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId; ///< Optional Required if inline_message_id is not specified. Unique identifier of the sent message
@JsonProperty(INLINE_MESSAGE_ID_FIELD)
private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message
@JsonProperty(USER_ID_FIELD)
private Integer userId; ///<Target user id
public GetGameHighScores() {
super();
}
public String getChatId() {
@ -81,6 +85,12 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
return this;
}
public GetGameHighScores setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public GetGameHighScores setMessageId(Integer messageId) {
this.messageId = messageId;
return this;
@ -97,21 +107,23 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public ArrayList<GameHighScore> deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
JSONArray highScores = answer.getJSONArray(Constants.RESPONSEFIELDRESULT);
ArrayList<GameHighScore> scores = new ArrayList<>();
for (int i = 0; i < highScores.length(); i++) {
scores.add(new GameHighScore(highScores.getJSONObject(i)));
public ArrayList<GameHighScore> deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<ArrayList<GameHighScore>> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<ArrayList<GameHighScore>>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting game high scores", result);
}
return scores;
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -136,41 +148,6 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
if (chatId != null) {
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
}
if (inlineMessageId != null) {
gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
gen.writeNumberField(USER_ID_FIELD, userId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (chatId != null) {
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
}
if (inlineMessageId != null) {
jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
jsonObject.put(USER_ID_FIELD, userId);
return jsonObject;
}
@Override
public String toString() {
return "GetGameHighScores{" +

View File

@ -17,18 +17,18 @@
package org.telegram.telegrambots.api.methods.games;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -50,14 +50,21 @@ public class SetGameScore extends BotApiMethod<Serializable> {
private static final String INLINE_MESSAGE_ID_FIELD = "inline_message_id";
private static final String EDIT_MESSAGE_FIELD = "edit_message";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Optional Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername)
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId; ///< Optional Required if inline_message_id is not specified. Unique identifier of the sent message
@JsonProperty(INLINE_MESSAGE_ID_FIELD)
private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message
@JsonProperty(EDIT_MESSAGE_FIELD)
private Boolean editMessage; ///< Optional Pass True, if the message should be edited to include the current scoreboard
@JsonProperty(USER_ID_FIELD)
private Integer userId; ///< User identifier
@JsonProperty(SCORE_FIELD)
private Integer score; ///< New score, must be positive
public SetGameScore() {
super();
}
public String getChatId() {
@ -89,6 +96,12 @@ public class SetGameScore extends BotApiMethod<Serializable> {
return this;
}
public SetGameScore setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public SetGameScore setMessageId(Integer messageId) {
this.messageId = messageId;
return this;
@ -115,22 +128,34 @@ public class SetGameScore extends BotApiMethod<Serializable> {
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Serializable deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
Object result = answer.get(Constants.RESPONSEFIELDRESULT);
if (result instanceof Boolean) {
return (Boolean) result;
public Serializable deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error setting game score", result);
}
if (result instanceof JSONObject) {
return new Message((JSONObject) result);
} catch (IOException e) {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>() {
});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error setting game score", result);
}
} catch (IOException e2) {
throw new TelegramApiRequestException("Unable to deserialize response", e2);
}
}
return null;
}
@Override
@ -158,49 +183,6 @@ public class SetGameScore extends BotApiMethod<Serializable> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
if (chatId != null) {
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
}
if (inlineMessageId != null) {
gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (editMessage != null) {
gen.writeBooleanField(EDIT_MESSAGE_FIELD, editMessage);
}
gen.writeNumberField(USER_ID_FIELD, userId);
gen.writeNumberField(SCORE_FIELD, score);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (chatId != null) {
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
}
if (inlineMessageId != null) {
jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (editMessage != null) {
jsonObject.put(EDIT_MESSAGE_FIELD, editMessage);
}
jsonObject.put(USER_ID_FIELD, userId);
jsonObject.put(SCORE_FIELD, score);
return jsonObject;
}
@Override
public String toString() {
return "SetGameScore{" +

View File

@ -1,16 +1,16 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Chat;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -22,6 +22,8 @@ public class GetChat extends BotApiMethod<Chat> {
public static final String PATH = "getChat";
private static final String CHATID_FIELD = "chat_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public GetChat() {
@ -37,24 +39,30 @@ public class GetChat extends BotApiMethod<Chat> {
return this;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
return jsonObject;
public GetChat setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Chat deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Chat(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Chat deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Chat> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Chat>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting chat", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -64,20 +72,6 @@ public class GetChat extends BotApiMethod<Chat> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "GetChat{" +

View File

@ -1,18 +1,17 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.ChatMember;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -28,6 +27,8 @@ public class GetChatAdministrators extends BotApiMethod<ArrayList<ChatMember>> {
public static final String PATH = "getChatAdministrators";
private static final String CHATID_FIELD = "chat_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public GetChatAdministrators() {
@ -43,29 +44,30 @@ public class GetChatAdministrators extends BotApiMethod<ArrayList<ChatMember>> {
return this;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
return jsonObject;
public GetChatAdministrators setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public ArrayList<ChatMember> deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
JSONArray admins = answer.getJSONArray(Constants.RESPONSEFIELDRESULT);
ArrayList<ChatMember> members = new ArrayList<>();
for (int i = 0; i < admins.length(); i++) {
members.add(new ChatMember(admins.getJSONObject(i)));
public ArrayList<ChatMember> deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<ArrayList<ChatMember>> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<ArrayList<ChatMember>>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting chat administrators", result);
}
return members;
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -75,20 +77,6 @@ public class GetChatAdministrators extends BotApiMethod<ArrayList<ChatMember>> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "GetChatAdministrators{" +

View File

@ -1,16 +1,16 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.ChatMember;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -24,7 +24,10 @@ public class GetChatMember extends BotApiMethod<ChatMember> {
private static final String CHATID_FIELD = "chat_id";
private static final String USERID_FIELD = "user_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(USERID_FIELD)
private Integer userId; ///< Unique identifier of the target user
public GetChatMember() {
@ -40,6 +43,12 @@ public class GetChatMember extends BotApiMethod<ChatMember> {
return this;
}
public GetChatMember setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getUserId() {
return userId;
}
@ -50,24 +59,23 @@ public class GetChatMember extends BotApiMethod<ChatMember> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(USERID_FIELD, userId);
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public ChatMember deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new ChatMember(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public ChatMember deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<ChatMember> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<ChatMember>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting chat member", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -80,21 +88,6 @@ public class GetChatMember extends BotApiMethod<ChatMember> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(USERID_FIELD, userId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "GetChatMember{" +

View File

@ -1,15 +1,15 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -21,6 +21,8 @@ public class GetChatMemberCount extends BotApiMethod<Integer> {
public static final String PATH = "getChatMembersCount";
private static final String CHATID_FIELD = "chat_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public GetChatMemberCount() {
@ -36,24 +38,30 @@ public class GetChatMemberCount extends BotApiMethod<Integer> {
return this;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
return jsonObject;
public GetChatMemberCount setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Integer deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getInt(Constants.RESPONSEFIELDRESULT);
public Integer deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Integer> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Integer>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting chat member count", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -63,20 +71,6 @@ public class GetChatMemberCount extends BotApiMethod<Integer> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "GetChatMemberCount{" +

View File

@ -1,15 +1,15 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -28,7 +28,10 @@ public class KickChatMember extends BotApiMethod<Boolean> {
private static final String CHATID_FIELD = "chat_id";
private static final String USER_ID_FIELD = "user_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(USER_ID_FIELD)
private Integer userId; ///< Unique identifier of the target user
public KickChatMember() {
@ -44,6 +47,12 @@ public class KickChatMember extends BotApiMethod<Boolean> {
return this;
}
public KickChatMember setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getUserId() {
return userId;
}
@ -54,24 +63,23 @@ public class KickChatMember extends BotApiMethod<Boolean> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(USER_ID_FIELD, userId);
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getBoolean(Constants.RESPONSEFIELDRESULT);
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error kicking chat member", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -84,21 +92,6 @@ public class KickChatMember extends BotApiMethod<Boolean> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(USER_ID_FIELD, userId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "KickChatMember{" +

View File

@ -1,15 +1,15 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -21,6 +21,8 @@ public class LeaveChat extends BotApiMethod<Boolean> {
public static final String PATH = "leaveChat";
private static final String CHATID_FIELD = "chat_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
public LeaveChat() {
@ -36,24 +38,30 @@ public class LeaveChat extends BotApiMethod<Boolean> {
return this;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
return jsonObject;
public LeaveChat setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getBoolean(Constants.RESPONSEFIELDRESULT);
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error leaving chat", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -63,20 +71,6 @@ public class LeaveChat extends BotApiMethod<Boolean> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "LeaveChat{" +

View File

@ -1,15 +1,15 @@
package org.telegram.telegrambots.api.methods.groupadministration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -24,7 +24,10 @@ public class UnbanChatMember extends BotApiMethod<Boolean> {
private static final String CHATID_FIELD = "chat_id";
private static final String USER_ID_FIELD = "user_id";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(USER_ID_FIELD)
private Integer userId; ///< Unique identifier of the target user
public UnbanChatMember() {
@ -40,6 +43,12 @@ public class UnbanChatMember extends BotApiMethod<Boolean> {
return this;
}
public UnbanChatMember setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getUserId() {
return userId;
}
@ -50,24 +59,23 @@ public class UnbanChatMember extends BotApiMethod<Boolean> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(USER_ID_FIELD, userId);
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getBoolean(Constants.RESPONSEFIELDRESULT);
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error unbanning chat member", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -80,21 +88,6 @@ public class UnbanChatMember extends BotApiMethod<Boolean> {
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(USER_ID_FIELD, userId);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "UnbanChatMember{" +

View File

@ -1,8 +1,16 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@ -16,7 +24,7 @@ import java.util.Objects;
* @note For sending voice notes, use sendVoice method instead.
* @date 16 of July of 2015
*/
public class SendAudio {
public class SendAudio extends PartialBotApiMethod<Message> {
public static final String PATH = "sendaudio";
public static final String DURATION_FIELD = "duration";
@ -70,6 +78,12 @@ public class SendAudio {
return this;
}
public SendAudio setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getAudio() {
return audio;
}
@ -92,7 +106,6 @@ public class SendAudio {
* @param file New audio file
*/
public SendAudio setNewAudio(File file) {
this.audio = file.getName();
this.isNewAudio = true;
this.newAudioFile = file;
return this;
@ -182,6 +195,43 @@ public class SendAudio {
return this;
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending audio", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId == null) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (isNewAudio) {
if (newAudioFile == null && newAudioStream == null) {
throw new TelegramApiValidationException("Audio can't be empty", this);
}
if (newAudioStream != null && (audioName == null || audioName.isEmpty())) {
throw new TelegramApiValidationException("Audio name can't be empty", this);
}
} else if (audio == null) {
throw new TelegramApiValidationException("Audio can't be empty", this);
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "SendAudio{" +

View File

@ -1,16 +1,17 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.ActionType;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -26,6 +27,8 @@ public class SendChatAction extends BotApiMethod<Boolean> {
public static final String CHATID_FIELD = "chat_id";
public static final String ACTION_FIELD = "action";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
/**
* Type of action to broadcast. Choose one, depending on what the user is about to receive:
@ -33,32 +36,57 @@ public class SendChatAction extends BotApiMethod<Boolean> {
* videos 'record_audio' or 'upload_audio' for audio files 'upload_document' for general files,
* 'find_location' for location data.
*/
private ActionType action;
@JsonProperty(ACTION_FIELD)
private String action;
public SendChatAction() {
super();
}
public String getChatId() {
return chatId;
}
@JsonIgnore
public ActionType getAction() {
return ActionType.get(action);
}
public SendChatAction setChatId(String chatId) {
this.chatId = chatId;
return this;
}
public void setAction(ActionType action) {
this.action = action;
public SendChatAction setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
@JsonIgnore
public SendChatAction setAction(ActionType action) {
this.action = action.toString();
return this;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Boolean deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return answer.getBoolean(Constants.RESPONSEFIELDRESULT);
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Boolean>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending chat action", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -71,27 +99,6 @@ public class SendChatAction extends BotApiMethod<Boolean> {
}
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(ACTION_FIELD, action);
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(ACTION_FIELD, action.toString());
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "SendChatAction{" +

View File

@ -1,17 +1,17 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -30,18 +30,30 @@ public class SendContact extends BotApiMethod<Message> {
private static final String DISABLENOTIFICATION_FIELD = "disable_notification";
private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private static final String REPLYMARKUP_FIELD = "reply_markup";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(PHONE_NUMBER_FIELD)
private String phoneNumber; ///< User's phone number
@JsonProperty(FIRST_NAME_FIELD)
private String firstName; ///< User's first name
@JsonProperty(LAST_NAME_FIELD)
private String lastName; ///< Optional. User's last name
/**
* Optional. Sends the message silently. iOS users will not receive a notification, Android
* users will receive a notification with no sound. Other apps coming soon
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
@JsonProperty(REPLYTOMESSAGEID_FIELD)
private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message
@JsonProperty(REPLYMARKUP_FIELD)
private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public SendContact() {
super();
}
public String getChatId() {
return chatId;
}
@ -51,6 +63,12 @@ public class SendContact extends BotApiMethod<Message> {
return this;
}
public SendContact setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getReplyToMessageId() {
return replyToMessageId;
}
@ -111,16 +129,23 @@ public class SendContact extends BotApiMethod<Message> {
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending contact", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -134,57 +159,9 @@ public class SendContact extends BotApiMethod<Message> {
if (firstName == null) {
throw new TelegramApiValidationException("FirstName parameter can't be empty", this);
}
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(PHONE_NUMBER_FIELD, phoneNumber);
jsonObject.put(FIRST_NAME_FIELD, firstName);
if (lastName != null) {
jsonObject.put(LAST_NAME_FIELD, lastName);
}
if (disableNotification != null) {
jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
replyMarkup.validate();
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(PHONE_NUMBER_FIELD, phoneNumber);
gen.writeStringField(FIRST_NAME_FIELD, firstName);
if (lastName != null) {
gen.writeStringField(LAST_NAME_FIELD, lastName);
}
if (disableNotification != null) {
gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,8 +1,16 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@ -12,7 +20,7 @@ import java.util.Objects;
* @brief Use this method to send general files. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendDocument {
public class SendDocument extends PartialBotApiMethod<Message> {
public static final String PATH = "senddocument";
public static final String CHATID_FIELD = "chat_id";
@ -50,6 +58,12 @@ public class SendDocument {
return this;
}
public SendDocument setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getDocument() {
return document;
}
@ -72,7 +86,7 @@ public class SendDocument {
* @param file New document file
*/
public SendDocument setNewDocument(File file) {
this.document = file.getName();
Objects.requireNonNull(file, "documentName cannot be null!");
this.isNewDocument = true;
this.newDocumentFile = file;
return this;
@ -144,6 +158,43 @@ public class SendDocument {
return this;
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending document", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId == null) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (isNewDocument) {
if (newDocumentFile == null && newDocumentStream == null) {
throw new TelegramApiValidationException("Document can't be empty", this);
}
if (newDocumentStream != null && (documentName == null || documentName.isEmpty())) {
throw new TelegramApiValidationException("Document name can't be empty", this);
}
} else if (document == null) {
throw new TelegramApiValidationException("Document can't be empty", this);
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "SendDocument{" +

View File

@ -17,18 +17,18 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -45,14 +45,19 @@ public class SendGame extends BotApiMethod<Message> {
private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private static final String REPLYMARKUP_FIELD = "reply_markup";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(GAMESHORTNAME_FIELD)
private String gameShortName; ///< Short name of the game
/**
* Optional. Sends the message silently. iOS users will not receive a notification, Android
* users will receive a notification with no sound. Other apps coming soon
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
@JsonProperty(REPLYTOMESSAGEID_FIELD)
private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message
@JsonProperty(REPLYMARKUP_FIELD)
private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public SendGame() {
@ -68,6 +73,12 @@ public class SendGame extends BotApiMethod<Message> {
return this;
}
public SendGame setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getReplyToMessageId() {
return replyToMessageId;
}
@ -110,34 +121,23 @@ public class SendGame extends BotApiMethod<Message> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(GAMESHORTNAME_FIELD, gameShortName);
if (disableNotification != null) {
jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending game", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -148,30 +148,9 @@ public class SendGame extends BotApiMethod<Message> {
if (gameShortName == null || gameShortName.isEmpty()) {
throw new TelegramApiValidationException("GameShortName parameter can't be empty", this);
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(GAMESHORTNAME_FIELD, gameShortName);
if (disableNotification != null) {
gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
replyMarkup.validate();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,17 +1,17 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -28,17 +28,28 @@ public class SendLocation extends BotApiMethod<Message> {
private static final String DISABLENOTIFICATION_FIELD = "disable_notification";
private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private static final String REPLYMARKUP_FIELD = "reply_markup";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(LATITUDE_FIELD)
private Float latitude; ///< Latitude of location
@JsonProperty(LONGITUDE_FIELD)
private Float longitude; ///< Longitude of location
/**
* Optional. Sends the message silently. iOS users will not receive a notification, Android
* users will receive a notification with no sound. Other apps coming soon
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
@JsonProperty(REPLYTOMESSAGEID_FIELD)
private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message
@JsonProperty(REPLYMARKUP_FIELD)
private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public SendLocation() {
super();
}
public String getChatId() {
return chatId;
}
@ -48,6 +59,12 @@ public class SendLocation extends BotApiMethod<Message> {
return this;
}
public SendLocation setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Float getLatitude() {
return latitude;
}
@ -99,16 +116,23 @@ public class SendLocation extends BotApiMethod<Message> {
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending location", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -122,51 +146,9 @@ public class SendLocation extends BotApiMethod<Message> {
if (longitude == null) {
throw new TelegramApiValidationException("Longitude parameter can't be empty", this);
}
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(LATITUDE_FIELD, latitude);
jsonObject.put(LONGITUDE_FIELD, longitude);
if (disableNotification != null) {
jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
replyMarkup.validate();
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeNumberField(LONGITUDE_FIELD, longitude);
if (disableNotification != null) {
gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,18 +1,18 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.ParseMode;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -30,16 +30,24 @@ public class SendMessage extends BotApiMethod<Message> {
private static final String DISABLENOTIFICATION_FIELD = "disable_notification";
private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private static final String REPLYMARKUP_FIELD = "reply_markup";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(TEXT_FIELD)
private String text; ///< Text of the message to be sent
@JsonProperty(PARSEMODE_FIELD)
private String parseMode; ///< Optional. Send Markdown, if you want Telegram apps to show bold, italic and URL text in your bot's message.
@JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message
/**
* Optional. Sends the message silently. iOS users will not receive a notification, Android
* users will receive a notification with no sound. Other apps coming soon
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
@JsonProperty(REPLYTOMESSAGEID_FIELD)
private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message
@JsonProperty(REPLYMARKUP_FIELD)
private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public SendMessage() {
@ -55,6 +63,12 @@ public class SendMessage extends BotApiMethod<Message> {
return this;
}
public SendMessage setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getText() {
return text;
}
@ -110,6 +124,11 @@ public class SendMessage extends BotApiMethod<Message> {
return this;
}
public SendMessage setParseMode(String parseMode) {
this.parseMode = parseMode;
return this;
}
public SendMessage enableMarkdown(boolean enable) {
if (enable) {
this.parseMode = ParseMode.MARKDOWN;
@ -129,40 +148,23 @@ public class SendMessage extends BotApiMethod<Message> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(TEXT_FIELD, text);
if (parseMode != null) {
jsonObject.put(PARSEMODE_FIELD, parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview);
}
if (disableNotification != null) {
jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending message", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -173,38 +175,9 @@ public class SendMessage extends BotApiMethod<Message> {
if (text == null || text.isEmpty()) {
throw new TelegramApiValidationException("Text parameter can't be empty", this);
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeStringField(TEXT_FIELD, text);
if (parseMode != null) {
gen.writeStringField(PARSEMODE_FIELD, parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, disableWebPagePreview);
}
if (disableNotification != null) {
gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
replyMarkup.validate();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,8 +1,16 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@ -12,7 +20,7 @@ import java.util.Objects;
* @brief Use this method to send photos. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendPhoto {
public class SendPhoto extends PartialBotApiMethod<Message> {
public static final String PATH = "sendphoto";
public static final String CHATID_FIELD = "chat_id";
@ -50,6 +58,12 @@ public class SendPhoto {
return this;
}
public SendPhoto setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getPhoto() {
return photo;
}
@ -118,7 +132,6 @@ public class SendPhoto {
}
public SendPhoto setNewPhoto(File file) {
this.photo = file.getName();
this.newPhotoFile = file;
this.isNewPhoto = true;
return this;
@ -133,6 +146,42 @@ public class SendPhoto {
return this;
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending photo", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId == null) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (isNewPhoto) {
if (newPhotoFile == null && newPhotoStream == null) {
throw new TelegramApiValidationException("Photo can't be empty", this);
}
if (newPhotoStream != null && (photoName == null || photoName.isEmpty())) {
throw new TelegramApiValidationException("Photo name can't be empty", this);
}
} else if (photo == null) {
throw new TelegramApiValidationException("Photo can't be empty", this);
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "SendPhoto{" +

View File

@ -1,8 +1,16 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@ -12,7 +20,7 @@ import java.util.Objects;
* @brief Use this method to send .webp stickers. On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendSticker {
public class SendSticker extends PartialBotApiMethod<Message> {
public static final String PATH = "sendsticker";
public static final String CHATID_FIELD = "chat_id";
@ -48,6 +56,12 @@ public class SendSticker {
return this;
}
public SendSticker setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getSticker() {
return sticker;
}
@ -77,7 +91,6 @@ public class SendSticker {
}
public SendSticker setNewSticker(File file) {
this.sticker = file.getName();
this.isNewSticker = true;
this.newStickerFile = file;
return this;
@ -122,6 +135,42 @@ public class SendSticker {
return newStickerStream;
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending sticker", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId == null) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (isNewSticker) {
if (newStickerFile == null && newStickerStream == null) {
throw new TelegramApiValidationException("Sticker can't be empty", this);
}
if (newStickerStream != null && (stickerName == null || stickerName.isEmpty())) {
throw new TelegramApiValidationException("Sticker name can't be empty", this);
}
} else if (sticker == null) {
throw new TelegramApiValidationException("Sticker can't be empty", this);
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "SendSticker{" +

View File

@ -1,17 +1,17 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -32,20 +32,34 @@ public class SendVenue extends BotApiMethod<Message> {
private static final String FOURSQUARE_ID_FIELD = "foursquare_id";
private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private static final String REPLYMARKUP_FIELD = "reply_markup";
@JsonProperty(CHATID_FIELD)
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
@JsonProperty(LATITUDE_FIELD)
private Float latitude; ///< Latitude of venue location
@JsonProperty(LONGITUDE_FIELD)
private Float longitude; ///< Longitude of venue location
@JsonProperty(TITLE_FIELD)
private String title; ///< Title of the venue
/**
* Optional. Sends the message silently. iOS users will not receive a notification, Android
* users will receive a notification with no sound. Other apps coming soon
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
@JsonProperty(ADDRESS_FIELD)
private String address; ///< Address of the venue
@JsonProperty(FOURSQUARE_ID_FIELD)
private String foursquareId; ///< Optional. Foursquare identifier of the venue
@JsonProperty(REPLYTOMESSAGEID_FIELD)
private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message
@JsonProperty(REPLYMARKUP_FIELD)
private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
public SendVenue() {
super();
}
public String getChatId() {
return chatId;
}
@ -55,6 +69,12 @@ public class SendVenue extends BotApiMethod<Message> {
return this;
}
public SendVenue setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Float getLatitude() {
return latitude;
}
@ -133,16 +153,23 @@ public class SendVenue extends BotApiMethod<Message> {
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending venue", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -162,61 +189,9 @@ public class SendVenue extends BotApiMethod<Message> {
if (address == null) {
throw new TelegramApiValidationException("Address parameter can't be empty", this);
}
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(LATITUDE_FIELD, latitude);
jsonObject.put(LONGITUDE_FIELD, longitude);
jsonObject.put(TITLE_FIELD, title);
jsonObject.put(ADDRESS_FIELD, address);
if (foursquareId != null) {
jsonObject.put(FOURSQUARE_ID_FIELD, foursquareId);
}
if (disableNotification != null) {
jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
replyMarkup.validate();
}
return jsonObject;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(LATITUDE_FIELD, latitude);
gen.writeNumberField(LONGITUDE_FIELD, longitude);
gen.writeStringField(TITLE_FIELD, title);
gen.writeStringField(ADDRESS_FIELD, address);
if (foursquareId != null) {
gen.writeStringField(FOURSQUARE_ID_FIELD, foursquareId);
}
if (disableNotification != null) {
gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification);
}
if (replyToMessageId != null) {
gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,8 +1,16 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@ -13,7 +21,7 @@ import java.util.Objects;
* may be sent as Document). On success, the sent Message is returned.
* @date 20 of June of 2015
*/
public class SendVideo {
public class SendVideo extends PartialBotApiMethod<Message> {
public static final String PATH = "sendvideo";
public static final String CHATID_FIELD = "chat_id";
@ -67,6 +75,12 @@ public class SendVideo {
return this;
}
public SendVideo setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getDuration() {
return duration;
}
@ -152,7 +166,6 @@ public class SendVideo {
}
public SendVideo setNewVideo(File file) {
this.video = file.getName();
this.isNewVideo = true;
this.newVideoFile = file;
return this;
@ -167,6 +180,42 @@ public class SendVideo {
return this;
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending video", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId == null) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (isNewVideo) {
if (newVideoFile == null && newVideoStream == null) {
throw new TelegramApiValidationException("Video can't be empty", this);
}
if (newVideoStream != null && (videoName == null || videoName.isEmpty())) {
throw new TelegramApiValidationException("Video name can't be empty", this);
}
} else if (video == null) {
throw new TelegramApiValidationException("Video can't be empty", this);
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "SendVideo{" +

View File

@ -1,8 +1,16 @@
package org.telegram.telegrambots.api.methods.send;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@ -14,7 +22,7 @@ import java.util.Objects;
* (other formats may be sent as Audio or Document).
* @date 16 of July of 2015
*/
public class SendVoice {
public class SendVoice extends PartialBotApiMethod<Message> {
public static final String PATH = "sendvoice";
public static final String CHATID_FIELD = "chat_id";
@ -69,6 +77,12 @@ public class SendVoice {
return this;
}
public SendVoice setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public String getVoice() {
return voice;
}
@ -80,7 +94,6 @@ public class SendVoice {
}
public SendVoice setNewVoice(File file) {
this.voice = file.getName();
this.isNewVoice = true;
this.newVoiceFile = file;
return this;
@ -147,6 +160,43 @@ public class SendVoice {
return this;
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending voice", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId == null) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (isNewVoice) {
if (newVoiceFile == null && newVoiceStream == null) {
throw new TelegramApiValidationException("Voice can't be empty", this);
}
if (newVoiceStream != null && (voiceName == null || voiceName.isEmpty())) {
throw new TelegramApiValidationException("Voice name can't be empty", this);
}
} else if (voice == null) {
throw new TelegramApiValidationException("Voice can't be empty", this);
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "SendVoice{" +

View File

@ -1,7 +1,16 @@
package org.telegram.telegrambots.api.methods.updates;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IToJson;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.ArrayList;
/**
* @author Ruben Bermudez
@ -10,7 +19,7 @@ import org.telegram.telegrambots.api.interfaces.IToJson;
* objects is returned.
* @date 20 of June of 2015
*/
public class GetUpdates implements IToJson {
public class GetUpdates extends BotApiMethod<ArrayList<Update>>{
public static final String PATH = "getupdates";
private static final String OFFSET_FIELD = "offset";
@ -24,16 +33,19 @@ public class GetUpdates implements IToJson {
* specified to retrieve updates starting from -offset update from the end of the updates queue.
* All previous updates will forgotten.
*/
@JsonProperty(OFFSET_FIELD)
private Integer offset;
/**
* Optional Limits the number of updates to be retrieved. Values between 1100 are accepted.
* Defaults to 100
*/
@JsonProperty(LIMIT_FIELD)
private Integer limit;
/**
* Optional. Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling.
* Should be positive, 0 should be used for testing purposes only.
*/
@JsonProperty(TIMEOUT_FIELD)
private Integer timeout;
public GetUpdates() {
@ -68,18 +80,28 @@ public class GetUpdates implements IToJson {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (offset != null) {
jsonObject.put(OFFSET_FIELD, offset);
public String getMethod() {
return PATH;
}
@Override
public ArrayList<Update> deserializeResponse(String answer) throws
TelegramApiRequestException {
try {
ApiResponse<ArrayList<Update>> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<ArrayList<Update>>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting updates", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
if (limit != null) {
jsonObject.put(LIMIT_FIELD, limit);
}
if (timeout != null) {
jsonObject.put(TIMEOUT_FIELD, timeout);
}
return jsonObject;
}
@Override
public void validate() throws TelegramApiValidationException {
}
@Override

View File

@ -0,0 +1,59 @@
package org.telegram.telegrambots.api.methods.updates;
import com.fasterxml.jackson.core.type.TypeReference;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.WebhookInfo;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 2.4
* @brief Use this method to get current webhook status.
* Requires no parameters.
* On success, returns a WebhookInfo object.
* Will throw an error, if the bot is using getUpdates.
*
* @date 12 of August of 2016
*/
public class GetWebhookInfo extends BotApiMethod<WebhookInfo> {
public static final String PATH = "getwebhookinfo";
public GetWebhookInfo() {
super();
}
@Override
public String toString() {
return "GetWebhookInfo{}";
}
@Override
public String getMethod() {
return PATH;
}
@Override
public WebhookInfo deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<WebhookInfo> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<WebhookInfo>>() {
});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error getting webhook info", result);
}
} catch (IOException e2) {
throw new TelegramApiRequestException("Unable to deserialize response", e2);
}
}
@Override
public void validate() throws TelegramApiValidationException {
}
}

View File

@ -14,6 +14,7 @@ public class SetWebhook {
public static final String URL_FIELD = "url";
public static final String CERTIFICATE_FIELD = "certificate";
private String url; ///< Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration
private String certificateFile; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked

View File

@ -1,15 +1,13 @@
package org.telegram.telegrambots.api.methods.updatingmessages;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
@ -34,16 +32,21 @@ public class EditMessageCaption extends BotApiMethod<Message> {
* Required if inline_message_id is not specified. Unique identifier for the chat to send the
* message to (Or username for channels)
*/
@JsonProperty(CHATID_FIELD)
private String chatId;
/**
* Required if inline_message_id is not specified. Unique identifier of the sent message
*/
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId;
/**
* Required if chat_id and message_id are not specified. Identifier of the inline message
*/
@JsonProperty(INLINE_MESSAGE_ID_FIELD)
private String inlineMessageId;
@JsonProperty(CAPTION_FIELD)
private String caption; ///< Optional. New caption of the message
@JsonProperty(REPLYMARKUP_FIELD)
private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard.
public EditMessageCaption() {
@ -96,38 +99,23 @@ public class EditMessageCaption extends BotApiMethod<Message> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (inlineMessageId == null) {
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
} else {
jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (caption != null) {
jsonObject.put(CAPTION_FIELD, caption);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
try {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
} catch (JSONException e) {
return new Message();
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error editing message caption", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -147,31 +135,9 @@ public class EditMessageCaption extends BotApiMethod<Message> {
throw new TelegramApiValidationException("MessageId parameter must be empty if inlineMessageId is provided", this);
}
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
if (inlineMessageId == null) {
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
} else {
gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (caption != null) {
gen.writeStringField(CAPTION_FIELD, caption);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
replyMarkup.validate();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,18 +1,17 @@
package org.telegram.telegrambots.api.methods.updatingmessages;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -33,15 +32,19 @@ public class EditMessageReplyMarkup extends BotApiMethod<Message> {
* Required if inline_message_id is not specified. Unique identifier for the chat to send the
* message to (Or username for channels)
*/
@JsonProperty(CHATID_FIELD)
private String chatId;
/**
* Required if inline_message_id is not specified. Unique identifier of the sent message
*/
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId;
/**
* Required if chat_id and message_id are not specified. Identifier of the inline message
*/
@JsonProperty(INLINE_MESSAGE_ID_FIELD)
private String inlineMessageId;
@JsonProperty(REPLYMARKUP_FIELD)
private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard.
public EditMessageReplyMarkup() {
@ -57,6 +60,12 @@ public class EditMessageReplyMarkup extends BotApiMethod<Message> {
return this;
}
public EditMessageReplyMarkup setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getMessageId() {
return messageId;
}
@ -85,35 +94,23 @@ public class EditMessageReplyMarkup extends BotApiMethod<Message> {
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (inlineMessageId == null) {
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
} else {
jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
}
return jsonObject;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
try {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
} catch (JSONException e) {
return new Message();
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error editing message reply markup", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -133,28 +130,9 @@ public class EditMessageReplyMarkup extends BotApiMethod<Message> {
throw new TelegramApiValidationException("MessageId parameter must be empty if inlineMessageId is provided", this);
}
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
if (inlineMessageId == null) {
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
} else {
gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
replyMarkup.validate();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,19 +1,18 @@
package org.telegram.telegrambots.api.methods.updatingmessages;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.ParseMode;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ApiResponse;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.Objects;
/**
* @author Ruben Bermudez
@ -37,25 +36,32 @@ public class EditMessageText extends BotApiMethod<Message> {
* Required if inline_message_id is not specified. Unique identifier for the chat to send the
* message to (Or username for channels)
*/
@JsonProperty(CHATID_FIELD)
private String chatId;
/**
* Required if inline_message_id is not specified. Unique identifier of the sent message
*/
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId;
/**
* Required if chat_id and message_id are not specified. Identifier of the inline message
*/
@JsonProperty(INLINE_MESSAGE_ID_FIELD)
private String inlineMessageId;
/**
* New text of the message
*/
@JsonProperty(TEXT_FIELD)
private String text;
/**
* Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width
* text or inline URLs in your bot's message.
*/
@JsonProperty(PARSE_MODE_FIELD)
private String parseMode;
@JsonProperty(DISABLE_WEB_PREVIEW_FIELD)
private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message
@JsonProperty(REPLYMARKUP_FIELD)
private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard.
public EditMessageText() {
@ -71,6 +77,12 @@ public class EditMessageText extends BotApiMethod<Message> {
return this;
}
public EditMessageText setChatId(Long chatId) {
Objects.requireNonNull(chatId);
this.chatId = chatId.toString();
return this;
}
public Integer getMessageId() {
return messageId;
}
@ -135,43 +147,30 @@ public class EditMessageText extends BotApiMethod<Message> {
return this;
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
if (inlineMessageId == null) {
jsonObject.put(CHATID_FIELD, chatId);
jsonObject.put(MESSAGEID_FIELD, messageId);
} else {
jsonObject.put(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
jsonObject.put(TEXT_FIELD, text);
if (parseMode != null) {
jsonObject.put(PARSE_MODE_FIELD, parseMode);
}
if (disableWebPagePreview != null) {
jsonObject.put(DISABLE_WEB_PREVIEW_FIELD, disableWebPagePreview);
}
if (replyMarkup != null) {
jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson());
}
return jsonObject;
public EditMessageText setParseMode(String parseMode) {
this.parseMode = parseMode;
return this;
}
@Override
public String getPath() {
public String getMethod() {
return PATH;
}
@Override
public Message deserializeResponse(JSONObject answer) {
if (answer.getBoolean(Constants.RESPONSEFIELDOK)) {
try {
return new Message(answer.getJSONObject(Constants.RESPONSEFIELDRESULT));
} catch (JSONException e) {
return new Message();
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
try {
ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<Message>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error editing message text", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
return null;
}
@Override
@ -194,35 +193,9 @@ public class EditMessageText extends BotApiMethod<Message> {
if (text == null || text.isEmpty()) {
throw new TelegramApiValidationException("Text parameter can't be empty", this);
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(METHOD_FIELD, PATH);
if (inlineMessageId == null) {
gen.writeStringField(CHATID_FIELD, chatId);
gen.writeNumberField(MESSAGEID_FIELD, messageId);
} else {
gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
gen.writeStringField(TEXT_FIELD, text);
if (parseMode != null) {
gen.writeStringField(PARSE_MODE_FIELD, parseMode);
}
if (disableWebPagePreview != null) {
gen.writeBooleanField(DISABLE_WEB_PREVIEW_FIELD, disableWebPagePreview);
}
if (replyMarkup != null) {
gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup);
replyMarkup.validate();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,7 +10,7 @@ import java.io.IOException;
* @brief This object represents an audio file
* @date 16 of July of 2015
*/
public class Audio implements IBotApiObject {
public class Audio implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String DURATION_FIELD = "duration";
@ -24,6 +18,7 @@ public class Audio implements IBotApiObject {
private static final String FILESIZE_FIELD = "file_size";
private static final String TITLE_FIELD = "title";
private static final String PERFORMER_FIELD = "performer";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(DURATION_FIELD)
@ -41,24 +36,6 @@ public class Audio implements IBotApiObject {
super();
}
public Audio(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.duration = jsonObject.getInt(DURATION_FIELD);
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILEID_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
if (jsonObject.has(TITLE_FIELD)) {
this.title = jsonObject.getString(TITLE_FIELD);
}
if (jsonObject.has(PERFORMER_FIELD)) {
this.performer = jsonObject.getString(PERFORMER_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -83,32 +60,6 @@ public class Audio implements IBotApiObject {
return performer;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(DURATION_FIELD, duration);
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
if (title != null) {
gen.writeStringField(TITLE_FIELD, title);
}
if (performer != null) {
gen.writeStringField(PERFORMER_FIELD, performer);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Audio{" +

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -25,7 +19,7 @@ import java.io.IOException;
* (e.g., without specifying any of the optional parameters).
* @date 10 of April of 2016
*/
public class CallbackQuery implements IBotApiObject {
public class CallbackQuery implements BotApiObject {
private static final String ID_FIELD = "id";
private static final String FROM_FIELD = "from";
@ -39,58 +33,39 @@ public class CallbackQuery implements IBotApiObject {
private String id; ///< Unique identifier for this query
@JsonProperty(FROM_FIELD)
private User from; ///< Sender
@JsonProperty(MESSAGE_FIELD)
/**
* Optional.
* Message with the callback button that originated the query.
*
* @note The message content and message date will not be available if the message is too old
*/
@JsonProperty(MESSAGE_FIELD)
private Message message;
@JsonProperty(INLINE_MESSAGE_ID_FIELD)
private String inlineMessageId; ///< Optional. Identifier of the message sent via the bot in inline mode, that originated the query
@JsonProperty(DATA_FIELD)
/**
*
* Optional. Data associated with the callback button.
* @note Be aware that a bad client can send arbitrary data in this field
*/
@JsonProperty(DATA_FIELD)
private String data;
@JsonProperty(GAMESHORTNAME_FIELD)
/**
* Optional. Short name of a Game to be returned, serves as the unique identifier for the game
*/
@JsonProperty(GAMESHORTNAME_FIELD)
private String gameShortName;
@JsonProperty(CHAT_INSTANCE_FIELD)
/**
* Identifier, uniquely corresponding to the chat to which the message with the
* callback button was sent. Useful for high scores in games.
*/
@JsonProperty(CHAT_INSTANCE_FIELD)
private String chatInstance;
public CallbackQuery() {
super();
}
public CallbackQuery(JSONObject jsonObject) {
super();
this.id = jsonObject.getString(ID_FIELD);
this.from = new User(jsonObject.getJSONObject(FROM_FIELD));
chatInstance = jsonObject.getString(CHAT_INSTANCE_FIELD);
if (jsonObject.has(MESSAGE_FIELD)) {
this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD));
}
if (jsonObject.has(INLINE_MESSAGE_ID_FIELD)) {
this.inlineMessageId = jsonObject.getString(INLINE_MESSAGE_ID_FIELD);
}
if (jsonObject.has(DATA_FIELD)) {
data = jsonObject.getString(DATA_FIELD);
}
if (jsonObject.has(GAMESHORTNAME_FIELD)) {
gameShortName = jsonObject.getString(GAMESHORTNAME_FIELD);
}
}
public String getId() {
return this.id;
}
@ -119,33 +94,6 @@ public class CallbackQuery implements IBotApiObject {
return chatInstance;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(ID_FIELD, id);
gen.writeObjectField(FROM_FIELD, from);
gen.writeStringField(CHAT_INSTANCE_FIELD, chatInstance);
if (message != null) {
gen.writeObjectField(MESSAGE_FIELD, message);
}
if (inlineMessageId != null) {
gen.writeStringField(INLINE_MESSAGE_ID_FIELD, inlineMessageId);
}
if (data != null) {
gen.writeStringField(DATA_FIELD, data);
}
if (gameShortName != null) {
gen.writeStringField(GAMESHORTNAME_FIELD, gameShortName);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "CallbackQuery{" +

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,7 +10,8 @@ import java.io.IOException;
* @brief This object represents a Telegram chat with an user or a group
* @date 24 of June of 2015
*/
public class Chat implements IBotApiObject {
public class Chat implements BotApiObject {
private static final String ID_FIELD = "id";
private static final String TYPE_FIELD = "type";
private static final String TITLE_FIELD = "title";
@ -28,13 +23,14 @@ public class Chat implements IBotApiObject {
private static final String GROUPCHATTYPE = "group";
private static final String CHANNELCHATTYPE = "channel";
private static final String SUPERGROUPCHATTYPE = "supergroup";
@JsonProperty(ID_FIELD)
/**
* Unique identifier for this chat.
* This number may be greater than 32 bits and some programming languages may
* have difficulty/silent defects in interpreting it. But it smaller than 52 bits,
* so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
*/
@JsonProperty(ID_FIELD)
private Long id; ///< Unique identifier for this chat, not exciding 1e13 by absolute value
@JsonProperty(TYPE_FIELD)
private String type; ///< Type of the chat, one of private, group or channel
@ -46,37 +42,16 @@ public class Chat implements IBotApiObject {
private String lastName; ///< Optional. Interlocutor's first name for private chats
@JsonProperty(USERNAME_FIELD)
private String userName; ///< Optional. Interlocutor's last name for private chats
@JsonProperty(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD)
/**
* Optional. True if the group or supergroup has All Members Are Admins enabled.
*/
@JsonProperty(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD)
private Boolean allMembersAreAdministrators;
public Chat() {
super();
}
public Chat(JSONObject jsonObject) {
super();
this.id = jsonObject.getLong(ID_FIELD);
this.type = jsonObject.getString(TYPE_FIELD);
if (jsonObject.has(TITLE_FIELD)) {
this.title = jsonObject.getString(TITLE_FIELD);
}
if (jsonObject.has(FIRSTNAME_FIELD)) {
this.firstName = jsonObject.getString(FIRSTNAME_FIELD);
}
if (jsonObject.has(LASTNAME_FIELD)) {
this.lastName = jsonObject.getString(LASTNAME_FIELD);
}
if (jsonObject.has(USERNAME_FIELD)) {
this.userName = jsonObject.getString(USERNAME_FIELD);
}
if (jsonObject.has(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD)) {
allMembersAreAdministrators = jsonObject.getBoolean(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD);
}
}
public Long getId() {
return id;
}
@ -117,38 +92,6 @@ public class Chat implements IBotApiObject {
return allMembersAreAdministrators;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(ID_FIELD, id);
gen.writeStringField(TYPE_FIELD, type);
if (isUserChat()) {
if (firstName != null) {
gen.writeStringField(FIRSTNAME_FIELD, firstName);
}
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
} else {
if (title != null) {
gen.writeStringField(TITLE_FIELD, title);
}
}
if (!isGroupChat() && userName != null) {
gen.writeStringField(USERNAME_FIELD, userName);
}
if (allMembersAreAdministrators != null) {
gen.writeBooleanField(ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD, allMembersAreAdministrators);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Chat{" +

View File

@ -0,0 +1,41 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object contains information about one member of the chat.
* @date 20 of May of 2016
*/
public class ChatMember implements BotApiObject {
private static final String USER_FIELD = "user";
private static final String STATUS_FIELD = "status";
@JsonProperty(USER_FIELD)
private User user; ///< Information about the user
@JsonProperty(STATUS_FIELD)
private String status; ///< The member's status in the chat. Can be creator, administrator, member, left or kicked
public ChatMember() {
super();
}
public User getUser() {
return user;
}
public String getStatus() {
return status;
}
@Override
public String toString() {
return "ChatMember{" +
"user=" + user +
", status='" + status + '\'' +
'}';
}
}

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,12 +10,13 @@ import java.io.IOException;
* @brief This object represents a phone contact.
* @date 20 of June of 2015
*/
public class Contact implements IBotApiObject {
public class Contact implements BotApiObject {
private static final String PHONENUMBER_FIELD = "phone_number";
private static final String FIRSTNAME_FIELD = "first_name";
private static final String LASTNAME_FIELD = "last_name";
private static final String USERID_FIELD = "user_id";
@JsonProperty(PHONENUMBER_FIELD)
private String phoneNumber; ///< Contact's phone number
@JsonProperty(FIRSTNAME_FIELD)
@ -35,18 +30,6 @@ public class Contact implements IBotApiObject {
super();
}
public Contact(JSONObject jsonObject) {
super();
this.phoneNumber = jsonObject.getString(PHONENUMBER_FIELD);
this.firstName = jsonObject.getString(FIRSTNAME_FIELD);
if (jsonObject.has(LASTNAME_FIELD)) {
this.lastName = jsonObject.getString(LASTNAME_FIELD);
}
if (jsonObject.has(USERID_FIELD)) {
this.userID = jsonObject.getInt(USERID_FIELD);
}
}
public String getPhoneNumber() {
return phoneNumber;
}
@ -63,26 +46,6 @@ public class Contact implements IBotApiObject {
return userID;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(PHONENUMBER_FIELD, phoneNumber);
gen.writeStringField(FIRSTNAME_FIELD, firstName);
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
if (userID != null) {
gen.writeNumberField(USERID_FIELD, userID);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Contact{" +

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -17,13 +11,14 @@ import java.io.IOException;
* Telegram users can send files of any type of up to 1.5 GB in size.
* @date 20 of June of 2015
*/
public class Document implements IBotApiObject {
public class Document implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String THUMB_FIELD = "thumb";
private static final String FILENAME_FIELD = "file_name";
private static final String MIMETYPE_FIELD = "mime_type";
private static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(THUMB_FIELD)
@ -39,22 +34,6 @@ public class Document implements IBotApiObject {
super();
}
public Document(JSONObject jsonObject) {
this.fileId = jsonObject.getString(FILEID_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(FILENAME_FIELD)) {
this.fileName = jsonObject.getString(FILENAME_FIELD);
}
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -75,29 +54,6 @@ public class Document implements IBotApiObject {
return fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeObjectField(THUMB_FIELD, thumb);
if (fileName != null) {
gen.writeStringField(FILENAME_FIELD, fileName);
}
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Document{" +

View File

@ -1,14 +1,12 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.text.MessageFormat;
/**
* @author Ruben Bermudez
@ -16,12 +14,19 @@ import java.io.IOException;
* @brief This object represents a file ready to be downloaded
* @date 24 of June of 2015
*/
public class File implements IBotApiObject {
public class File implements BotApiObject {
@JsonIgnore
/**
* @deprecated It is still public for backward compatibility, will be removed in next big release.
* use {@link #getFileUrl(String, String)} or {@link #getFileUrl(String)} instead.
*/
@Deprecated
public static final String FILEBASEURL = "https://api.telegram.org/file/bot{0}/{1}";
private static final String FILE_ID = "file_id";
private static final String FILE_SIZE_FIELD = "file_size";
private static final String FILE_PATH_FIELD = "file_path";
@JsonProperty(FILE_ID)
private String fileId; ///< Unique identifier for this file
@JsonProperty(FILE_SIZE_FIELD)
@ -33,17 +38,6 @@ public class File implements IBotApiObject {
super();
}
public File(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILE_ID);
if (jsonObject.has(FILE_SIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILE_SIZE_FIELD);
}
if (jsonObject.has(FILE_PATH_FIELD)) {
this.filePath = jsonObject.getString(FILE_PATH_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -56,25 +50,6 @@ public class File implements IBotApiObject {
return filePath;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILE_ID, fileId);
if (fileSize != null) {
gen.writeNumberField(FILE_SIZE_FIELD, fileSize);
}
if (filePath != null) {
gen.writeStringField(FILE_PATH_FIELD, filePath);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "File{" +
@ -83,4 +58,15 @@ public class File implements IBotApiObject {
", filePath='" + filePath + '\'' +
'}';
}
public String getFileUrl(String botToken) {
return getFileUrl(botToken, filePath);
}
public static String getFileUrl(String botToken, String filePath) {
if (botToken == null || botToken.isEmpty()) {
throw new InvalidParameterException("Bot token can't be empty");
}
return MessageFormat.format("https://api.telegram.org/file/bot{0}/{1}", botToken, filePath);
}
}

View File

@ -0,0 +1,42 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a point on the map.
* @date 20 of June of 2015
*/
public class Location implements BotApiObject {
private static final String LONGITUDE_FIELD = "longitude";
private static final String LATITUDE_FIELD = "latitude";
@JsonProperty(LONGITUDE_FIELD)
private Double longitude; ///< Longitude as defined by sender
@JsonProperty(LATITUDE_FIELD)
private Double latitude; ///< Latitude as defined by sender
public Location() {
super();
}
public Double getLongitude() {
return longitude;
}
public Double getLatitude() {
return latitude;
}
@Override
public String toString() {
return "Location{" +
"longitude=" + longitude +
", latitude=" + latitude +
'}';
}
}

View File

@ -1,17 +1,10 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.objects.games.Game;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
@ -20,7 +13,7 @@ import java.util.List;
* @brief This object represents a message.
* @date 20 of June of 2015
*/
public class Message implements IBotApiObject {
public class Message implements BotApiObject {
private static final String MESSAGEID_FIELD = "message_id";
private static final String FROM_FIELD = "from";
private static final String DATE_FIELD = "date";
@ -71,11 +64,11 @@ public class Message implements IBotApiObject {
private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent
@JsonProperty(TEXT_FIELD)
private String text; ///< Optional. For text messages, the actual UTF-8 text of the message
@JsonProperty(ENTITIES_FIELD)
/**
* Optional. For text messages, special entities like usernames, URLs,
* bot commands, etc. that appear in the text
*/
@JsonProperty(ENTITIES_FIELD)
private List<MessageEntity> entities;
@JsonProperty(AUDIO_FIELD)
private Audio audio; ///< Optional. Message is an audio file, information about the file
@ -113,7 +106,6 @@ public class Message implements IBotApiObject {
private Voice voice; ///< Optional. Message is a voice message, information about the file
@JsonProperty(CAPTION_FIELD)
private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters
@JsonProperty(SUPERGROUPCREATED_FIELD)
/**
* Optional. Service message: the supergroup has been created.
* This field cant be received in a message coming through updates,
@ -121,8 +113,8 @@ public class Message implements IBotApiObject {
* It can only be found in reply_to_message
* if someone replies to a very first message in a directly created supergroup.
*/
@JsonProperty(SUPERGROUPCREATED_FIELD)
private Boolean superGroupCreated;
@JsonProperty(CHANNELCHATCREATED_FIELD)
/**
* Optional. Service message: the channel has been created.
* This field cant be received in a message coming through updates,
@ -130,8 +122,8 @@ public class Message implements IBotApiObject {
* It can only be found in reply_to_message if someone
* replies to a very first message in a channel.
*/
@JsonProperty(CHANNELCHATCREATED_FIELD)
private Boolean channelChatCreated;
@JsonProperty(MIGRATETOCHAT_FIELD)
/**
* Optional. The group has been migrated to a supergroup with the specified identifier.
* This number may be greater than 32 bits and some programming languages
@ -139,8 +131,8 @@ public class Message implements IBotApiObject {
* But it smaller than 52 bits, so a signed 64 bit integer or double-precision
* float type are safe for storing this identifier.
*/
@JsonProperty(MIGRATETOCHAT_FIELD)
private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
@JsonProperty(MIGRATEFROMCHAT_FIELD)
/**
* Optional. The supergroup has been migrated from a group with the specified identifier.
* This number may be greater than 32 bits and some programming languages
@ -148,6 +140,7 @@ public class Message implements IBotApiObject {
* But it smaller than 52 bits, so a signed 64 bit integer or double-precision
* float type are safe for storing this identifier.
*/
@JsonProperty(MIGRATEFROMCHAT_FIELD)
private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
@JsonProperty(EDITDATE_FIELD)
private Integer editDate; ///< Optional. Date the message was last edited in Unix time
@ -158,120 +151,6 @@ public class Message implements IBotApiObject {
super();
}
public Message(JSONObject jsonObject) {
super();
this.messageId = jsonObject.getInt(MESSAGEID_FIELD);
if (jsonObject.has(FROM_FIELD)) {
this.from = new User(jsonObject.getJSONObject(FROM_FIELD));
}
if (jsonObject.has(DATE_FIELD)) {
this.date = jsonObject.getInt(DATE_FIELD);
}
this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD));
if (jsonObject.has(FORWARDFROMCHAT_FIELD)) {
this.forwardFromChat = new Chat(jsonObject.getJSONObject(FORWARDFROMCHAT_FIELD));
}
if (jsonObject.has(FORWARDFROM_FIELD)) {
this.forwardFrom = new User(jsonObject.getJSONObject(FORWARDFROM_FIELD));
}
if (jsonObject.has(FORWARDDATE_FIELD)) {
this.forwardDate = jsonObject.getInt(FORWARDDATE_FIELD);
}
if (jsonObject.has(TEXT_FIELD)) {
this.text = jsonObject.getString(TEXT_FIELD);
}
if (jsonObject.has(ENTITIES_FIELD)) {
this.entities = new ArrayList<>();
JSONArray entities = jsonObject.getJSONArray(ENTITIES_FIELD);
for (int i = 0; i < entities.length(); i++) {
this.entities.add(new MessageEntity(entities.getJSONObject(i)));
}
}
if (jsonObject.has(AUDIO_FIELD)) {
this.audio = new Audio(jsonObject.getJSONObject(AUDIO_FIELD));
}
if (jsonObject.has(DOCUMENT_FIELD)) {
this.document = new Document(jsonObject.getJSONObject(DOCUMENT_FIELD));
}
if (jsonObject.has(PHOTO_FIELD)) {
this.photo = new ArrayList<>();
JSONArray photos = jsonObject.getJSONArray(PHOTO_FIELD);
for (int i = 0; i < photos.length(); i++) {
this.photo.add(new PhotoSize(photos.getJSONObject(i)));
}
}
if (jsonObject.has(STICKER_FIELD)) {
this.sticker = new Sticker(jsonObject.getJSONObject(STICKER_FIELD));
}
if (jsonObject.has(VIDEO_FIELD)) {
this.video = new Video(jsonObject.getJSONObject(VIDEO_FIELD));
}
if (jsonObject.has(CONTACT_FIELD)) {
this.contact = new Contact(jsonObject.getJSONObject(CONTACT_FIELD));
}
if (jsonObject.has(LOCATION_FIELD)) {
this.location = new Location(jsonObject.getJSONObject(LOCATION_FIELD));
}
if (jsonObject.has(VENUE_FIELD)) {
venue = new Venue(jsonObject.getJSONObject(VENUE_FIELD));
}
if (jsonObject.has(PINNED_MESSAGE_FIELD)) {
pinnedMessage = new Message(jsonObject.getJSONObject(PINNED_MESSAGE_FIELD));
}
if (jsonObject.has(VOICE_FIELD)) {
this.voice = new Voice(jsonObject.getJSONObject(VOICE_FIELD));
}
if (jsonObject.has(CAPTION_FIELD)) {
this.caption = jsonObject.getString(CAPTION_FIELD);
}
if (jsonObject.has(NEWCHATMEMBER_FIELD)) {
this.newChatMember = new User(jsonObject.getJSONObject(NEWCHATMEMBER_FIELD));
}
if (jsonObject.has(LEFTCHATMEMBER_FIELD)) {
this.leftChatMember = new User(jsonObject.getJSONObject(LEFTCHATMEMBER_FIELD));
}
if (jsonObject.has(REPLYTOMESSAGE_FIELD)) {
this.replyToMessage = new Message(jsonObject.getJSONObject(REPLYTOMESSAGE_FIELD));
}
if (jsonObject.has(NEWCHATTITLE_FIELD)) {
this.newChatTitle = jsonObject.getString(NEWCHATTITLE_FIELD);
}
if (jsonObject.has(NEWCHATPHOTO_FIELD)) {
JSONArray photoArray = jsonObject.getJSONArray(NEWCHATPHOTO_FIELD);
this.newChatPhoto = new ArrayList<>();
for (int i = 0; i < photoArray.length(); i++) {
this.newChatPhoto.add(new PhotoSize(photoArray.getJSONObject(i)));
}
}
if (jsonObject.has(DELETECHATPHOTO_FIELD)) {
this.deleteChatPhoto = true;
}
if (jsonObject.has(GROUPCHATCREATED_FIELD)) {
this.groupchatCreated = true;
}
if (jsonObject.has(SUPERGROUPCREATED_FIELD)) {
this.superGroupCreated = true;
}
if (jsonObject.has(CHANNELCHATCREATED_FIELD)) {
this.channelChatCreated = true;
}
if (jsonObject.has(MIGRATETOCHAT_FIELD)) {
this.migrateToChatId = jsonObject.getLong(MIGRATETOCHAT_FIELD);
}
if (jsonObject.has(MIGRATEFROMCHAT_FIELD)) {
this.migrateFromChatId = jsonObject.getLong(MIGRATEFROMCHAT_FIELD);
}
if (jsonObject.has(EDITDATE_FIELD)) {
editDate = jsonObject.getInt(EDITDATE_FIELD);
}
if (jsonObject.has(GAME_FIELD)) {
game = new Game(jsonObject.getJSONObject(GAME_FIELD));
}
if (hasText() && entities != null) {
entities.forEach(x -> x.computeText(text));
}
}
public Integer getMessageId() {
return messageId;
}
@ -301,6 +180,7 @@ public class Message implements IBotApiObject {
}
public List<MessageEntity> getEntities() {
entities.forEach(x -> x.computeText(text));
return entities;
}
@ -460,120 +340,8 @@ public class Message implements IBotApiObject {
return entities != null && !entities.isEmpty();
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(MESSAGEID_FIELD, messageId);
if (from != null) {
gen.writeObjectField(FROM_FIELD, from);
}
if (date != null) {
gen.writeNumberField(DATE_FIELD, date);
}
gen.writeObjectField(CHAT_FIELD, chat);
if (forwardFromChat != null) {
gen.writeObjectField(FORWARDFROMCHAT_FIELD, forwardFromChat);
}
if (forwardFrom != null) {
gen.writeObjectField(FORWARDFROM_FIELD, forwardFrom);
}
if (forwardDate != null) {
gen.writeNumberField(FORWARDDATE_FIELD, forwardDate);
}
if (text != null) {
gen.writeStringField(TEXT_FIELD, text);
}
if (audio != null) {
gen.writeObjectField(AUDIO_FIELD, audio);
}
if (document != null) {
gen.writeObjectField(DOCUMENT_FIELD, document);
}
if (photo != null && photo.size() > 0) {
gen.writeArrayFieldStart(PHOTO_FIELD);
for (PhotoSize photoSize : photo) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
}
if (sticker != null) {
gen.writeObjectField(STICKER_FIELD, sticker);
}
if (video != null) {
gen.writeObjectField(VIDEO_FIELD, video);
}
if (contact != null) {
gen.writeObjectField(CONTACT_FIELD, contact);
}
if (location != null) {
gen.writeObjectField(LOCATION_FIELD, location);
}
if (venue != null) {
gen.writeObjectField(VENUE_FIELD, venue);
}
if (voice != null) {
gen.writeObjectField(VOICE_FIELD, voice);
}
if (caption != null) {
gen.writeObjectField(CAPTION_FIELD, caption);
}
if (newChatMember != null) {
gen.writeObjectField(NEWCHATMEMBER_FIELD, newChatMember);
}
if (leftChatMember != null) {
gen.writeObjectField(LEFTCHATMEMBER_FIELD, leftChatMember);
}
if (replyToMessage != null) {
gen.writeObjectField(REPLYTOMESSAGE_FIELD, replyToMessage);
}
if (newChatTitle != null) {
gen.writeStringField(NEWCHATTITLE_FIELD, newChatTitle);
}
if (newChatPhoto != null && newChatPhoto.size() > 0) {
gen.writeArrayFieldStart(NEWCHATPHOTO_FIELD);
for (PhotoSize photoSize: newChatPhoto) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
}
if (deleteChatPhoto != null) {
gen.writeBooleanField(DELETECHATPHOTO_FIELD, deleteChatPhoto);
}
if (groupchatCreated != null) {
gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated);
}
if (superGroupCreated != null) {
gen.writeBooleanField(SUPERGROUPCREATED_FIELD, superGroupCreated);
}
if (channelChatCreated != null) {
gen.writeBooleanField(CHANNELCHATCREATED_FIELD, channelChatCreated);
}
if (migrateToChatId != null) {
gen.writeNumberField(MIGRATETOCHAT_FIELD, migrateToChatId);
}
if (migrateFromChatId != null) {
gen.writeNumberField(MIGRATEFROMCHAT_FIELD, migrateFromChatId);
}
if (editDate != null) {
gen.writeNumberField(EDITDATE_FIELD, editDate);
}
if (game != null) {
gen.writeObjectField(GAME_FIELD, game);
}
if (entities != null) {
gen.writeArrayFieldStart(ENTITIES_FIELD);
for (MessageEntity entity : entities) {
gen.writeObject(entity);
}
gen.writeEndArray();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
public boolean hasPhoto() {
return photo != null && !photo.isEmpty();
}
@Override

View File

@ -1,14 +1,9 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -17,14 +12,13 @@ import java.io.IOException;
* usernames, URL.
* @date 20 of June of 2015
*/
public class MessageEntity implements IBotApiObject {
public class MessageEntity implements BotApiObject {
private static final String TYPE_FIELD = "type";
private static final String OFFSET_FIELD = "offset";
private static final String LENGTH_FIELD = "length";
private static final String URL_FIELD = "url";
private static final String USER_FIELD = "user";
@JsonProperty(TYPE_FIELD)
/**
* Type of the entity. One of
* mention (@username),
@ -39,6 +33,8 @@ public class MessageEntity implements IBotApiObject {
* text_link (for clickable text URLs)
* text_mention (for users without usernames)
*/
@JsonProperty(TYPE_FIELD)
private String type;
@JsonProperty(OFFSET_FIELD)
private Integer offset; ///< Offset in UTF-16 code units to the start of the entity
@ -48,26 +44,13 @@ public class MessageEntity implements IBotApiObject {
private String url; ///< Optional. For text_link only, url that will be opened after user taps on the text
@JsonProperty(USER_FIELD)
private User user; ///< Optional. For text_mention only, the mentioned user
@JsonIgnore
private String text; ///< Text present in the entity. Computed from offset and length
public MessageEntity() {
super();
}
public MessageEntity(JSONObject jsonObject) {
super();
this.type = jsonObject.getString(TYPE_FIELD);
this.offset = jsonObject.getInt(OFFSET_FIELD);
this.length = jsonObject.getInt(LENGTH_FIELD);
if (EntityType.TEXTLINK.equals(type)) {
this.url = jsonObject.getString(URL_FIELD);
}
if (EntityType.TEXTMENTION.equals(type)) {
this.user = new User(jsonObject.getJSONObject(USER_FIELD));
}
}
public String getType() {
return type;
}
@ -93,28 +76,9 @@ public class MessageEntity implements IBotApiObject {
}
protected void computeText(String message) {
text = message.substring(offset, offset + length);
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TYPE_FIELD, type);
gen.writeNumberField(OFFSET_FIELD, offset);
gen.writeNumberField(LENGTH_FIELD, length);
if (url != null && EntityType.TEXTLINK.equals(type)) {
gen.writeStringField(URL_FIELD, url);
if (message != null) {
text = message.substring(offset, offset + length);
}
if (user != null && EntityType.TEXTMENTION.equals(type)) {
gen.writeObjectField(USER_FIELD, user);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,13 +10,14 @@ import java.io.IOException;
* @brief This object represents one size of a photo or a file / sticker thumbnail.
* @date 20 of June of 2015
*/
public class PhotoSize implements IBotApiObject {
public class PhotoSize implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String WIDTH_FIELD = "width";
private static final String HEIGHT_FIELD = "height";
private static final String FILESIZE_FIELD = "file_size";
private static final String FILEPATH_FIELD = "file_path";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(WIDTH_FIELD)
@ -38,19 +33,6 @@ public class PhotoSize implements IBotApiObject {
super();
}
public PhotoSize(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
if (jsonObject.has(FILEPATH_FIELD)) {
this.filePath = jsonObject.getString(FILEPATH_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -71,25 +53,8 @@ public class PhotoSize implements IBotApiObject {
return filePath;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
if (filePath != null) {
gen.writeStringField(FILEPATH_FIELD, filePath);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
public boolean hasFilePath() {
return filePath != null && !filePath.isEmpty();
}
@Override

View File

@ -18,14 +18,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -33,34 +27,27 @@ import java.io.IOException;
* @brief Contains information about why a request was unsuccessfull.
* @date 28 of September of 2016
*/
public class ResponseParameters implements IBotApiObject {
public class ResponseParameters implements BotApiObject {
private static final String MIGRATETOCHATID_FIELD = "migrate_to_chat_id";
private static final String RETRYAFTER_FIELD = "retry_after";
@JsonProperty(MIGRATETOCHATID_FIELD)
/**
* Optional. The group has been migrated to a supergroup with the specified identifier.
* This number may be greater than 32 bits and some programming languages may have
* difficulty/silent defects in interpreting it. But it is smaller than 52 bits,
* so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
*/
@JsonProperty(MIGRATETOCHATID_FIELD)
private Integer migrateToChatId;
@JsonProperty(RETRYAFTER_FIELD)
/**
* Optional. In case of exceeding flood control a number of seconds to
* wait before the request can be repeated
*/
@JsonProperty(RETRYAFTER_FIELD)
private Integer retryAfter;
public ResponseParameters(JSONObject object) {
if (object != null) {
if (object.has(MIGRATETOCHATID_FIELD)) {
migrateToChatId = object.getInt(MIGRATETOCHATID_FIELD);
}
if (object.has(RETRYAFTER_FIELD)) {
retryAfter = object.getInt(RETRYAFTER_FIELD);
}
}
public ResponseParameters() {
super();
}
public Integer getMigrateToChatId() {
@ -72,20 +59,10 @@ public class ResponseParameters implements IBotApiObject {
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
if (migrateToChatId != null) {
gen.writeNumberField(MIGRATETOCHATID_FIELD, migrateToChatId);
}
if (retryAfter != null) {
gen.writeNumberField(RETRYAFTER_FIELD, retryAfter);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
public String toString() {
return "ResponseParameters{" +
"migrateToChatId=" + migrateToChatId +
", retryAfter=" + retryAfter +
'}';
}
}

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,7 +10,7 @@ import java.io.IOException;
* @brief This object represents a sticker.
* @date 20 of June of 2015
*/
public class Sticker implements IBotApiObject {
public class Sticker implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String WIDTH_FIELD = "width";
@ -24,6 +18,7 @@ public class Sticker implements IBotApiObject {
private static final String THUMB_FIELD = "thumb";
private static final String FILESIZE_FIELD = "file_size";
private static final String EMOJI_FIELD = "emoji";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(WIDTH_FIELD)
@ -41,22 +36,6 @@ public class Sticker implements IBotApiObject {
super();
}
public Sticker(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
if (jsonObject.has(EMOJI_FIELD)) {
this.emoji = jsonObject.getString(EMOJI_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -81,30 +60,6 @@ public class Sticker implements IBotApiObject {
return emoji;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
if (thumb != null) {
gen.writeObjectField(THUMB_FIELD, thumb);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
if (emoji != null) {
gen.writeStringField(EMOJI_FIELD, emoji);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Sticker{" +

View File

@ -1,17 +1,11 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.objects.inlinequery.ChosenInlineQuery;
import org.telegram.telegrambots.api.objects.inlinequery.InlineQuery;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
@ -19,13 +13,14 @@ import java.io.IOException;
* Only one of the optional parameters can be present in any given update.
* @date 20 of June of 2015
*/
public class Update implements IBotApiObject {
public class Update implements BotApiObject {
private static final String UPDATEID_FIELD = "update_id";
private static final String MESSAGE_FIELD = "message";
private static final String INLINEQUERY_FIELD = "inline_query";
private static final String CHOSENINLINEQUERY_FIELD = "chosen_inline_result";
private static final String CALLBACKQUERY_FIELD = "callback_query";
private static final String EDITEDMESSAGE_FIELD = "edited_message";
@JsonProperty(UPDATEID_FIELD)
private Integer updateId;
@JsonProperty(MESSAGE_FIELD)
@ -43,26 +38,6 @@ public class Update implements IBotApiObject {
super();
}
public Update(JSONObject jsonObject) {
super();
this.updateId = jsonObject.getInt(UPDATEID_FIELD);
if (jsonObject.has(MESSAGE_FIELD)) {
this.message = new Message(jsonObject.getJSONObject(MESSAGE_FIELD));
}
if (jsonObject.has(INLINEQUERY_FIELD)) {
this.inlineQuery = new InlineQuery(jsonObject.getJSONObject(INLINEQUERY_FIELD));
}
if (jsonObject.has(CHOSENINLINEQUERY_FIELD)) {
this.chosenInlineQuery = new ChosenInlineQuery(jsonObject.getJSONObject(CHOSENINLINEQUERY_FIELD));
}
if (jsonObject.has(CALLBACKQUERY_FIELD)) {
callbackQuery = new CallbackQuery(jsonObject.getJSONObject(CALLBACKQUERY_FIELD));
}
if (jsonObject.has(EDITEDMESSAGE_FIELD)){
editedMessage = new Message(jsonObject.getJSONObject(EDITEDMESSAGE_FIELD));
}
}
public Integer getUpdateId() {
return updateId;
}
@ -106,33 +81,6 @@ public class Update implements IBotApiObject {
public boolean hasEditedMessage() {
return editedMessage != null;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(UPDATEID_FIELD, updateId);
if (message != null) {
gen.writeObjectField(MESSAGE_FIELD, message);
}
if (inlineQuery != null) {
gen.writeObjectField(INLINEQUERY_FIELD, inlineQuery);
}
if (chosenInlineQuery != null) {
gen.writeObjectField(CHOSENINLINEQUERY_FIELD, chosenInlineQuery);
}
if (callbackQuery != null) {
gen.writeObjectField(CALLBACKQUERY_FIELD, callbackQuery);
}
if (editedMessage != null) {
gen.writeObjectField(EDITEDMESSAGE_FIELD, editedMessage);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,12 +10,13 @@ import java.io.IOException;
* @brief This object represents a Telegram user or bot.
* @date 20 of June of 2015
*/
public class User implements IBotApiObject {
public class User implements BotApiObject {
private static final String ID_FIELD = "id";
private static final String FIRSTNAME_FIELD = "first_name";
private static final String LASTNAME_FIELD = "last_name";
private static final String USERNAME_FIELD = "username";
@JsonProperty(ID_FIELD)
private Integer id; ///< Unique identifier for this user or bot
@JsonProperty(FIRSTNAME_FIELD)
@ -35,18 +30,6 @@ public class User implements IBotApiObject {
super();
}
public User(JSONObject jsonObject) {
super();
this.id = jsonObject.getInt(ID_FIELD);
this.firstName = jsonObject.getString(FIRSTNAME_FIELD);
if (jsonObject.has(LASTNAME_FIELD)) {
this.lastName = jsonObject.getString(LASTNAME_FIELD);
}
if (jsonObject.has(USERNAME_FIELD)) {
this.userName = jsonObject.getString(USERNAME_FIELD);
}
}
public Integer getId() {
return id;
}
@ -63,26 +46,6 @@ public class User implements IBotApiObject {
return userName;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(ID_FIELD, id);
gen.writeStringField(FIRSTNAME_FIELD, firstName);
if (lastName != null) {
gen.writeStringField(LASTNAME_FIELD, lastName);
}
if (userName != null) {
gen.writeStringField(USERNAME_FIELD, userName);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "User{" +

View File

@ -0,0 +1,44 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represent a user's profile pictures.
* @date 22 of June of 2015
*/
public class UserProfilePhotos implements BotApiObject {
private static final String TOTALCOUNT_FIELD = "total_count";
private static final String PHOTOS_FIELD = "photos";
@JsonProperty(TOTALCOUNT_FIELD)
private Integer totalCount; ///< Total number of profile pictures the target user has
@JsonProperty(PHOTOS_FIELD)
private List<List<PhotoSize>> photos; ///< Requested profile pictures (in up to 4 sizes each)
public UserProfilePhotos() {
super();
}
public Integer getTotalCount() {
return totalCount;
}
public List<List<PhotoSize>> getPhotos() {
return photos;
}
@Override
public String toString() {
return "UserProfilePhotos{" +
"totalCount=" + totalCount +
", photos=" + photos +
'}';
}
}

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,7 +10,7 @@ import java.io.IOException;
* @brief This object represents a venue.
* @date 10 of April of 2016
*/
public class Venue implements IBotApiObject {
public class Venue implements BotApiObject {
private static final String LOCATION_FIELD = "location";
private static final String TITLE_FIELD = "title";
private static final String ADDRESS_FIELD = "address";
@ -31,21 +25,10 @@ public class Venue implements IBotApiObject {
@JsonProperty(FOURSQUARE_ID_FIELD)
private String foursquareId; ///< Optional. Foursquare identifier of the venue
public Venue() {
super();
}
public Venue(JSONObject jsonObject) {
super();
location = new Location(jsonObject.getJSONObject(LOCATION_FIELD));
title = jsonObject.getString(TITLE_FIELD);
address = jsonObject.getString(ADDRESS_FIELD);
if (jsonObject.has(FOURSQUARE_ID_FIELD)) {
foursquareId = jsonObject.getString(FOURSQUARE_ID_FIELD);
}
}
public Location getLocation() {
return location;
}
@ -62,24 +45,6 @@ public class Venue implements IBotApiObject {
return foursquareId;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeObjectField(LOCATION_FIELD, location);
gen.writeStringField(TITLE_FIELD, title);
gen.writeStringField(ADDRESS_FIELD, address);
if (foursquareId != null) {
gen.writeStringField(FOURSQUARE_ID_FIELD, foursquareId);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Venue{" +

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,7 +10,7 @@ import java.io.IOException;
* @brief This object represents a video file.
* @date 20 of June of 2015
*/
public class Video implements IBotApiObject {
public class Video implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String WIDTH_FIELD = "width";
@ -25,6 +19,7 @@ public class Video implements IBotApiObject {
private static final String THUMB_FIELD = "thumb";
private static final String MIMETYPE_FIELD = "mime_type";
private static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(WIDTH_FIELD)
@ -44,22 +39,6 @@ public class Video implements IBotApiObject {
super();
}
public Video(JSONObject jsonObject) {
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
this.duration = jsonObject.getInt(DURATION_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -88,31 +67,6 @@ public class Video implements IBotApiObject {
return fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
gen.writeNumberField(DURATION_FIELD, duration);
if (thumb != null) {
gen.writeObjectField(THUMB_FIELD, thumb);
}
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Video{" +

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,11 +10,12 @@ import java.io.IOException;
* @brief This object represents a voice note
* @date 16 of July of 2015
*/
public class Voice implements IBotApiObject {
public class Voice implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String DURATION_FIELD = "duration";
private static final String MIMETYPE_FIELD = "mime_type";
private static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(DURATION_FIELD)
@ -34,18 +29,6 @@ public class Voice implements IBotApiObject {
super();
}
public Voice(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.duration = jsonObject.getInt(DURATION_FIELD);
if (jsonObject.has(MIMETYPE_FIELD)) {
this.mimeType = jsonObject.getString(MIMETYPE_FIELD);
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -62,26 +45,6 @@ public class Voice implements IBotApiObject {
return fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(DURATION_FIELD, duration);
if (mimeType != null) {
gen.writeStringField(MIMETYPE_FIELD, mimeType);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Voice{" +

View File

@ -1,14 +1,8 @@
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
@ -16,7 +10,7 @@ import java.io.IOException;
* @brief Contains information about the current status of a webhook.
* @date 12 of August of 2016
*/
public class WebhookInfo implements IBotApiObject {
public class WebhookInfo implements BotApiObject {
private static final String URL_FIELD = "url";
private static final String HASCUSTOMCERTIFICATE_FIELD = "has_custom_certificate";
@ -35,21 +29,8 @@ public class WebhookInfo implements IBotApiObject {
@JsonProperty(LASTERRORMESSAGE_FIELD)
private String lastErrorMessage; ///< Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
public WebhookInfo() {
}
public WebhookInfo(JSONObject object) {
url = object.getString(URL_FIELD);
hasCustomCertificate = object.getBoolean(HASCUSTOMCERTIFICATE_FIELD);
pendingUpdatesCount = object.getInt(PENDINGUPDATESCOUNT_FIELD);
if (object.has(LASTERRORDATE_FIELD)) {
lastErrorDate = object.getInt(LASTERRORDATE_FIELD);
}
if (object.has(LASTERRORMESSAGE_FIELD)) {
lastErrorMessage = object.getString(LASTERRORMESSAGE_FIELD);
}
super();
}
public String getUrl() {
@ -71,24 +52,4 @@ public class WebhookInfo implements IBotApiObject {
public String getLastErrorMessage() {
return lastErrorMessage;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(URL_FIELD, url);
gen.writeBooleanField(HASCUSTOMCERTIFICATE_FIELD, hasCustomCertificate);
gen.writeNumberField(PENDINGUPDATESCOUNT_FIELD, pendingUpdatesCount);
if (lastErrorDate != null) {
gen.writeNumberField(LASTERRORDATE_FIELD, lastErrorDate);
}
if (lastErrorMessage != null) {
gen.writeStringField(LASTERRORMESSAGE_FIELD, lastErrorMessage);
}
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
}

View File

@ -17,23 +17,17 @@
package org.telegram.telegrambots.api.objects.games;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.objects.PhotoSize;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 2.4
* @brief This object represents an animation file.
* @date 27 of September of 2016
*/
public class Animation implements IBotApiObject {
public class Animation implements BotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String THUMB_FIELD = "thumb";
private static final String FILENAME_FIELD = "file_name";
@ -55,23 +49,6 @@ public class Animation implements IBotApiObject {
super();
}
public Animation(JSONObject object) {
super();
fileId = object.getString(FILEID_FIELD);
if (object.has(THUMB_FIELD)) {
thumb = new PhotoSize(object.getJSONObject(THUMB_FIELD));
}
if (object.has(FILENAME_FIELD)) {
fileName = object.getString(FILENAME_FIELD);
}
if (object.has(MIMETYPE_FIELD)) {
mimetype = object.getString(MIMETYPE_FIELD);
}
if (object.has(FILESIZE_FIELD)) {
fileSize = object.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
@ -92,31 +69,6 @@ public class Animation implements IBotApiObject {
return fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
if (thumb != null) {
gen.writeObjectField(THUMB_FIELD, thumb);
}
if (fileName != null) {
gen.writeStringField(FILENAME_FIELD, fileName);
}
if (mimetype != null) {
gen.writeStringField(MIMETYPE_FIELD, mimetype);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Animation{" +

View File

@ -0,0 +1,37 @@
/*
* This file is part of TelegramBots.
*
* TelegramBots is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TelegramBots is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TelegramBots. If not, see <http://www.gnu.org/licenses/>.
*/
package org.telegram.telegrambots.api.objects.games;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
/**
* @author Ruben Bermudez
* @version 2.4
* @brief A placeholder, currently holds no information. Use BotFather to set up your game.
* @date 16 of September of 2016
*/
public class CallbackGame implements BotApiObject {
public CallbackGame() {
super();
}
@Override
public String toString() {
return "CallbackGame{}";
}
}

View File

@ -17,18 +17,11 @@
package org.telegram.telegrambots.api.objects.games;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.objects.MessageEntity;
import org.telegram.telegrambots.api.objects.PhotoSize;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
@ -38,7 +31,8 @@ import java.util.List;
* Use BotFather to create and edit games, their short names will act as unique identifiers.
* @date 27 of September of 2016
*/
public class Game implements IBotApiObject {
public class Game implements BotApiObject {
private static final String TITLE_FIELD = "title";
private static final String DESCRIPTION_FIELD = "description";
private static final String PHOTO_FIELD = "photo";
@ -52,19 +46,19 @@ public class Game implements IBotApiObject {
private String description; ///< Description of the game
@JsonProperty(PHOTO_FIELD)
private List<PhotoSize> photo; ///< Photo
@JsonProperty(TEXT_FIELD)
/**
* Optional. Brief description of the game or high scores included in the game message.
* Can be automatically edited to include current high scores for the game
* when the bot calls setGameScore, or manually edited using editMessageText.
* 0-4096 characters.
*/
@JsonProperty(TEXT_FIELD)
private String text;
@JsonProperty(TEXTENTITIES_FIELD)
/**
* Optional. Special entities that appear in text, such as usernames,
* URLs, bot commands, etc.
*/
@JsonProperty(TEXTENTITIES_FIELD)
private List<MessageEntity> entities;
@JsonProperty(ANIMATION_FIELD)
private Animation animation; ///< Optional. Animation
@ -73,30 +67,6 @@ public class Game implements IBotApiObject {
super();
}
public Game(JSONObject object) {
super();
title = object.getString(TITLE_FIELD);
description = object.getString(DESCRIPTION_FIELD);
this.photo = new ArrayList<>();
JSONArray photos = object.getJSONArray(PHOTO_FIELD);
for (int i = 0; i < photos.length(); i++) {
this.photo.add(new PhotoSize(photos.getJSONObject(i)));
}
if (object.has(TEXT_FIELD)) {
text = object.getString(TEXT_FIELD);
}
if (object.has(TEXTENTITIES_FIELD)) {
this.entities = new ArrayList<>();
JSONArray entities = object.getJSONArray(TEXTENTITIES_FIELD);
for (int i = 0; i < entities.length(); i++) {
this.entities.add(new MessageEntity(entities.getJSONObject(i)));
}
}
if (object.has(ANIMATION_FIELD)) {
animation = new Animation(object.getJSONObject(ANIMATION_FIELD));
}
}
public String getTitle() {
return title;
}
@ -125,38 +95,6 @@ public class Game implements IBotApiObject {
return entities;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(TITLE_FIELD, title);
gen.writeStringField(DESCRIPTION_FIELD, description);
gen.writeArrayFieldStart(PHOTO_FIELD);
for (PhotoSize photoSize : photo) {
gen.writeObject(photoSize);
}
gen.writeEndArray();
if (animation != null) {
gen.writeObjectField(ANIMATION_FIELD, animation);
}
if (text != null) {
gen.writeStringField(TEXT_FIELD, text);
}
if (entities != null) {
gen.writeArrayFieldStart(TEXTENTITIES_FIELD);
for (MessageEntity entity : entities) {
gen.writeObject(entity);
}
gen.writeEndArray();
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Game{" +

View File

@ -18,23 +18,17 @@
package org.telegram.telegrambots.api.objects.games;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.objects.User;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents one row of a game high scores table
* @date 25 of September of 2016
*/
public class GameHighScore implements IBotApiObject {
public class GameHighScore implements BotApiObject {
private static final String POSITION_FIELD = "position";
private static final String USER_FIELD = "user";
private static final String SCORE_FIELD = "score";
@ -46,12 +40,6 @@ public class GameHighScore implements IBotApiObject {
@JsonProperty(SCORE_FIELD)
private Integer score; ///< Score
public GameHighScore(JSONObject object) {
position = object.getInt(POSITION_FIELD);
user = new User(object.getJSONObject(USER_FIELD));
score = object.getInt(SCORE_FIELD);
}
public Integer getPosition() {
return position;
}
@ -64,21 +52,6 @@ public class GameHighScore implements IBotApiObject {
return score;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeNumberField(POSITION_FIELD, position);
gen.writeObjectField(USER_FIELD, user);
gen.writeNumberField(SCORE_FIELD, score);
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "GameHighScore{" +

Some files were not shown because too many files have changed in this diff Show More