Compare commits

..

No commits in common. "master" and "dev" have entirely different histories.
master ... dev

363 changed files with 3873 additions and 12899 deletions

View File

@ -1,10 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = false
max_line_length = 120
tab_width = 4

View File

@ -1,38 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

2
.gitignore vendored
View File

@ -43,5 +43,3 @@ copyright/
#File System specific files
.DS_Store
telegrambots/.factorypath

View File

@ -27,18 +27,18 @@ Just import add the library to your project with one of these options:
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
```
2. Using Gradle:
```gradle
implementation 'org.telegram:telegrambots:6.8.0'
implementation 'org.telegram:telegrambots:5.5.0'
```
3. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/6.8.0)
4. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/6.8.0)
3. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/5.5.0)
4. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/5.5.0)
In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`.

View File

@ -1,47 +1,5 @@
### <a id="6.8.0"></a>6.8.0 ###
1. Update Api version [6.8](https://core.telegram.org/bots/api-changelog#august-18-2023)
2. Fix #1254
### <a id="6.7.0"></a>6.7.0 ###
1. Update Api version [6.7](https://core.telegram.org/bots/api-changelog#april-21-2023)
**[[How to update to version 6.7.0|How-To-Update#6.7.0]]**
### <a id="6.6.0"></a>6.6.0 ###
1. Update Api version [6.6](https://core.telegram.org/bots/api-changelog#march-9-2023)
### <a id="6.5.0"></a>6.5.0 ###
1. Update Api version [6.5](https://core.telegram.org/bots/api-changelog#february-3-2023)
### <a id="6.4.0"></a>6.4.0 ###
1. Update Api version [6.4](https://core.telegram.org/bots/api-changelog#december-30-2022)
2. Bug fixing: #1159
### <a id="6.3.0"></a>6.3.0 ###
1. Update Api version [6.3](https://core.telegram.org/bots/api-changelog#November-5-2022)
2. Bug fixing: #1116
### <a id="6.1.0"></a>6.1.0 ###
1. Update Api version [6.1](https://core.telegram.org/bots/api-changelog#june-20-2022)
2. Add support for Long when setting the chatId: #1065
3. Bug fixing: #755, #1036, #1055, #1060, #1064, #1065, #1067, #1069, #1070, #1086, #1088
**[[How to update to version 6.1.0|How-To-Update#6.1.0]]**
### <a id="6.0.1"></a>6.0.1 ###
1. Update Api version [6.0](https://core.telegram.org/bots/api-changelog#april-16-2022)
2. Removed all deprecated methods/classes with this major upgrade
### <a id="5.7.1"></a>5.7.1 ###
1. Update Api version [5.7](https://core.telegram.org/bots/api-changelog#january-31-2022)
2. Spring boot 2.5.8
3. Bug Fixing: #1023
### <a id="5.6.0"></a>5.6.0 ###
1. Update Api version [5.6](https://core.telegram.org/bots/api-changelog#december-30-2021)
### <a id="5.5.0"></a>5.5.0 ###
1. Update Api version [5.5](https://core.telegram.org/bots/api-changelog#december-7-2021)
1. Update Api version [5.5](https://core.telegram.org/bots/api#december-7-2021)
### <a id="5.4.0.1"></a>5.4.0.1 ###
1. Bug fixing: #999, #1000

View File

@ -2,7 +2,6 @@
* [How to display ChatActions like "typing" or "recording a voice message"?](#how_to_sendchataction)
* [How to send photos?](#how_to_send_photos)
* [How do I send photos by file_id?](#how_to_send_photos_file_id)
* [How to send stickers?](#how_to_send_stickers)
* [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)
@ -108,7 +107,7 @@ if (update.hasMessage() && update.getMessage().hasText()) {
## <a id="how_to_send_photos"></a>How to send photos? ##
There are several methods 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:
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) {
@ -156,34 +155,7 @@ There are several methods to send a photo to an user using `sendPhoto` method: W
}
}
```
## <a id="how_to_send_stickers"></a>How to send stickers? ##
There are several ways to send a sticker, but now we will use `file_id` and `url`.
`file_id`: To get the *file_id*, you have to send your sticker to the [**Get Sticker ID**](https://t.me/idstickerbot?do=open_link) bot and then you will receive a string.
`url`: All you need to have is an link to the sticker in `.webp` format, like [**This**](https://www.gstatic.com/webp/gallery/5.webp).
#### Implementation
Just call the method below in your `onUpdateReceived(Update update)` method.
```java
// Sticker_file_id is received from @idstickerbot bot
private void StickerSender(Update update, String Sticker_file_id) {
//the ChatId that we received form Update class
String ChatId = update.getMessage().getChatId().toString();
// Create an InputFile containing Sticker's file_id or URL
InputFile StickerFile = new InputFile(Sticker_file_id);
// Create a SendSticker object using the ChatId and StickerFile
SendSticker TheSticker = new SendSticker(ChatId, StickerFile);
// Will reply the sticker to the message sent
//TheSticker.setReplyToMessageId(update.getMessage().getMessageId());
try { // Execute the method
execute(TheSticker);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
```
## <a id="how_to_send_photos_file_id"></a>How to send photo by its file_id? ##
In this example we will check if user sends to bot a photo, if it is, get Photo's file_id and send this photo by file_id to user.

View File

@ -1,7 +1,7 @@
So, youd like to create your own Telegram bot with TelegramBots? Then Let's get You started quickly.
So, you just wanna program your own Telegram bot with TelegramBots? Let's see the fast version.
## Grab the library
First you need to acquire the library and add it to your project. There are several ways to do this:
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:
@ -11,23 +11,23 @@ First you need to acquire the library and add it to your project. There are seve
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
```
* With **Gradle**:
```gradle
implementation 'org.telegram:telegrambots:6.8.0'
implementation 'org.telegram:telegrambots:5.5.0'
```
2. Don't like the **Maven Central Repository**? It can also be grabbed 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 fetch the latest 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)
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)
## Building your first bot
Now that you have the library, you 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):
## 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. **Creating your actual bot:**
1. **Create your actual bot:**
The class must extends `TelegramLongPollingBot` and implement necessary methods:
```java
@ -99,7 +99,7 @@ Now that you have the library, you can start coding. There are few steps to foll
```
2. **Instantiate `TelegramBotsApi` and register our new bot:**
For this part, we need to actually perform 2 steps: _Instantiate Telegram Api_ and _Register our Bot_. In this tutorial, we are going to do it in our `main` method:
For this part, we need to actually perform 2 steps: _Instantiate Telegram Api_ and _Register our Bot_. In this tutorial, we are going to make it in our `main` method:
```java

View File

@ -1,14 +1,3 @@
### <a id="6.8.0"></a>To version 6.8.0 ###
1. Api methods with thumbnails have changed the field, use getThumbnail()/setThumbnail() instead of getThumb()/setThumb()
2. In `AddStickerToSet`/`CreateNewStickerSet`/`UploadStickerFile`/etc, use field `sticker` instead of the deprecated fields.
3. `ChatMember` has more details permissions, use those instead of the legacy general ones.
4. All classes with mandatory fields will lose the default no-arg constructor in the future.
5. In `AnswerInlineQuery`, start using the `button` field instead of deprecated parameters.
### <a id="6.1.0"></a>To version 6.1.0 ###
1. As per API guidelines, FileSize can now have 64 bits size, hence they are now using Long datatype instead of Integer.
2. Methods accept chatId as Long or String.
### <a id="5.3.0"></a>To version 5.3.0 ###
1. As per API guidelines, ChatMember method has been divided in different classed.
Where used in your code, replace old import with new one

View File

@ -2,48 +2,41 @@
You have around 100 abilities in your bot and you're looking for a way to refactor that mess into more modular classes. `AbillityExtension` is here to support just that! It's not a secret that AbilityBot uses refactoring backstage to be able to construct all of your abilities and map them accordingly. However, AbilityBot searches initially for all methods that return an `AbilityExtension` type. Then, those extensions will be used to search for declared abilities. Here's an example.
```java
public class MrGoodGuy implements AbilityExtension {
private AbilityBot extensionUser;
public MrGoodGuy(AbilityBot extensionUser) { this.extensionUser = extensionUser; }
public Ability nice() {
return Ability.builder()
.name("nice")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> extensionUser.silent().send("You're awesome!", ctx.chatId())
);
}
public Ability nice() {
return Ability.builder()
.name("nice")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> silent.send("You're awesome!", ctx.chatId())
);
}
}
public class MrBadGuy implements AbilityExtension {
private AbilityBot extensionUser;
public Ability notnice() {
return Ability.builder()
.name("notnice")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> silent.send("You're horrible!", ctx.chatId())
);
}
}
public MrBadGuy(AbilityBot extensionUser) { this.extensionUser = extensionUser; }
public Ability notnice() {
return Ability.builder()
.name("notnice")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> extensionUser.silent().send("You're horrible!", ctx.chatId())
);
}
}
public class YourAwesomeBot implements AbilityBot {
public class YourAwesomeBot implements AbilityBot {
// Constructor for your bot
public AbilityExtension goodGuy() {
return new MrGoodGuy(this);
return new MrGoodGuy();
}
public AbilityExtension badGuy() {
return new MrBadGuy(this);
return new MrBadGuy();
}
// Override creatorId
}
}
```
It's also possible to add extensions in the constructor by using the `addExtension()` or `addExtensions()` method:
@ -52,10 +45,10 @@ It's also possible to add extensions in the constructor by using the `addExtensi
public class YourAwesomeBot implements AbilityBot {
public YourAwesomeBot() {
super(/* pass required args ... */);
addExtensions(new MrGoodGuy(this), new MrBadGuy(this));
super(/* pass required args ... */);
addExtensions(new MrGoodGuy(), new MrBadGuy());
}
// Override creatorId
}
}
```

View File

@ -29,7 +29,7 @@ As an example, if you want to restrict the updates to photos only, then you may
```java
@Override
public boolean checkGlobalFlags(Update update) {
return Flag.PHOTO.test(update);
return Flag.PHOTO;
}
```

View File

@ -9,12 +9,12 @@ As with any Java project, you will need to set your dependencies.
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-abilities</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
```
* **Gradle**
```gradle
implementation 'org.telegram:telegrambots-abilities:6.8.0'
implementation 'org.telegram:telegrambots-abilities:5.5.0'
```
* [JitPack](https://jitpack.io/#rubenlagus/TelegramBots)
@ -109,8 +109,6 @@ Since you've implemented an AbilityBot, you get **factory abilities** as well. T
* /demote @username - demotes bot admin to user
* /ban @username - bans the user from accessing your bot commands and features
* /unban @username - lifts the ban from the user
* /stats - displays how many times were your abilities called
* **This command returns empty String by default.** To use this command, add ```.setStatsEnabled(true)``` to your abilities. You'll then be able to view how many times each of them was called.
## Conclusion
Congratulation on creating your first AbilityBot. What's next? So far we've only considered the case of commands, but what about images and inline replies? AbilityBots can also handle that! Oh and, did you know that all ability bots have an embedded database that you can use?

95
pom.xml
View File

@ -4,10 +4,10 @@
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.warp</groupId>
<artifactId>bots</artifactId>
<groupId>org.telegram</groupId>
<artifactId>Bots</artifactId>
<packaging>pom</packaging>
<version>6.8.0</version>
<version>5.5.0</version>
<modules>
<module>telegrambots</module>
@ -21,7 +21,7 @@
<licenses>
<license>
<name>MIT License</name>
<url>https://www.opensource.org/licenses/mit-license.php</url>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
@ -51,34 +51,32 @@
</developers>
<distributionManagement>
<repository>
<id>mchv-release-distribution</id>
<name>MCHV Release Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv</url>
</repository>
<snapshotRepository>
<id>mchv-snapshot-distribution</id>
<name>MCHV Snapshot Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv-snapshot</url>
<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>
<java.version>11</java.version>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>8</maven.compiler.release>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<junit.version>5.9.1</junit.version>
<mockito.version>4.8.1</mockito.version>
<mockitojupiter.version>4.8.1</mockitojupiter.version>
<jacksonanotation.version>2.14.2</jacksonanotation.version>
<jackson.version>2.14.2</jackson.version>
<slf4j.version>2.0.3</slf4j.version>
<jakarta.annotation.version>2.1.1</jakarta.annotation.version>
<lombok.version>1.18.28</lombok.version>
<guava.version>32.0.0-jre</guava.version>
<commons.version>3.12.0</commons.version>
<junit.version>5.7.1</junit.version>
<mockito.version>3.6.0</mockito.version>
<mockitojupiter.version>3.6.0</mockitojupiter.version>
<jacksonanotation.version>2.11.3</jacksonanotation.version>
<jackson.version>2.11.3</jackson.version>
<json.version>20180813</json.version>
<slf4j.version>1.7.30</slf4j.version>
<jakarta.annotation.version>1.3.5</jakarta.annotation.version>
<lombok.version>1.18.16</lombok.version>
<guava.version>30.0-jre</guava.version>
</properties>
<dependencyManagement>
@ -95,6 +93,18 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
@ -107,12 +117,12 @@
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jakarta-xmlbind-annotations</artifactId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>${jacksonanotation.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jakarta.rs</groupId>
<artifactId>jackson-jakarta-rs-json-provider</artifactId>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jacksonanotation.version}</version>
</dependency>
<dependency>
@ -120,22 +130,16 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.version}</version>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<!-- Included to enforce common version-->
<dependency>
<groupId>jakarta.annotation</groupId>
@ -179,12 +183,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.0</version>
<version>3.8.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
@ -198,7 +202,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.0</version>
<version>3.1.1</version>
<executions>
<execution>
<id>aggregate</id>
@ -213,10 +217,21 @@
<javadocExecutable>${java.home}/bin/javadoc</javadocExecutable>
</configuration>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<version>3.0.0-M2</version>
<executions>
<execution>
<id>enforce-versions</id>
@ -227,7 +242,7 @@
</executions>
<configuration>
<rules>
<DependencyConvergence/>
<DependencyConvergence />
</rules>
</configuration>
</plugin>

View File

@ -18,14 +18,14 @@ Usage
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-abilities</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
```
**Gradle**
```gradle
implementation 'org.telegram:telegrambots-abilities:6.8.0'
implementation 'org.telegram:telegrambots-abilities:5.5.0'
```
**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v5.0.1)

View File

@ -5,9 +5,9 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.warp</groupId>
<artifactId>bots</artifactId>
<version>6.8.0</version>
<groupId>org.telegram</groupId>
<artifactId>Bots</artifactId>
<version>5.5.0</version>
</parent>
<artifactId>telegrambots-abilities</artifactId>
@ -57,45 +57,39 @@
</licenses>
<distributionManagement>
<repository>
<id>mchv-release-distribution</id>
<name>MCHV Release Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv</url>
</repository>
<snapshotRepository>
<id>mchv-snapshot-distribution</id>
<name>MCHV Snapshot Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv-snapshot</url>
<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>
<java.version>11</java.version>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>8</maven.compiler.release>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<commonslang.version>3.12.0</commonslang.version>
<commonslang.version>3.11</commonslang.version>
<mapdb.version>3.0.8</mapdb.version>
</properties>
<dependencies>
<dependency>
<groupId>org.warp</groupId>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commonslang.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.mapdb</groupId>
@ -120,7 +114,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<version>3.0.0-M3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -136,9 +130,20 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</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.2.0</version>
<version>3.1.0</version>
<executions>
<execution>
<id>clean-project</id>
@ -151,7 +156,7 @@
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
@ -170,7 +175,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -182,7 +187,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.0</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -197,7 +202,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>0.8.4</version>
<executions>
<execution>
<goals>
@ -216,7 +221,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M2</version>
<executions>
<execution>
<id>enforce-versions</id>
@ -234,7 +239,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<executions>
<execution>
<id>copy</id>
@ -248,18 +253,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>

View File

@ -1,13 +0,0 @@
module telegrambots.abilities {
requires telegrambots;
requires telegrambots.meta;
requires com.google.common;
requires org.slf4j;
requires com.fasterxml.jackson.core;
requires com.fasterxml.jackson.databind;
requires mapdb;
requires org.apache.commons.lang3;
requires annotations;
requires org.apache.commons.io;
requires static com.fasterxml.jackson.annotation;
}

View File

@ -1,18 +1,12 @@
package org.telegram.abilitybots.api.bot;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.*;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Ability;
import org.telegram.abilitybots.api.objects.Locality;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.abilitybots.api.objects.Privacy;
import org.telegram.abilitybots.api.objects.Reply;
import org.telegram.abilitybots.api.objects.ReplyCollection;
import org.telegram.abilitybots.api.objects.Stats;
import org.telegram.abilitybots.api.objects.*;
import org.telegram.abilitybots.api.sender.DefaultSender;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.sender.SilentSender;
@ -32,12 +26,7 @@ import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberOwner;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.function.BiFunction;
import java.util.function.Function;
@ -55,25 +44,12 @@ import static java.util.Optional.ofNullable;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;
import static java.util.stream.Collectors.toSet;
import static org.telegram.abilitybots.api.objects.Locality.ALL;
import static org.telegram.abilitybots.api.objects.Locality.GROUP;
import static org.telegram.abilitybots.api.objects.Locality.USER;
import static org.telegram.abilitybots.api.objects.Locality.*;
import static org.telegram.abilitybots.api.objects.MessageContext.newContext;
import static org.telegram.abilitybots.api.objects.Privacy.ADMIN;
import static org.telegram.abilitybots.api.objects.Privacy.CREATOR;
import static org.telegram.abilitybots.api.objects.Privacy.GROUP_ADMIN;
import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC;
import static org.telegram.abilitybots.api.objects.Privacy.*;
import static org.telegram.abilitybots.api.objects.Stats.createStats;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.CHECK_INPUT_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.CHECK_LOCALITY_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.CHECK_PRIVACY_FAIL;
import static org.telegram.abilitybots.api.util.AbilityUtils.EMPTY_USER;
import static org.telegram.abilitybots.api.util.AbilityUtils.getChatId;
import static org.telegram.abilitybots.api.util.AbilityUtils.getLocalizedMessage;
import static org.telegram.abilitybots.api.util.AbilityUtils.getUser;
import static org.telegram.abilitybots.api.util.AbilityUtils.isGroupUpdate;
import static org.telegram.abilitybots.api.util.AbilityUtils.isSuperGroupUpdate;
import static org.telegram.abilitybots.api.util.AbilityUtils.isUserMessage;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.*;
import static org.telegram.abilitybots.api.util.AbilityUtils.*;
/**
* The <b>father</b> of all ability bots. Bots that need to utilize abilities need to extend this bot.
@ -107,7 +83,7 @@ import static org.telegram.abilitybots.api.util.AbilityUtils.isUserMessage;
*
* @author Abbas Abou Daya
*/
@SuppressWarnings({"UnusedReturnValue", "WeakerAccess", "unused", "ConstantConditions"})
@SuppressWarnings({"ConfusingArgumentToVarargsMethod", "UnusedReturnValue", "WeakerAccess", "unused", "ConstantConditions"})
public abstract class BaseAbilityBot extends DefaultAbsSender implements AbilityExtension {
private static final Logger log = LoggerFactory.getLogger(BaseAbilityBot.class);
@ -127,7 +103,8 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
// Ability toggle
private final AbilityToggle toggle;
// Bot username
// Bot token and username
private final String botToken;
private final String botUsername;
// Ability registry
@ -141,8 +118,9 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
public abstract long creatorId();
protected BaseAbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) {
super(botOptions, botToken);
super(botOptions);
this.botToken = botToken;
this.botUsername = botUsername;
this.db = db;
this.toggle = toggle;
@ -262,6 +240,10 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
log.info(format("[%s] Processing of update [%s] ended at %s%n---> Processing time: [%d ms] <---%n", botUsername, update.getUpdateId(), now(), processingTime));
}
public String getBotToken() {
return botToken;
}
public String getBotUsername() {
return botUsername;
}
@ -278,7 +260,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
}
public boolean isGroupAdmin(long chatId, long id) {
GetChatAdministrators admins = GetChatAdministrators.builder().chatId(chatId).build();
GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build();
return silent.execute(admins)
.orElse(new ArrayList<>())
.stream()
@ -691,13 +673,8 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
try {
return callable.call();
} catch(Exception ex) {
String msg = format("Reply [%s] failed to check for conditions. " +
"Make sure you're safeguarding against all possible updates.", name);
if (log.isDebugEnabled()) {
log.error(msg, ex);
} else {
log.error(msg);
}
log.error(format("Reply [%s] failed to check for conditions. " +
"Make sure you're safeguarding against all possible updates.", name));
}
return false;
}

View File

@ -224,7 +224,7 @@ public final class DefaultAbilities implements AbilityExtension {
printStream.print(bot.db.backup());
bot.sender.sendDocument(SendDocument.builder()
.document(new InputFile(backup))
.chatId(ctx.chatId())
.chatId(ctx.chatId().toString())
.build()
);
} catch (FileNotFoundException e) {

View File

@ -215,6 +215,16 @@ public final class Ability {
return this;
}
/**
* @deprecated Please use {@link #reply(BiConsumer, Predicate[])}
*/
@Deprecated
@SafeVarargs
public final AbilityBuilder reply(Consumer<Update> action, Predicate<Update>... conditions) {
replies.add(Reply.of(action, conditions));
return this;
}
@SafeVarargs
public final AbilityBuilder reply(BiConsumer<BaseAbilityBot, Update> action, Predicate<Update>... conditions) {
replies.add(Reply.of(action, conditions));

View File

@ -3,7 +3,7 @@ package org.telegram.abilitybots.api.objects;
import org.telegram.abilitybots.api.objects.Ability.AbilityBuilder;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import static java.util.Objects.nonNull;
@ -11,7 +11,7 @@ import static java.util.Objects.nonNull;
/**
* Flags are an conditions that are applied on an {@link Update}.
* <p>
* They can be used on {@link AbilityBuilder#flag(Predicate[])} and on the post conditions in {@link AbilityBuilder#reply(BiConsumer, Predicate[])}.
* They can be used on {@link AbilityBuilder#flag(Predicate[])} and on the post conditions in {@link AbilityBuilder#reply(Consumer, Predicate[])}.
*
* @author Abbas Abou Daya
*/

View File

@ -9,6 +9,7 @@ import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
@ -17,7 +18,7 @@ import static com.google.common.collect.Lists.newArrayList;
/**
* A reply consists of update conditionals and an action to be applied on the update.
* <p>
* If an update satisfies the {@link Reply#conditions} set by the reply, then it's safe to {@link Reply#actOn(BaseAbilityBot, Update)}.
* If an update satisfies the {@link Reply#conditions} set by the reply, then it's safe to {@link Reply#actOn(Update)}.
*
* @author Abbas Abou Daya
*/
@ -42,6 +43,29 @@ public class Reply {
}
}
/**
* @deprecated Please use {@link #Reply(List, BiConsumer)}
*/
@Deprecated
Reply(List<Predicate<Update>> conditions, Consumer<Update> action) {
this.conditions = ImmutableList.<Predicate<Update>>builder()
.addAll(conditions)
.build();
this.action = ((baseAbilityBot, update) -> action.accept(update));
statsEnabled = false;
}
/**
* @deprecated Please use {@link #Reply(List, BiConsumer, String)}
*/
@Deprecated
Reply(List<Predicate<Update>> conditions, Consumer<Update> action, String name) {
this(conditions, action);
if (Objects.nonNull(name)) {
enableStats(name);
}
}
public static Reply of(BiConsumer<BaseAbilityBot, Update> action, List<Predicate<Update>> conditions) {
return new Reply(conditions, action);
}
@ -51,6 +75,23 @@ public class Reply {
return Reply.of(action, newArrayList(conditions));
}
/**
* @deprecated Please use {@link #of(BiConsumer, List)}
*/
@Deprecated
public static Reply of(Consumer<Update> action, List<Predicate<Update>> conditions) {
return new Reply(conditions, action);
}
/**
* @deprecated Please use {@link #of(BiConsumer, Predicate[])}
*/
@Deprecated
@SafeVarargs
public static Reply of(Consumer<Update> action, Predicate<Update>... conditions) {
return Reply.of(action, newArrayList(conditions));
}
public boolean isOkFor(Update update) {
// The following variable is required to avoid bug #JDK-8044546
BiFunction<Boolean, Predicate<Update>, Boolean> stateAnd = (state, cond) -> state && cond.test(update);

View File

@ -12,6 +12,7 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
@ -64,6 +65,15 @@ public class ReplyFlow extends Reply {
this(db, replyCounter.getAndIncrement());
}
/**
* @deprecated Please use {@link #action(BiConsumer)}
*/
@Deprecated
public ReplyFlowBuilder action(Consumer<Update> action) {
this.action = (bot, update) -> action.accept(update);
return this;
}
public ReplyFlowBuilder action(BiConsumer<BaseAbilityBot, Update> action) {
this.action = action;
return this;

View File

@ -3,6 +3,7 @@ package org.telegram.abilitybots.api.objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import org.json.JSONPropertyIgnore;
import java.io.Serializable;
import java.util.Objects;

View File

@ -30,9 +30,9 @@ public interface MessageSender {
Boolean addStickerToSet(AddStickerToSet addStickerToSet) throws TelegramApiException;
Boolean createNewStickerSet(CreateNewStickerSet createNewStickerSet) throws TelegramApiException;
public Boolean createNewStickerSet(CreateNewStickerSet createNewStickerSet) throws TelegramApiException;
File uploadStickerFile(UploadStickerFile uploadStickerFile) throws TelegramApiException;
public File uploadStickerFile(UploadStickerFile uploadStickerFile) throws TelegramApiException;
Boolean setChatPhoto(SetChatPhoto setChatPhoto) throws TelegramApiException;

View File

@ -38,7 +38,7 @@ public class SilentSender {
public Optional<Message> forceReply(String message, long id) {
SendMessage msg = new SendMessage();
msg.setText(message);
msg.setChatId(id);
msg.setChatId(Long.toString(id));
ForceReplyKeyboard kb = new ForceReplyKeyboard();
kb.setForceReply(true);
kb.setSelective(true);
@ -67,7 +67,7 @@ public class SilentSender {
private Optional<Message> doSendMessage(String txt, long groupId, boolean format) {
SendMessage smsg = new SendMessage();
smsg.setChatId(groupId);
smsg.setChatId(Long.toString(groupId));
smsg.setText(txt);
smsg.enableMarkdown(format);

View File

@ -4,11 +4,10 @@ import org.telegram.abilitybots.api.objects.Ability;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* This custom toggle can be used to customize default abilities supplied by the library. Users can call {@link CustomToggle#toggle} to
* rename the default abilities or {@link CustomToggle#turnOff} to simply turn off the said ability.
* rename the default abilites or {@link CustomToggle#turnOff} to simply turn off the said ability.
*/
public class CustomToggle implements AbilityToggle {
public static final String OFF = "turn_off_base_ability";
@ -54,76 +53,4 @@ public class CustomToggle implements AbilityToggle {
baseMapping.put(ability, OFF);
return this;
}
/**
* @param properties the abilities toggle definition
* @return the toggle instance
*/
public CustomToggle config(Properties properties) {
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
key = key.toLowerCase();
// compare with legal configuration names
for (Property p: Property.values()) {
if (key.equals(p.key())) {
String ability = key.split("\\.")[1];
if (key.contains("enabled") && value.equalsIgnoreCase("false")) {
this.turnOff(ability);
}else if (key.contains("toggle")) {
this.toggle(ability, value);
}
}
}
}
return this;
}
/**
* List of all the properties recognized by {@link CustomToggle}.
* Can be used to programmatically get, set or remove default values.
*/
public enum Property{
CLAIM_ENABLED("ability.claim.enabled"),
CLAIM_TOGGLE("ability.claim.toggle"),
BAN_ENABLED("ability.ban.enabled"),
BAN_TOGGLE("ability.ban.toggle"),
PROMOTE_ENABLED("ability.promote.enabled"),
PROMOTE_TOGGLE("ability.promote.toggle"),
DEMOTE_ENABLED("ability.demote.enabled"),
DEMOTE_TOGGLE("ability.demote.toggle"),
UNBAN_ENABLED("ability.unban.enabled"),
UNBAN_TOGGLE("ability.unban.toggle"),
BACKUP_ENABLED("ability.backup.enabled"),
BACKUP_TOGGLE("ability.backup.toggle"),
RECOVER_ENABLED("ability.recover.enabled"),
RECOVER_TOGGLE("ability.recover.toggle"),
COMMANDS_ENABLED("ability.commands.enabled"),
COMMANDS_TOGGLE("ability.commands.toggle"),
REPORT_ENABLED("ability.report.enabled"),
REPORT_TOGGLE("ability.report.toggle"),
STATS_ENABLED("ability.stats.enabled"),
STATS_TOGGLE("ability.stats.toggle")
;
private final String key;
Property (final String key){
this.key = key;
}
public String key() {
return key;
}
}
}

View File

@ -13,7 +13,6 @@ import java.util.ResourceBundle;
import java.util.StringJoiner;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import static java.util.ResourceBundle.Control.FORMAT_PROPERTIES;
import static java.util.ResourceBundle.Control.getNoFallbackControl;

View File

@ -1,13 +1,5 @@
package org.telegram.abilitybots.api.bot;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.telegram.abilitybots.api.bot.TestUtils.mockContext;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -17,9 +9,18 @@ import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.sender.SilentSender;
import org.telegram.telegrambots.meta.api.objects.User;
import java.io.IOException;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.telegram.abilitybots.api.bot.TestUtils.mockContext;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
class AbilityBotI18nTest {
private static final User NO_LANGUAGE_USER = new User(1L, "first", false, "last", "username", null, false, false, false, false, false, false, false, false, false, false, false);
private static final User ITALIAN_USER = new User(2L, "first", false, "last", "username", "it-IT", false, false, false, false, false, false, false, false, false, false, false);
private static final User NO_LANGUAGE_USER = new User(1L, "first", false, "last", "username", null, false, false, false);
private static final User ITALIAN_USER = new User(2L, "first", false, "last", "username", "it-IT", false, false, false);
private DBContext db;
private NoPublicCommandsBot bot;

View File

@ -1,5 +1,44 @@
package org.telegram.abilitybots.api.bot;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Ability;
import org.telegram.abilitybots.api.objects.Flag;
import org.telegram.abilitybots.api.objects.Locality;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.abilitybots.api.objects.Privacy;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.sender.SilentSender;
import org.telegram.abilitybots.api.util.AbilityUtils;
import org.telegram.abilitybots.api.util.Pair;
import org.telegram.abilitybots.api.util.Trio;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.meta.api.objects.Document;
import org.telegram.telegrambots.meta.api.objects.File;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberAdministrator;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;
@ -35,44 +74,6 @@ import static org.telegram.abilitybots.api.objects.Privacy.ADMIN;
import static org.telegram.abilitybots.api.objects.Privacy.GROUP_ADMIN;
import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Ability;
import org.telegram.abilitybots.api.objects.Flag;
import org.telegram.abilitybots.api.objects.Locality;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.abilitybots.api.objects.Privacy;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.sender.SilentSender;
import org.telegram.abilitybots.api.util.AbilityUtils;
import org.telegram.abilitybots.api.util.Pair;
import org.telegram.abilitybots.api.util.Trio;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.meta.api.objects.Document;
import org.telegram.telegrambots.meta.api.objects.File;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberAdministrator;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
public class AbilityBotTest {
// Messages
private static final String RECOVERY_MESSAGE = "I am ready to receive the backup file. Please reply to this message with the backup file attached.";
@ -373,7 +374,7 @@ public class AbilityBotTest {
String newFirstName = USER.getFirstName() + "-test";
String newLastName = USER.getLastName() + "-test";
long sameId = USER.getId();
User changedUser = new User(sameId, newFirstName, false, newLastName, newUsername, "en", false, false, false, false, false, false, false, false, false, false, false);
User changedUser = new User(sameId, newFirstName, false, newLastName, newUsername, "en", false, false, false);
mockAlternateUser(update, message, changedUser);
@ -382,7 +383,7 @@ public class AbilityBotTest {
Map<String, Long> expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId());
Map<Long, User> expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser);
assertEquals(bot.userIds(), expectedUserIds, "User was not properly edited");
assertEquals(bot.users(), expectedUsers, "User was not properly edited");
assertEquals(expectedUsers, expectedUsers, "User was not properly edited");
}
@Test

View File

@ -78,20 +78,19 @@ public class DefaultBot extends AbilityBot {
public Reply channelPostReply() {
return Reply.of(
(bot, upd) -> silent.send("test channel post", upd.getChannelPost().getChatId()),
Flag.CHANNEL_POST
(bot, upd) -> silent.send("test channel post", upd.getChannelPost().getChatId()), Flag.CHANNEL_POST
);
}
public ReplyCollection createReplyCollection() {
return ReplyCollection.of(
Reply.of(
(bot, upd) -> silent.send("first reply answer", upd.getMessage().getChatId()),
update -> update.getMessage().getText().equalsIgnoreCase(FIRST_REPLY_KEY_MESSAGE)
upd -> silent.send("first reply answer", upd.getMessage().getChatId()),
update -> update.getMessage().getText().equalsIgnoreCase(FIRST_REPLY_KEY_MESSAGE)
),
Reply.of(
(bot, upd) -> silent.send("second reply answer", upd.getMessage().getChatId()),
update -> update.getMessage().getText().equalsIgnoreCase(SECOND_REPLY_KEY_MESSAGE)
upd -> silent.send("second reply answer", upd.getMessage().getChatId()),
update -> update.getMessage().getText().equalsIgnoreCase(SECOND_REPLY_KEY_MESSAGE)
)
);
}

View File

@ -41,13 +41,9 @@ class ExtensionTest {
}
public static class ExtensionUsingBot extends AbilityBot {
/**
* Constructor for ExtensionUsingBot
*/
ExtensionUsingBot() {
// https://github.com/rubenlagus/TelegramBots/issues/834
super("", "", offlineInstance("testing"));
addExtension(new AbilityBotExtension("addedInConstructor", this));
addExtension(new AbilityBotExtension("addedInConstructor"));
}
@Override
@ -55,63 +51,42 @@ class ExtensionTest {
return 0;
}
/**
* Method for returning AbiltyExtension
* @return AbilityBotExtension instance
*/
public AbilityBotExtension methodReturningExtensionSubClass() {
// https://github.com/rubenlagus/TelegramBots/issues/834
return new AbilityBotExtension("returningSubClass", this);
return new AbilityBotExtension("returningSubClass");
}
/**
* Method for returning AbilityExtension
* @return AbiltyBotExtension instance
*/
public AbilityExtension methodReturningExtensionSuperClass() {
// https://github.com/rubenlagus/TelegramBots/issues/834
return new AbilityBotExtension("returningSuperClass", this);
return new AbilityBotExtension("returningSuperClass");
}
public Ability methodReturningAbility() {
return Ability.builder()
.name("direct")
.info("Test ability")
.locality(ALL)
.privacy(PUBLIC)
.action(messageContext -> {
})
.build();
.name("direct")
.info("Test ability")
.locality(ALL)
.privacy(PUBLIC)
.action(messageContext -> {
})
.build();
}
}
public static class AbilityBotExtension implements AbilityExtension {
private String name;
private AbilityBot extensionUser;
/**
* https://github.com/rubenlagus/TelegramBots/issues/721
* Constructor for AbilityBotExtension
* @param name Name of the ability extension
* @param extensionUser The AbilityBot that uses this AbilityExtension
*/
AbilityBotExtension(String name, AbilityBot extensionUser) {
AbilityBotExtension(String name) {
this.name = name;
// https://github.com/rubenlagus/TelegramBots/issues/834
this.extensionUser = extensionUser;
}
public Ability abc() {
return Ability.builder()
.name(name + "0abc")
.info("Test ability")
.locality(ALL)
.privacy(PUBLIC)
.action(ctx -> {
// https://github.com/rubenlagus/TelegramBots/issues/834
extensionUser.silent().send("This is a test message.", ctx.chatId());
})
.build();
.name(name + "0abc")
.info("Test ability")
.locality(ALL)
.privacy(PUBLIC)
.action(ctx -> {
})
.build();
}
}
}

View File

@ -1,18 +1,18 @@
package org.telegram.abilitybots.api.bot;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.telegram.abilitybots.api.objects.MessageContext.newContext;
import org.jetbrains.annotations.NotNull;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.telegram.abilitybots.api.objects.MessageContext.newContext;
public final class TestUtils {
public static final User USER = new User(1L, "first", false, "last", "username", null, false, false, false, false, false, false, false, false, false, false, false);
public static final User CREATOR = new User(1337L, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false, false, false, false, false, false, false, false, false);
public static final User USER = new User(1L, "first", false, "last", "username", null, false, false, false);
public static final User CREATOR = new User(1337L, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false);
private TestUtils() {

View File

@ -143,17 +143,4 @@ class MapDBContextTest {
Var<User> changedVar = db.getVar(varName);
assertEquals(changedVar.get(), USER);
}
@Test
void testToString() throws Exception {
String varName = "somevar";
Var<User> var = db.getVar(varName);
var.set(CREATOR);
db.commit();
var = db.getVar(varName);
var.set(USER);
db.commit();
Var<User> changedVar = db.getVar(varName);
Assertions.assertEquals("MapDBVar{var=User(id=1, firstName=first, isBot=false, lastName=last, userName=username, languageCode=null, canJoinGroups=false, canReadAllGroupMessages=false, supportInlineQueries=false, isPremium=false, addedToAttachmentMenu=false)}", ((MapDBVar) (changedVar)).toString());
}
}

View File

@ -14,10 +14,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
class SilentSenderTest {
private SilentSender silent;
@ -58,7 +55,7 @@ class SilentSenderTest {
verify(sender, only()).executeAsync(methodObject, callback);
}
private static class NoOpCallback implements SentCallback<Message> {
private class NoOpCallback implements SentCallback<Message> {
@Override
public void onResult(BotApiMethod<Message> method, Message response) {
@ -75,4 +72,6 @@ class SilentSenderTest {
}
}
;
}

View File

@ -8,25 +8,19 @@ import org.telegram.abilitybots.api.bot.DefaultBot;
import org.telegram.abilitybots.api.db.DBContext;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.*;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
class CustomToggleTest {
private DBContext db;
private AbilityToggle toggle;
private DefaultBot customBot;
private String filename;
@BeforeEach
void setUp() {
db = offlineInstance("db");
filename = "src/test/resources/toggle.properties";
}
@AfterEach
@ -53,37 +47,4 @@ class CustomToggleTest {
assertTrue(customBot.abilities().containsKey(targetName));
}
@Test
public void canTurnOffAbilitiesThroughProperties() {
Properties properties = new Properties();
try {
properties.load(Files.newInputStream(Paths.get(filename)));
toggle = new CustomToggle().config(properties);
} catch (IOException e) {
System.out.println("No such file");
}
customBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
customBot.onRegister();
assertFalse(customBot.abilities().containsKey(DefaultAbilities.CLAIM));
}
@Test
public void canProcessAbilitiesThroughProperties() {
Properties properties = new Properties();
try {
properties.load(Files.newInputStream(Paths.get(filename)));
toggle = new CustomToggle().config(properties);
} catch (IOException e) {
System.out.println("No such file");
}
customBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
customBot.onRegister();
String targetName = "restrict";
assertTrue(customBot.abilities().containsKey(targetName));
}
}

View File

@ -1,2 +0,0 @@
ability.claim.enabled=false
ability.ban.toggle=restrict

View File

@ -15,14 +15,14 @@ Usage
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-chat-session-bot</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
```
**Gradle**
```gradle
implementation 'org.telegram:telegrambots-chat-session-bot:6.8.0'
implementation 'org.telegram:telegrambots-chat-session-bot:5.5.0'
```
Motivation

View File

@ -5,9 +5,9 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.warp</groupId>
<artifactId>bots</artifactId>
<version>6.8.0</version>
<groupId>org.telegram</groupId>
<artifactId>Bots</artifactId>
<version>5.5.0</version>
</parent>
<artifactId>telegrambots-chat-session-bot</artifactId>
@ -57,36 +57,34 @@
</licenses>
<distributionManagement>
<repository>
<id>mchv-release-distribution</id>
<name>MCHV Release Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv</url>
</repository>
<snapshotRepository>
<id>mchv-snapshot-distribution</id>
<name>MCHV Snapshot Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv-snapshot</url>
<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>
<java.version>11</java.version>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>8</maven.compiler.release>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<shiro.version>1.10.0</shiro.version>
<shiro.version>1.8.0</shiro.version>
</properties>
<dependencies>
<dependency>
<groupId>org.warp</groupId>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
@ -94,12 +92,6 @@
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
@ -113,7 +105,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<version>3.0.0-M3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -129,9 +121,20 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</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.2.0</version>
<version>3.1.0</version>
<executions>
<execution>
<id>clean-project</id>
@ -144,7 +147,7 @@
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
@ -163,7 +166,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -175,7 +178,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.0</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -190,7 +193,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>0.8.4</version>
<executions>
<execution>
<goals>
@ -209,7 +212,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M2</version>
<executions>
<execution>
<id>enforce-versions</id>
@ -227,7 +230,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<executions>
<execution>
<id>copy</id>
@ -241,18 +244,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>

View File

@ -1,5 +0,0 @@
module telegrambots.chat.session.bot {
requires shiro.core;
requires telegrambots;
requires telegrambots.meta;
}

View File

@ -20,7 +20,7 @@ public class DefaultChatIdConverter implements ChatIdConverter {
@Override
public void setSessionId(Serializable sessionId){
this.sessionId = (long) sessionId;
}
};
@Override
public Serializable getSessionId() {

View File

@ -6,9 +6,9 @@ import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.util.Optional;
@ -17,50 +17,22 @@ public abstract class TelegramLongPollingSessionBot extends TelegramLongPollingB
DefaultSessionManager sessionManager;
ChatIdConverter chatIdConverter;
/**
* If this is used getBotToken has to be overridden in order to return the bot token!
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*/
@Deprecated
public TelegramLongPollingSessionBot(){
this(new DefaultChatIdConverter());
}
/**
* If this is used getBotToken has to be overridden in order to return the bot token!
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*/
@Deprecated
public TelegramLongPollingSessionBot(ChatIdConverter chatIdConverter){
this(chatIdConverter, new DefaultBotOptions());
}
/**
* If this is used getBotToken has to be overridden in order to return the bot token!
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*/
@Deprecated
public TelegramLongPollingSessionBot(ChatIdConverter chatIdConverter, DefaultBotOptions defaultBotOptions){
this(chatIdConverter, defaultBotOptions, null);
}
public TelegramLongPollingSessionBot(String botToken){
this(new DefaultChatIdConverter(), botToken);
}
public TelegramLongPollingSessionBot(ChatIdConverter chatIdConverter, String botToken){
this(chatIdConverter, new DefaultBotOptions(), botToken);
}
public TelegramLongPollingSessionBot(ChatIdConverter chatIdConverter, DefaultBotOptions defaultBotOptions, String botToken){
super(defaultBotOptions, botToken);
this.setSessionManager(new DefaultSessionManager());
this.setChatIdConverter(chatIdConverter);
AbstractSessionDAO sessionDAO = (AbstractSessionDAO) sessionManager.getSessionDAO();
sessionDAO.setSessionIdGenerator(chatIdConverter);
}
public void setSessionManager(DefaultSessionManager sessionManager) {
this.sessionManager = sessionManager;
}
@ -82,12 +54,8 @@ public abstract class TelegramLongPollingSessionBot extends TelegramLongPollingB
onUpdateReceived(update, chatSession);
return;
}
if (message.getChat() != null) {
chatIdConverter.setSessionId(message.getChatId());
chatSession = this.getSession(message);
} else {
chatSession = Optional.empty();
}
chatIdConverter.setSessionId(message.getChatId());
chatSession = this.getSession(message);
onUpdateReceived(update, chatSession);
}

View File

@ -16,12 +16,12 @@ Just import add the library to your project with one of these options:
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambotsextensions</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
```
2. Using Gradle:
```gradle
implementation 'org.telegram:telegrambotsextensions:6.8.0'
implementation 'org.telegram:telegrambotsextensions:5.5.0'
```

View File

@ -5,9 +5,9 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.warp</groupId>
<artifactId>bots</artifactId>
<version>6.8.0</version>
<groupId>org.telegram</groupId>
<artifactId>Bots</artifactId>
<version>5.5.0</version>
</parent>
<artifactId>telegrambotsextensions</artifactId>
@ -51,21 +51,19 @@
</licenses>
<distributionManagement>
<repository>
<id>mchv-release-distribution</id>
<name>MCHV Release Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv</url>
</repository>
<snapshotRepository>
<id>mchv-snapshot-distribution</id>
<name>MCHV Snapshot Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv-snapshot</url>
<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>
<java.version>11</java.version>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>8</maven.compiler.release>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
@ -75,9 +73,9 @@
<dependencies>
<dependency>
<groupId>org.warp</groupId>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.8.0</version>
<version>5.5.0</version>
</dependency>
</dependencies>
@ -91,7 +89,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<version>3.0.0-M3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -107,9 +105,20 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</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.2.0</version>
<version>3.1.0</version>
<executions>
<execution>
<id>clean-project</id>
@ -122,7 +131,7 @@
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
@ -141,7 +150,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -153,7 +162,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.0</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -168,7 +177,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>0.8.4</version>
<executions>
<execution>
<goals>
@ -187,7 +196,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M2</version>
<executions>
<execution>
<id>enforce-versions</id>
@ -205,7 +214,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<executions>
<execution>
<id>copy</id>
@ -219,18 +228,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>

View File

@ -1,4 +0,0 @@
module telegrambotsextensions {
requires telegrambots.meta;
requires telegrambots;
}

View File

@ -1,47 +0,0 @@
package org.telegram.telegrambots.extensions.bots.commandbot;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
/**
* This interface represents common functions for command bots
*
* @author Andrey Korsakov (loolzaaa)
*/
public interface CommandBot {
/**
* Process all updates, that are not commands.
*
* @param update the update
* @warning Commands that have valid syntax but are not registered on this bot,
* won't be forwarded to this method <b>if a default action is present</b>.
*/
void processNonCommandUpdate(Update update);
/**
* This method is called when user sends a not registered command. By default it will just call processNonCommandUpdate(),
* override it in your implementation if you want your bot to do other things, such as sending an error message
*
* @param update Received update from Telegram
*/
default void processInvalidCommandUpdate(Update update) {
processNonCommandUpdate(update);
}
/**
* Override this function in your bot implementation to filter messages with commands
* <p>
* For example, if you want to prevent commands execution incoming from group chat:
* #
* # return !message.getChat().isGroupChat();
* #
*
* @param message Received message
* @return true if the message must be ignored by the command bot and treated as a non command message,
* false otherwise
* @note Default implementation doesn't filter anything
*/
default boolean filter(Message message) {
return false;
}
}

View File

@ -19,16 +19,14 @@ import java.util.function.BiConsumer;
*
* @author Timo Schulz (Mit0x2)
*/
public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingBot implements CommandBot, ICommandRegistry {
public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingBot implements ICommandRegistry {
private final CommandRegistry commandRegistry;
/**
* Creates a TelegramLongPollingCommandBot using default options
* Use ICommandRegistry's methods on this bot to register commands
*
* @deprecated Use {{@link #TelegramLongPollingBot(String)}
*/
@Deprecated
public TelegramLongPollingCommandBot() {
this(new DefaultBotOptions());
}
@ -39,10 +37,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB
* Use ICommandRegistry's methods on this bot to register commands
*
* @param options Bot options
*
* @deprecated Use {{@link #TelegramLongPollingBot(DefaultBotOptions, String)}
*/
@Deprecated
public TelegramLongPollingCommandBot(DefaultBotOptions options) {
this(options, true);
}
@ -54,48 +49,12 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB
* @param options Bot options
* @param allowCommandsWithUsername true to allow commands with parameters (default),
* false otherwise
*
* @deprecated Use {{@link #TelegramLongPollingBot(DefaultBotOptions, boolean, String)}
*/
@Deprecated
public TelegramLongPollingCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername) {
super(options);
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername);
}
/**
* Creates a TelegramLongPollingCommandBot using default options
* Use ICommandRegistry's methods on this bot to register commands
*
*/
public TelegramLongPollingCommandBot(String botToken) {
this(new DefaultBotOptions(), botToken);
}
/**
* Creates a TelegramLongPollingCommandBot with custom options and allowing commands with
* usernames
* Use ICommandRegistry's methods on this bot to register commands
*
* @param options Bot options
*/
public TelegramLongPollingCommandBot(DefaultBotOptions options, String botToken) {
this(options, true, botToken);
}
/**
* Creates a TelegramLongPollingCommandBot
* Use ICommandRegistry's methods on this bot to register commands
*
* @param options Bot options
* @param allowCommandsWithUsername true to allow commands with parameters (default),
* false otherwise
*/
public TelegramLongPollingCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername, String botToken) {
super(options, botToken);
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername);
}
@Override
public final void onUpdateReceived(Update update) {
if (update.hasMessage()) {
@ -111,6 +70,34 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB
processNonCommandUpdate(update);
}
/**
* This method is called when user sends a not registered command. By default it will just call processNonCommandUpdate(),
* override it in your implementation if you want your bot to do other things, such as sending an error message
*
* @param update Received update from Telegram
*/
protected void processInvalidCommandUpdate(Update update) {
processNonCommandUpdate(update);
}
/**
* Override this function in your bot implementation to filter messages with commands
* <p>
* For example, if you want to prevent commands execution incoming from group chat:
* #
* # return !message.getChat().isGroupChat();
* #
*
* @param message Received message
* @return true if the message must be ignored by the command bot and treated as a non command message,
* false otherwise
* @note Default implementation doesn't filter anything
*/
protected boolean filter(Message message) {
return false;
}
@Override
public final boolean register(IBotCommand botCommand) {
return commandRegistry.register(botCommand);
@ -151,4 +138,13 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB
*/
@Override
public abstract String getBotUsername();
/**
* Process all updates, that are not commands.
*
* @param update the update
* @warning Commands that have valid syntax but are not registered on this bot,
* won't be forwarded to this method <b>if a default action is present</b>.
*/
public abstract void processNonCommandUpdate(Update update);
}

View File

@ -1,153 +0,0 @@
package org.telegram.telegrambots.extensions.bots.commandbot;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramWebhookBot;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.CommandRegistry;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.IBotCommand;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.ICommandRegistry;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.bots.AbsSender;
import java.util.Collection;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* This class adds command functionality to the TelegramWebhookBot
*
* @author Andrey Korsakov (loolzaaa)
*/
public abstract class TelegramWebhookCommandBot extends TelegramWebhookBot implements CommandBot, ICommandRegistry {
private final CommandRegistry commandRegistry;
/**
* Creates a TelegramWebhookCommandBot using default options
* Use ICommandRegistry's methods on this bot to register commands
*
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*/
@Deprecated
public TelegramWebhookCommandBot() {
this(new DefaultBotOptions());
}
/**
* Creates a TelegramWebhookCommandBot with custom options and allowing commands with
* usernames
* Use ICommandRegistry's methods on this bot to register commands
*
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*
* @param options Bot options
*/
@Deprecated
public TelegramWebhookCommandBot(DefaultBotOptions options) {
this(options, true);
}
/**
* Creates a TelegramWebhookCommandBot
* Use ICommandRegistry's methods on this bot to register commands
*
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*
* @param options Bot options
* @param allowCommandsWithUsername true to allow commands with parameters (default),
* false otherwise
*/
@Deprecated
public TelegramWebhookCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername) {
super(options);
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername);
}
/**
* Creates a TelegramWebhookCommandBot using default options
* Use ICommandRegistry's methods on this bot to register commands
*
* @param botToken the telegram api token
*/
public TelegramWebhookCommandBot(String botToken) {
this(new DefaultBotOptions(), botToken);
}
/**
* Creates a TelegramWebhookCommandBot with custom options and allowing commands with
* usernames
* Use ICommandRegistry's methods on this bot to register commands
*
* @param options Bot options
* @param botToken the telegram api token
*/
public TelegramWebhookCommandBot(DefaultBotOptions options, String botToken) {
this(options, true, botToken);
}
/**
* Creates a TelegramWebhookCommandBot
* Use ICommandRegistry's methods on this bot to register commands
*
* @param options Bot options
* @param allowCommandsWithUsername true to allow commands with parameters (default),
* false otherwise
* @param botToken the telegram api token
*/
public TelegramWebhookCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername, String botToken) {
super(options, botToken);
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername);
}
@Override
public BotApiMethod<?> onWebhookUpdateReceived(Update update) {
if (update.hasMessage()) {
Message message = update.getMessage();
if (message.isCommand() && !filter(message)) {
if (!commandRegistry.executeCommand(this, message)) {
//we have received a not registered command, handle it as invalid
processInvalidCommandUpdate(update);
}
return null;
}
}
processNonCommandUpdate(update);
return null;
}
@Override
public final boolean register(IBotCommand botCommand) {
return commandRegistry.register(botCommand);
}
@Override
public final Map<IBotCommand, Boolean> registerAll(IBotCommand... botCommands) {
return commandRegistry.registerAll(botCommands);
}
@Override
public final boolean deregister(IBotCommand botCommand) {
return commandRegistry.deregister(botCommand);
}
@Override
public final Map<IBotCommand, Boolean> deregisterAll(IBotCommand... botCommands) {
return commandRegistry.deregisterAll(botCommands);
}
@Override
public final Collection<IBotCommand> getRegisteredCommands() {
return commandRegistry.getRegisteredCommands();
}
@Override
public void registerDefaultAction(BiConsumer<AbsSender, Message> defaultConsumer) {
commandRegistry.registerDefaultAction(defaultConsumer);
}
@Override
public final IBotCommand getRegisteredCommand(String commandIdentifier) {
return commandRegistry.getRegisteredCommand(commandIdentifier);
}
}

View File

@ -1,11 +1,11 @@
package org.telegram.telegrambots.extensions.bots.commandbot.commands.helpCommand;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.IBotCommand;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.ICommandRegistry;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.IBotCommand;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.ICommandRegistry;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.Collection;
@ -42,7 +42,7 @@ public class HelpCommand extends ManCommand {
* @return a formatted String containing command and description for all supplied commands
*/
public static String getHelpText(Collection<IBotCommand> botCommands) {
return getHelpText(botCommands.toArray(new IBotCommand[0]));
return getHelpText(botCommands.toArray(new IBotCommand[botCommands.size()]));
}
/**
@ -98,14 +98,14 @@ public class HelpCommand extends ManCommand {
IBotCommand command = registry.getRegisteredCommand(arguments[0]);
String reply = getManText(command);
try {
absSender.execute(SendMessage.builder().chatId(chat.getId()).text(reply).parseMode("HTML").build());
absSender.execute(SendMessage.builder().chatId(chat.getId().toString()).text(reply).parseMode("HTML").build());
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else {
String reply = getHelpText(registry);
try {
absSender.execute(SendMessage.builder().chatId(chat.getId()).text(reply).parseMode("HTML").build());
absSender.execute(SendMessage.builder().chatId(chat.getId().toString()).text(reply).parseMode("HTML").build());
} catch (TelegramApiException e) {
e.printStackTrace();
}

View File

@ -132,20 +132,8 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot
}
//Constructor
/**
* @deprecated Overwriting the getBotToken() method is deprecated. Use the constructor instead
*/
@Deprecated
protected TimedSendLongPollingBot()
{
super();
mSendTimer.schedule(new MessageSenderTask(), MANY_CHATS_SEND_INTERVAL, MANY_CHATS_SEND_INTERVAL);
}
protected TimedSendLongPollingBot(String botToken)
{
super(botToken);
mSendTimer.schedule(new MessageSenderTask(), MANY_CHATS_SEND_INTERVAL, MANY_CHATS_SEND_INTERVAL);
}

View File

@ -5,9 +5,9 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.warp</groupId>
<artifactId>bots</artifactId>
<version>6.8.0</version>
<groupId>org.telegram</groupId>
<artifactId>Bots</artifactId>
<version>5.5.0</version>
</parent>
<artifactId>telegrambots-meta</artifactId>
@ -45,27 +45,25 @@
<licenses>
<license>
<name>MIT License</name>
<url>https://www.opensource.org/licenses/mit-license.php</url>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<distributionManagement>
<repository>
<id>mchv-release-distribution</id>
<name>MCHV Release Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv</url>
</repository>
<snapshotRepository>
<id>mchv-snapshot-distribution</id>
<name>MCHV Snapshot Apache Maven Packages Distribution</name>
<url>https://mvn.mchv.eu/repository/mchv-snapshot</url>
<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>
<java.version>11</java.version>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>8</maven.compiler.release>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
@ -89,20 +87,18 @@
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.14.2</version>
</dependency>
</dependencies>
@ -127,9 +123,20 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</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.2.0</version>
<version>3.1.0</version>
<executions>
<execution>
<id>clean-project</id>
@ -142,7 +149,7 @@
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
@ -161,7 +168,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -173,7 +180,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.0</version>
<version>3.1.0</version>
<executions>
<execution>
<goals>
@ -188,7 +195,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>0.8.4</version>
<executions>
<execution>
<goals>
@ -207,7 +214,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<version>3.0.0-M2</version>
<executions>
<execution>
<id>enforce</id>
@ -225,7 +232,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<version>3.1.1</version>
<executions>
<execution>
<id>copy</id>
@ -236,7 +243,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<version>3.0.0-M3</version>
</plugin>
</plugins>
<pluginManagement>
@ -244,18 +251,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>

View File

@ -1,43 +0,0 @@
module telegrambots.meta {
opens org.telegram.telegrambots.meta.api.objects to com.fasterxml.jackson.databind;
exports org.telegram.telegrambots.meta.api.objects;
exports org.telegram.telegrambots.meta;
exports org.telegram.telegrambots.meta.generics;
exports org.telegram.telegrambots.meta.exceptions;
exports org.telegram.telegrambots.meta.api.methods;
exports org.telegram.telegrambots.meta.api.methods.groupadministration;
exports org.telegram.telegrambots.meta.api.methods.send;
exports org.telegram.telegrambots.meta.api.methods.stickers;
exports org.telegram.telegrambots.meta.api.objects.media;
exports org.telegram.telegrambots.meta.api.methods.updatingmessages;
exports org.telegram.telegrambots.meta.api.methods.commands;
exports org.telegram.telegrambots.meta.api.methods.games;
exports org.telegram.telegrambots.meta.api.methods.polls;
exports org.telegram.telegrambots.meta.api.methods.invoices;
exports org.telegram.telegrambots.meta.bots;
exports org.telegram.telegrambots.meta.updateshandlers;
exports org.telegram.telegrambots.meta.api.methods.updates;
exports org.telegram.telegrambots.meta.api.objects.chatmember;
exports org.telegram.telegrambots.meta.api.objects.replykeyboard;
exports org.telegram.telegrambots.meta.api.objects.payments;
exports org.telegram.telegrambots.meta.api.objects.extra;
exports org.telegram.telegrambots.meta.api.objects.commands;
exports org.telegram.telegrambots.meta.api.objects.games;
exports org.telegram.telegrambots.meta.api.objects.forum;
exports org.telegram.telegrambots.meta.api.objects.inlinequery;
exports org.telegram.telegrambots.meta.api.objects.passport;
exports org.telegram.telegrambots.meta.api.objects.polls;
exports org.telegram.telegrambots.meta.api.objects.stickers;
exports org.telegram.telegrambots.meta.api.objects.videochat;
exports org.telegram.telegrambots.meta.api.objects.webapp;
exports org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons;
exports org.telegram.telegrambots.meta.api.interfaces;
exports org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent;
exports org.telegram.telegrambots.meta.api.objects.inlinequery.result;
requires static lombok;
requires com.fasterxml.jackson.annotation;
requires com.fasterxml.jackson.core;
requires com.fasterxml.jackson.databind;
requires org.slf4j;
requires org.apache.commons.lang3;
}

View File

@ -1,38 +0,0 @@
package org.telegram.telegrambots.meta;
import java.nio.charset.StandardCharsets;
public class MemoizedUTF16String {
private final String original;
private byte[] cache;
public MemoizedUTF16String(String string) {
this.original = string;
}
public MemoizedUTF16String(byte[] utf16Data) {
this.original = null;
this.cache = utf16Data;
}
public byte[] getBytes() {
if (original != null && cache == null) {
byte[] newCache = original.getBytes(StandardCharsets.UTF_16LE);
this.cache = newCache;
return newCache;
} else {
return cache;
}
}
public String substring(int offsetUtf16, int lengthUtf16) {
byte[] bytes = getBytes();
if (bytes != null) {
return new String(bytes, offsetUtf16, lengthUtf16, StandardCharsets.UTF_16LE);
} else {
return "";
}
}
}

View File

@ -1,35 +0,0 @@
package org.telegram.telegrambots.meta;
import java.nio.charset.StandardCharsets;
public class MemoizedUTF16Substring {
private final MemoizedUTF16String parentString;
private final int offsetUtf16;
private final int lengthUtf16;
private String cache;
public MemoizedUTF16Substring(MemoizedUTF16String parentString, int offsetUtf16, int lengthUtf16) {
this.parentString = parentString;
this.offsetUtf16 = offsetUtf16;
this.lengthUtf16 = lengthUtf16;
}
public String getString() {
if (parentString != null && cache == null) {
String newString = parentString.substring(offsetUtf16, lengthUtf16);
if (newString == null) {
this.cache = "";
return "";
} else {
this.cache = newString;
return newString;
}
} else if (cache != null) {
return cache;
} else {
return "";
}
}
}

View File

@ -1,6 +1,6 @@
package org.telegram.telegrambots.meta;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Strings;
import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.BotSession;
@ -100,32 +100,13 @@ public class TelegramBotsApi {
}
}
/**
* Register a bot in the api that will receive updates using webhook method
* @param bot Bot to register
*
* @apiNote The webhook url will be appended with `/callback/bot.getBotPath()` at the end
*/
public void registerBotWithoutToken(WebhookBot bot) throws TelegramApiException {
if (useWebhook) {
if (webhook == null) {
throw new TelegramApiException("This instance doesn't support Webhook bot, use correct constructor");
}
if (StringUtils.isEmpty(bot.getBotUsername())) {
throw new TelegramApiException("Bot username can't be empty");
}
bot.onRegister();
webhook.registerWebhook(bot);
}
}
/**
* Checks that the username and token are presented
* @param telegramBot bot to register
* @return False if username or token are empty or null, true otherwise
*/
private boolean validateBotUsernameAndToken(TelegramBot telegramBot) {
return StringUtils.isNotEmpty(telegramBot.getBotToken()) &&
StringUtils.isNotEmpty(telegramBot.getBotUsername());
return !Strings.isNullOrEmpty(telegramBot.getBotToken()) &&
!Strings.isNullOrEmpty(telegramBot.getBotUsername());
}
}

View File

@ -30,7 +30,5 @@ public interface Validable {
* Validates that mandatory fields are filled and optional objects
* @throws TelegramApiValidationException If any mandatory field is empty
*/
default void validate() throws TelegramApiValidationException {
}
void validate() throws TelegramApiValidationException;
}

View File

@ -9,10 +9,20 @@ public enum ActionType {
TYPING("typing"),
RECORDVIDEO("record_video"),
RECORDVIDEONOTE("record_video_note"),
/**
* @deprecated Use {@link #RECORDVOICE} instead
*/
@Deprecated
RECORDAUDIO("record_audio"),
RECORDVOICE("record_voice"),
UPLOADPHOTO("upload_photo"),
UPLOADVIDEO("upload_video"),
UPLOADVIDEONOTE("upload_video_note"),
/**
* @deprecated Use {@link #UPLOADVOICE} instead
*/
@Deprecated
UPLOADAUDIO("upload_audio"),
UPLOADVOICE("upload_voice"),
UPLOADDOCUMENT("upload_document"),
FINDLOCATION("find_location");

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,7 +11,11 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
@ -27,11 +32,11 @@ import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBool
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class AnswerCallbackQuery extends BotApiMethodBoolean {
public class AnswerCallbackQuery extends BotApiMethod<Boolean> {
public static final String PATH = "answercallbackquery";
private static final String CALLBACKQUERYID_FIELD = "callback_query_id";
@ -68,4 +73,26 @@ public class AnswerCallbackQuery extends BotApiMethodBoolean {
public String getMethod() {
return PATH;
}
@Override
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);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (callbackQueryId == null) {
throw new TelegramApiValidationException("CallbackQueryId can't be null", this);
}
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -11,12 +12,12 @@ import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Singular;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult;
import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResultsButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
@ -29,12 +30,11 @@ import java.util.regex.Pattern;
@Getter
@Setter
@ToString
@NoArgsConstructor
@RequiredArgsConstructor
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Jacksonized
@Builder
public class AnswerInlineQuery extends BotApiMethodBoolean {
public class AnswerInlineQuery extends BotApiMethod<Boolean> {
public static final String PATH = "answerInlineQuery";
private static final String INLINEQUERYID_FIELD = "inline_query_id";
@ -44,7 +44,6 @@ public class AnswerInlineQuery extends BotApiMethodBoolean {
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";
private static final String BUTTON_FIELD = "button";
@JsonProperty(INLINEQUERYID_FIELD)
@NonNull
@ -59,39 +58,19 @@ public class AnswerInlineQuery extends BotApiMethodBoolean {
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.
/**
* 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
*
* @deprecated Use {@link #setButton(InlineQueryResultsButton)}
*/
@JsonProperty(SWITCH_PM_TEXT_FIELD)
@Deprecated
private String switchPmText;
/**
* Optional.
* Parameter for the start message sent to the bot when user presses the switch button
*
* @deprecated Use {@link #setButton(InlineQueryResultsButton)}
*/
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)
@Deprecated
private String switchPmParameter;
/**
* Optional.
* A JSON serialized object describing a button to be shown above inline query results
*/
@JsonProperty(BUTTON_FIELD)
private InlineQueryResultsButton button;
private String switchPmParameter; ///< Optional. Parameter for the start message sent to the bot when user presses the switch button
@Override
public void validate() throws TelegramApiValidationException {
if (inlineQueryId.isEmpty()) {
if (inlineQueryId == null || inlineQueryId.isEmpty()) {
throw new TelegramApiValidationException("InlineQueryId can't be empty", this);
}
if (results == null) {
throw new TelegramApiValidationException("Results array can't be null", this);
}
if (switchPmText != null) {
if (switchPmText.isEmpty()) {
throw new TelegramApiValidationException("SwitchPmText can't be empty", this);
@ -109,14 +88,25 @@ public class AnswerInlineQuery extends BotApiMethodBoolean {
for (InlineQueryResult result : results) {
result.validate();
}
if (button != null) {
button.validate();
}
}
@Override
public String getMethod() {
return PATH;
}
@Override
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);
}
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,9 +11,12 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
@ -28,11 +32,11 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class AnswerPreCheckoutQuery extends BotApiMethodBoolean {
public class AnswerPreCheckoutQuery extends BotApiMethod<Boolean> {
public static final String PATH = "answerPreCheckoutQuery";
private static final String PRE_CHECKOUT_QUERY_ID_FIELD = "pre_checkout_query_id";
@ -50,9 +54,12 @@ public class AnswerPreCheckoutQuery extends BotApiMethodBoolean {
@Override
public void validate() throws TelegramApiValidationException {
if (preCheckoutQueryId.isEmpty()) {
if (preCheckoutQueryId == null || preCheckoutQueryId.isEmpty()) {
throw new TelegramApiValidationException("PreCheckoutQueryId can't be empty", this);
}
if (ok == null) {
throw new TelegramApiValidationException("Ok can't be null", this);
}
if (!ok) {
if (errorMessage == null || errorMessage.isEmpty()) {
throw new TelegramApiValidationException("ErrorMessage can't be empty if not ok", this);
@ -64,4 +71,19 @@ public class AnswerPreCheckoutQuery extends BotApiMethodBoolean {
public String getMethod() {
return PATH;
}
@Override
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 pre-checkout query", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,10 +11,12 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.payments.ShippingOption;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.List;
/**
@ -30,11 +33,11 @@ import java.util.List;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class AnswerShippingQuery extends BotApiMethodBoolean {
public class AnswerShippingQuery extends BotApiMethod<Boolean> {
public static final String PATH = "answerShippingQuery";
private static final String SHIPPING_QUERY_ID_FIELD = "shipping_query_id";
@ -79,4 +82,19 @@ public class AnswerShippingQuery extends BotApiMethodBoolean {
public String getMethod() {
return PATH;
}
@Override
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 shipping query", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
}

View File

@ -2,6 +2,7 @@ package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
@ -16,4 +17,10 @@ import java.io.Serializable;
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,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AllArgsConstructor;
import lombok.Builder;
@ -11,13 +12,14 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import org.telegram.telegrambots.meta.api.objects.MessageId;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.List;
/**
@ -25,7 +27,7 @@ import java.util.List;
* @version 1.0
* Use this method to copy messages of any kind.
* Service messages and invoice messages can't be copied.
* A quiz poll can be copied only if the value of the field correct_option_id is known to the bot.
*
* The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message.
* Returns the MessageId of the sent message on success.
*/
@ -35,14 +37,13 @@ import java.util.List;
@Setter
@ToString
@RequiredArgsConstructor
@NoArgsConstructor(force = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CopyMessage extends BotApiMethod<MessageId> {
public static final String PATH = "copyMessage";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
private static final String FROMCHATID_FIELD = "from_chat_id";
private static final String MESSAGEID_FIELD = "message_id";
private static final String CAPTION_FIELD = "caption";
@ -52,17 +53,10 @@ public class CopyMessage extends BotApiMethod<MessageId> {
private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply";
private static final String REPLYMARKUP_FIELD = "reply_markup";
private static final String PROTECTCONTENT_FIELD = "protect_content";
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
/**
* Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
*/
@JsonProperty(MESSAGETHREADID_FIELD)
private Integer messageThreadId;
@JsonProperty(FROMCHATID_FIELD)
@NonNull
private String fromChatId; ///< Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)
@ -91,18 +85,6 @@ public class CopyMessage extends BotApiMethod<MessageId> {
@JsonProperty(REPLYMARKUP_FIELD)
@JsonDeserialize()
private ReplyKeyboard replyMarkup;
@JsonProperty(PROTECTCONTENT_FIELD)
private Boolean protectContent; ///< Optional. Protects the contents of sent messages from forwarding and saving
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Tolerate
public void setFromChatId(@NonNull Long fromChatId) {
this.fromChatId = fromChatId.toString();
}
public void enableNotification() {
this.disableNotification = null;
@ -143,14 +125,30 @@ public class CopyMessage extends BotApiMethod<MessageId> {
@Override
public MessageId deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, MessageId.class);
try {
ApiResponse<MessageId> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<MessageId>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error copying message", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
if (chatId == null || chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
}
if (fromChatId == null) {
throw new TelegramApiValidationException("FromChatId parameter can't be empty", this);
}
if (messageId == null) {
throw new TelegramApiValidationException("MessageId parameter can't be empty", this);
}
if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) {
throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this);
@ -159,19 +157,4 @@ public class CopyMessage extends BotApiMethod<MessageId> {
replyMarkup.validate();
}
}
public static class CopyMessageBuilder {
@Tolerate
public CopyMessageBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
@Tolerate
public CopyMessageBuilder fromChatId(@NonNull Long fromChatId) {
this.fromChatId = fromChatId.toString();
return this;
}
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,10 +11,13 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodMessage;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
@ -26,29 +30,21 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class ForwardMessage extends BotApiMethodMessage {
public class ForwardMessage extends BotApiMethod<Message> {
public static final String PATH = "forwardmessage";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
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";
private static final String PROTECTCONTENT_FIELD = "protect_content";
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels)
/**
* Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
*/
@JsonProperty(MESSAGETHREADID_FIELD)
private Integer messageThreadId;
@JsonProperty(FROMCHATID_FIELD)
@NonNull
private String fromChatId; ///< Unique identifier for the chat where the original message was sent User or GroupChat id
@ -63,27 +59,18 @@ public class ForwardMessage extends BotApiMethodMessage {
*/
@JsonProperty(DISABLENOTIFICATION_FIELD)
private Boolean disableNotification;
@JsonProperty(PROTECTCONTENT_FIELD)
private Boolean protectContent; ///< Optional. Protects the contents of sent messages from forwarding and saving
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Tolerate
public void setFromChatId(@NonNull Long fromChatId) {
this.fromChatId = fromChatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
if (chatId == null || chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (fromChatId.isEmpty()) {
if (fromChatId == null || fromChatId.isEmpty()) {
throw new TelegramApiValidationException("FromChatId can't be empty", this);
}
if (messageId == null) {
throw new TelegramApiValidationException("MessageId can't be empty", this);
}
}
@Override
@ -91,18 +78,18 @@ public class ForwardMessage extends BotApiMethodMessage {
return PATH;
}
public static class ForwardMessageBuilder {
@Tolerate
public ForwardMessageBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
@Tolerate
public ForwardMessageBuilder fromChatId(@NonNull Long fromChatId) {
this.fromChatId = fromChatId.toString();
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 forwarding message", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -9,8 +10,12 @@ import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.File;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
@ -27,7 +32,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GetFile extends BotApiMethod<File> {
@ -39,6 +44,13 @@ public class GetFile extends BotApiMethod<File> {
@NonNull
private String fileId; ///< File identifier to get info about
@Override
public void validate() throws TelegramApiValidationException {
if (fileId == null) {
throw new TelegramApiValidationException("FileId can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
@ -46,6 +58,16 @@ public class GetFile extends BotApiMethod<File> {
@Override
public File deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, File.class);
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);
}
}
}

View File

@ -1,13 +1,18 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
@ -31,6 +36,21 @@ public class GetMe extends BotApiMethod<User> {
@Override
public User deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, User.class);
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,6 +1,8 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -11,7 +13,11 @@ import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.objects.UserProfilePhotos;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
@ -22,7 +28,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
@ -54,6 +60,23 @@ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
@Override
public UserProfilePhotos deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, UserProfilePhotos.class);
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);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (userId == null) {
throw new TelegramApiValidationException("UserId parameter can't be empty", this);
}
}
}

View File

@ -1,17 +1,12 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.telegram.telegrambots.meta.api.interfaces.Validable;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
/**
* @author Ruben Bermudez
@ -28,40 +23,4 @@ public abstract class PartialBotApiMethod<T extends Serializable> implements Val
* @return Answer for the method
*/
public abstract T deserializeResponse(String answer) throws TelegramApiRequestException;
public T deserializeResponse(String answer, Class<T> returnClass) throws TelegramApiRequestException {
JavaType type = OBJECT_MAPPER.getTypeFactory().constructType(returnClass);
return deserializeResponseInternal(answer, type);
}
public <K extends Serializable> T deserializeResponseArray(String answer, Class<K> returnClass) throws TelegramApiRequestException {
CollectionType collectionType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(ArrayList.class, returnClass);
return deserializeResponseInternal(answer, collectionType);
}
protected <K extends Serializable> T deserializeResponseSerializable(String answer, Class<K> returnClass) throws TelegramApiRequestException {
JavaType type = OBJECT_MAPPER.getTypeFactory().constructType(returnClass);
return deserializeResponseInternal(answer, type);
}
private T deserializeResponseInternal(String answer, JavaType type) throws TelegramApiRequestException {
try {
JavaType responseType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ApiResponse.class, type);
ApiResponse<T> result = OBJECT_MAPPER.readValue(answer, responseType);
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException(String.format("Error executing %s query", this.getClass().getName()), result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
/**
* Getter for method path (that is the same as method name)
* @return Method path
*/
@JsonProperty(BotApiMethod.METHOD_FIELD)
public abstract String getMethod();
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,10 +11,12 @@ import lombok.NonNull;
import lombok.Setter;
import lombok.Singular;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.passport.dataerror.PassportElementError;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.List;
/**
@ -27,10 +30,10 @@ import java.util.List;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SetPassportDataErrors extends BotApiMethodBoolean {
public class SetPassportDataErrors extends BotApiMethod<Boolean> {
public static final String PATH = "setPassportDataErrors";
private static final String USERID_FIELD = "user_id";
@ -49,9 +52,27 @@ public class SetPassportDataErrors extends BotApiMethodBoolean {
return PATH;
}
@Override
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 setting passport data errors", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (errors.isEmpty()) {
if (userId == null) {
throw new TelegramApiValidationException("User ID can't be empty", this);
}
if (errors == null || errors.isEmpty()) {
throw new TelegramApiValidationException("Errors can't be empty", this);
}
}

View File

@ -9,8 +9,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodSerializable;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
@ -34,7 +32,7 @@ import java.io.Serializable;
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class StopMessageLiveLocation extends BotApiMethodSerializable {
public class StopMessageLiveLocation extends BotApiMethod<Serializable> {
public static final String PATH = "stopMessageLiveLocation";
private static final String CHATID_FIELD = "chat_id";
@ -61,11 +59,6 @@ public class StopMessageLiveLocation extends BotApiMethodSerializable {
@JsonProperty(REPLYMARKUP_FIELD)
private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard.
@Tolerate
public void setChatId(Long chatId) {
this.chatId = chatId == null ? null : chatId.toString();
}
@Override
public String getMethod() {
return PATH;
@ -118,13 +111,4 @@ public class StopMessageLiveLocation extends BotApiMethodSerializable {
replyMarkup.validate();
}
}
public static class StopMessageLiveLocationBuilder {
@Tolerate
public StopMessageLiveLocationBuilder chatId(Long chatId) {
this.chatId = chatId == null ? null : chatId.toString();
return this;
}
}
}

View File

@ -1,52 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.adminrights;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.adminrights.ChatAdministratorRights;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
/**
* @author Ruben Bermudez
* @version 6.0
*
* Use this method to get the current default administrator rights of the bot.
*
* Returns ChatAdministratorRights on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GetMyDefaultAdministratorRights extends BotApiMethod<ChatAdministratorRights> {
public static final String PATH = "getMyDefaultAdministratorRights";
private static final String FORCHANNELS_FIELD = "for_channels";
/**
* Optional
* Pass True to change default administrator rights of the bot in channels.
* Otherwise, default administrator rights of the bot for groups and supergroups will be changed.
*/
@JsonProperty(FORCHANNELS_FIELD)
private Boolean forChannels;
@Override
public String getMethod() {
return PATH;
}
@Override
public ChatAdministratorRights deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, ChatAdministratorRights.class);
}
}

View File

@ -1,53 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.adminrights;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.objects.adminrights.ChatAdministratorRights;
/**
* @author Ruben Bermudez
* @version 6.0
*
* Use this method to change default administrator rights of the bot for adding it as an administrator to groups or channels.
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SetMyDefaultAdministratorRights extends BotApiMethodBoolean {
public static final String PATH = "setMyDefaultAdministratorRights";
private static final String RIGHTS_FIELD = "rights";
private static final String FORCHANNELS_FIELD = "for_channels";
/**
* Optional
* A JSON-serialized object, describing new default administrator rights.
* If not specified, the default administrator rights will be cleared.
*/
@JsonProperty(RIGHTS_FIELD)
private ChatAdministratorRights rights;
/**
* Optional
* Pass True to change default administrator rights of the bot in channels.
* Otherwise, default administrator rights of the bot for groups and supergroups will be changed.
*/
@JsonProperty(FORCHANNELS_FIELD)
private Boolean forChannels;
@Override
public String getMethod() {
return PATH;
}
}

View File

@ -1,21 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.botapimethods;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
/**
* @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 BotApiMethodBoolean extends BotApiMethod<Boolean> {
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, Boolean.class);
}
}

View File

@ -1,22 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.botapimethods;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
/**
* @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 BotApiMethodMessage extends BotApiMethod<Message> {
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, Message.class);
}
}

View File

@ -1,43 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.botapimethods;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* @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 BotApiMethodSerializable extends BotApiMethod<Serializable> {
public Serializable deserializeResponseMessageOrBoolean(String answer) throws TelegramApiRequestException {
return deserializeResponseFromPossibilities(answer, Arrays.asList(Message.class, Boolean.class));
}
public Serializable deserializeResponseFromPossibilities(String answer, List<Class<? extends Serializable>> possibleValues) throws TelegramApiRequestException {
Throwable lastException = null;
for (Class<? extends Serializable> possibleValue : possibleValues) {
try {
return deserializeResponseSerializable(answer, possibleValue);
} catch (TelegramApiRequestException e) {
if (e.getCause() instanceof IOException) {
lastException = e.getCause();
} else {
throw e;
}
}
}
throw new TelegramApiRequestException("Unable to deserialize response", lastException);
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods.commands;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -8,10 +9,14 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScope;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 5.3
@ -27,7 +32,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DeleteMyCommands extends BotApiMethodBoolean {
public class DeleteMyCommands extends BotApiMethod<Boolean> {
public static final String PATH = "deleteMyCommands";
private static final String SCOPE_FIELD = "scope";
@ -53,6 +58,21 @@ public class DeleteMyCommands extends BotApiMethodBoolean {
return PATH;
}
@Override
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 commands", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (scope != null) {

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods.commands;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -9,11 +10,13 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScope;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.ArrayList;
/**
@ -58,7 +61,17 @@ public class GetMyCommands extends BotApiMethod<ArrayList<BotCommand>> {
@Override
public ArrayList<BotCommand> deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponseArray(answer, BotCommand.class);
try {
ApiResponse<ArrayList<BotCommand>> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<ArrayList<BotCommand>>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error sending commands", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods.commands;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,11 +11,14 @@ import lombok.NonNull;
import lombok.Setter;
import lombok.Singular;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScope;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.List;
/**
@ -28,10 +32,10 @@ import java.util.List;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SetMyCommands extends BotApiMethodBoolean {
public class SetMyCommands extends BotApiMethod<Boolean> {
public static final String PATH = "setMyCommands";
private static final String COMMANDS_FIELD = "commands";
@ -66,12 +70,27 @@ public class SetMyCommands extends BotApiMethodBoolean {
return PATH;
}
@Override
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 commands", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (languageCode != null && languageCode.isEmpty()) {
throw new TelegramApiValidationException("LanguageCode parameter can't be empty string", this);
}
if (commands.isEmpty()) {
if (commands == null || commands.isEmpty()) {
throw new TelegramApiValidationException("Commands parameter can't be empty", this);
}
if (commands.size() > 100) {

View File

@ -1,50 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.description;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.description.BotDescription;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
/**
* @author Ruben Bermudez
* @version 6.6
* Use this method to get the current bot description for the given user language.
* Returns BotDescription on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GetMyDescription extends BotApiMethod<BotDescription> {
public static final String PATH = "getMyDescription";
private static final String LANGUAGE_CODE_FIELD = "language_code";
/**
* Optional
* A two-letter ISO 639-1 language code.
* If empty, the description will be applied to all users for whose language there is no dedicated description.
*/
@JsonProperty(LANGUAGE_CODE_FIELD)
private String languageCode;
@Override
public BotDescription deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, BotDescription.class);
}
@Override
public String getMethod() {
return PATH;
}
}

View File

@ -1,52 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.description;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.description.BotShortDescription;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
/**
* @author Ruben Bermudez
* @version 6.6
*
* Use this method to get the current bot short description for the given user language.
*
* Returns BotShortDescription on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GetMyShortDescription extends BotApiMethod<BotShortDescription> {
public static final String PATH = "getMyShortDescription";
private static final String LANGUAGE_CODE_FIELD = "language_code";
/**
* Optional
* A two-letter ISO 639-1 language code.
* If empty, the description will be applied to all users for whose language there is no dedicated description.
*/
@JsonProperty(LANGUAGE_CODE_FIELD)
private String languageCode;
@Override
public BotShortDescription deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, BotShortDescription.class);
}
@Override
public String getMethod() {
return PATH;
}
}

View File

@ -1,51 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.description;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
/**
* @author Ruben Bermudez
* @version 6.6
* Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SetMyDescription extends BotApiMethodBoolean {
public static final String PATH = "setMyDescription";
private static final String DESCRIPTION_FIELD = "description";
private static final String LANGUAGE_CODE_FIELD = "language_code";
/**
* Optional
* New bot description; 0-512 characters.
* Pass an empty string to remove the dedicated description for the given language.
*/
@JsonProperty(DESCRIPTION_FIELD)
private String description;
/**
* Optional
* A two-letter ISO 639-1 language code.
* If empty, the description will be applied to all users for whose language there is no dedicated description.
*/
@JsonProperty(LANGUAGE_CODE_FIELD)
private String languageCode;
@Override
public String getMethod() {
return PATH;
}
}

View File

@ -1,54 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.description;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
/**
* @author Ruben Bermudez
* @version 6.6
*
* Use this method to change the bot's short description, which is shown on the bot's
* profile page and is sent together with the link when users share the bot.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SetMyShortDescription extends BotApiMethodBoolean {
public static final String PATH = "setMyShortDescription";
private static final String SHORT_DESCRIPTION_FIELD = "short_description";
private static final String LANGUAGE_CODE_FIELD = "language_code";
/**
* Optional
* New short description for the bot; 0-120 characters.
* Pass an empty string to remove the dedicated short description for the given language.
*/
@JsonProperty(SHORT_DESCRIPTION_FIELD)
private String shortDescription;
/**
* Optional
* A two-letter ISO 639-1 language code.
* If empty, the short description will be applied to all users for whose language there is no dedicated short description.
*/
@JsonProperty(LANGUAGE_CODE_FIELD)
private String languageCode;
@Override
public String getMethod() {
return PATH;
}
}

View File

@ -1,80 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to close an open topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have
* the can_manage_topics administrator rights, unless it is the creator of the topic.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class CloseForumTopic extends BotApiMethodBoolean {
public static final String PATH = "closeForumTopic";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Unique identifier for the target message thread of the forum topic
*/
@JsonProperty(MESSAGETHREADID_FIELD)
@NonNull
private Integer messageThreadId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (messageThreadId <= 0) {
throw new TelegramApiValidationException("Message Thread Id can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class CloseForumTopicBuilder {
@Tolerate
public CloseForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,69 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.4
* Use this method to close an open 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class CloseGeneralForumTopic extends BotApiMethodBoolean {
public static final String PATH = "closeGeneralForumTopic";
private static final String CHATID_FIELD = "chat_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class CloseGeneralForumTopicBuilder {
@Tolerate
public CloseGeneralForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,103 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.forum.ForumTopic;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to create a topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* Returns information about the created topic as a ForumTopic object.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class CreateForumTopic extends BotApiMethod<ForumTopic> {
public static final String PATH = "createForumTopic";
private static final String CHATID_FIELD = "chat_id";
private static final String NAME_FIELD = "name";
private static final String ICONCOLOR_FIELD = "icon_color";
private static final String ICONCUSTOMEMOJIID_FIELD = "icon_custom_emoji_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Topic name, 1-128 characters
*/
@JsonProperty(NAME_FIELD)
@NonNull
private String name;
/**
* Optional.
* Color of the topic icon in RGB format. Currently,
* must be one of 0x6FB9F0, 0xFFD67E, 0xCB86DB, 0x8EEE98, 0xFF93B2, or 0xFB6F5F
*/
@JsonProperty(ICONCOLOR_FIELD)
private Integer iconColor;
/**
* Optional.
* Unique identifier of the custom emoji shown as the topic icon.
* Use getForumTopicIconStickers to get all allowed custom emoji identifiers
*/
@JsonProperty(ICONCUSTOMEMOJIID_FIELD)
private String iconCustomEmojiId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (name.isEmpty() || name.length() > 128) {
throw new TelegramApiValidationException("Name must be between 1 and 128 characters", this);
}
}
@Override
public String getMethod() {
return PATH;
}
@Override
public ForumTopic deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, ForumTopic.class);
}
public static class CreateForumTopicBuilder {
@Tolerate
public CreateForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,80 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to delete a forum topic along with all its messages in a
* forum supergroup chat. The bot must be an administrator in the chat
* for this to work and must have the can_delete_messages administrator rights.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class DeleteForumTopic extends BotApiMethodBoolean {
public static final String PATH = "deleteForumTopic";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Unique identifier for the target message thread of the forum topic
*/
@JsonProperty(MESSAGETHREADID_FIELD)
@NonNull
private Integer messageThreadId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (messageThreadId <= 0) {
throw new TelegramApiValidationException("Message Thread Id can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class DeleteForumTopicBuilder {
@Tolerate
public DeleteForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,106 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to edit name and icon of a topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have
* can_manage_topics administrator rights, unless it is the creator of the topic.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class EditForumTopic extends BotApiMethodBoolean {
public static final String PATH = "editForumTopic";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
private static final String NAME_FIELD = "name";
private static final String ICONCUSTOMEMOJIID_FIELD = "icon_custom_emoji_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Unique identifier for the target message thread of the forum topic
*/
@JsonProperty(MESSAGETHREADID_FIELD)
@NonNull
private Integer messageThreadId;
/**
* Optional.
* New topic name, 0-128 characters.
* If not specified or empty, the current name of the topic will be kept
*/
@JsonProperty(NAME_FIELD)
private String name;
/**
* Optional.
* New unique identifier of the custom emoji shown as the topic icon.
* Use getForumTopicIconStickers to get all allowed custom emoji identifiers.
* Pass an empty string to remove the icon.
* If not specified, the current icon will be kept
*/
@JsonProperty(ICONCUSTOMEMOJIID_FIELD)
private String iconCustomEmojiId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (name != null && !name.isEmpty()) {
if (name.length() > 128) {
throw new TelegramApiValidationException("Name must be less than 128 characters", this);
}
}
if (messageThreadId <= 0) {
throw new TelegramApiValidationException("Message Thread Id can't be empty", this);
}
if (iconCustomEmojiId.isEmpty()) {
throw new TelegramApiValidationException("Icon Custom Emoji Id can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class EditForumTopicBuilder {
@Tolerate
public EditForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,80 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.4
* Use this method to edit the name of the 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class EditGeneralForumTopic extends BotApiMethodBoolean {
public static final String PATH = "editGeneralForumTopic";
private static final String CHATID_FIELD = "chat_id";
private static final String NAME_FIELD = "name";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Optional.
* New topic name, 1-128 characters
*/
@JsonProperty(NAME_FIELD)
@NonNull
private String name;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (name.isEmpty() || name.length() > 128) {
throw new TelegramApiValidationException("Name must be between 1 and 128 characters", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class EditGeneralForumTopicBuilder {
@Tolerate
public EditGeneralForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,45 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.stickers.Sticker;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.util.ArrayList;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters.
* Returns an Array of Sticker objects.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor
@Builder
public class GetForumTopicIconStickers extends BotApiMethod<ArrayList<Sticker>> {
private static final String PATH = "getForumTopicIconStickers";
@Override
public void validate() throws TelegramApiValidationException {
}
@Override
public String getMethod() {
return PATH;
}
@Override
public ArrayList<Sticker> deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponseArray(answer, Sticker.class);
}
}

View File

@ -1,70 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.4
* Use this method to hide the 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* The topic will be automatically closed if it was open.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class HideGeneralForumTopic extends BotApiMethodBoolean {
public static final String PATH = "hideGeneralForumTopic";
private static final String CHATID_FIELD = "chat_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class HideGeneralForumTopicBuilder {
@Tolerate
public HideGeneralForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,81 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to reopen a closed topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must
* have the can_manage_topics administrator rights,
* unless it is the creator of the topic.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class ReopenForumTopic extends BotApiMethodBoolean {
public static final String PATH = "reopenForumTopic";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Unique identifier for the target message thread of the forum topic
*/
@JsonProperty(MESSAGETHREADID_FIELD)
@NonNull
private Integer messageThreadId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (messageThreadId <= 0) {
throw new TelegramApiValidationException("Message Thread Id can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class ReopenForumTopicBuilder {
@Tolerate
public ReopenForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,70 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.4
* Use this method to reopen a closed 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* The topic will be automatically unhidden if it was hidden.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class ReopenGeneralForumTopic extends BotApiMethodBoolean {
public static final String PATH = "reopenGeneralForumTopic";
private static final String CHATID_FIELD = "chat_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class ReopenGeneralForumTopicBuilder {
@Tolerate
public ReopenGeneralForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,69 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.4
* Use this method to unhide the 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class UnhideGeneralForumTopic extends BotApiMethodBoolean {
public static final String PATH = "unhideGeneralForumTopic";
private static final String CHATID_FIELD = "chat_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class UnhideGeneralForumTopicBuilder {
@Tolerate
public UnhideGeneralForumTopicBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,80 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.3
* Use this method to clear the list of pinned messages in a forum topic.
* The bot must be an administrator in the chat for this to work and must
* have the can_pin_messages administrator right in the supergroup.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class UnpinAllForumTopicMessages extends BotApiMethodBoolean {
public static final String PATH = "unpinAllForumTopicMessages";
private static final String CHATID_FIELD = "chat_id";
private static final String MESSAGETHREADID_FIELD = "message_thread_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHATID_FIELD)
@NonNull
private String chatId;
/**
* Unique identifier for the target message thread of the forum topic
*/
@JsonProperty(MESSAGETHREADID_FIELD)
@NonNull
private Integer messageThreadId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (messageThreadId <= 0) {
throw new TelegramApiValidationException("Message Thread Id can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class UnpinAllForumTopicMessagesBuilder {
@Tolerate
public UnpinAllForumTopicMessagesBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,70 +0,0 @@
package org.telegram.telegrambots.meta.api.methods.forum;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 6.8
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the
* can_pin_messages administrator right in the supergroup.
*
* Returns True on success.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@AllArgsConstructor
@Builder
public class UnpinAllGeneralForumTopicMessages extends BotApiMethodBoolean {
public static final String PATH = "unpinAllGeneralForumTopicMessages";
private static final String CHAT_ID_FIELD = "chat_id";
/**
* Unique identifier for the target chat or username
* of the target supergroup (in the format @supergroupusername)
*/
@JsonProperty(CHAT_ID_FIELD)
@NonNull
private String chatId;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
}
@Override
public String getMethod() {
return PATH;
}
public static class UnpinAllGeneralForumTopicMessagesBuilder {
@Tolerate
public UnpinAllGeneralForumTopicMessagesBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -17,6 +17,8 @@
package org.telegram.telegrambots.meta.api.methods.games;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -26,12 +28,13 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.games.GameHighScore;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.util.ArrayList;
/**
@ -51,7 +54,7 @@ import java.util.ArrayList;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
@ -64,20 +67,15 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
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)
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
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
private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message
@JsonProperty(USER_ID_FIELD)
@NonNull
private Long userId; ///<Target user id
@Tolerate
public void setChatId(Long chatId) {
this.chatId = chatId == null ? null : chatId.toString();
}
@Override
public String getMethod() {
return PATH;
@ -85,11 +83,24 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
@Override
public ArrayList<GameHighScore> deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponseArray(answer, GameHighScore.class);
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);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (userId == null) {
throw new TelegramApiValidationException("UserId parameter can't be empty", this);
}
if (inlineMessageId == null) {
if (chatId == null || chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId parameter can't be empty if inlineMessageId is not present", this);
@ -106,13 +117,4 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
}
}
}
public static class GetGameHighScoresBuilder {
@Tolerate
public GetGameHighScoresBuilder chatId(Long chatId) {
this.chatId = chatId == null ? null : chatId.toString();
return this;
}
}
}

View File

@ -18,6 +18,8 @@
package org.telegram.telegrambots.meta.api.methods.games;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -27,11 +29,13 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodSerializable;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.io.Serializable;
/**
@ -48,11 +52,11 @@ import java.io.Serializable;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class SetGameScore extends BotApiMethodSerializable {
public class SetGameScore extends BotApiMethod<Serializable> {
public static final String PATH = "setGameScore";
private static final String USER_ID_FIELD = "user_id";
@ -80,11 +84,6 @@ public class SetGameScore extends BotApiMethodSerializable {
@JsonProperty(FORCE_FIELD)
private Boolean force; ///< Optional. Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters
@Tolerate
public void setChatId(Long chatId) {
this.chatId = chatId == null ? null : chatId.toString();
}
@Override
public String getMethod() {
return PATH;
@ -92,13 +91,38 @@ public class SetGameScore extends BotApiMethodSerializable {
@Override
public Serializable deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponseMessageOrBoolean(answer);
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);
}
} 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);
}
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (userId == null) {
throw new TelegramApiValidationException("UserId parameter can't be empty", this);
}
if (score == null) {
throw new TelegramApiValidationException("Score parameter can't be empty", this);
}
if (inlineMessageId == null) {
if (chatId == null || chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId parameter can't be empty if inlineMessageId is not present", this);
@ -115,13 +139,4 @@ public class SetGameScore extends BotApiMethodSerializable {
}
}
}
public static class SetGameScoreBuilder {
@Tolerate
public SetGameScoreBuilder chatId(Long chatId) {
this.chatId = chatId == null ? null : chatId.toString();
return this;
}
}
}

View File

@ -1,18 +1,15 @@
package org.telegram.telegrambots.meta.api.methods.groupadministration;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.*;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 5.4
@ -24,10 +21,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@Builder
public class ApproveChatJoinRequest extends BotApiMethodBoolean {
public class ApproveChatJoinRequest extends BotApiMethod<Boolean> {
public static final String PATH = "approveChatJoinRequest";
private static final String CHATID_FIELD = "chat_id";
@ -40,16 +37,26 @@ public class ApproveChatJoinRequest extends BotApiMethodBoolean {
@NonNull
private Long userId; ///< Required. Unique identifier of the target user
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public String getMethod() {
return PATH;
}
@Override
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 approving chat join request", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
@ -59,13 +66,4 @@ public class ApproveChatJoinRequest extends BotApiMethodBoolean {
throw new TelegramApiValidationException("UserId can't be null or 0", this);
}
}
public static class ApproveChatJoinRequestBuilder {
@Tolerate
public ApproveChatJoinRequestBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -2,6 +2,7 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -11,10 +12,12 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
@ -34,11 +37,11 @@ import java.time.ZonedDateTime;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class BanChatMember extends BotApiMethodBoolean {
public class BanChatMember extends BotApiMethod<Boolean> {
public static final String PATH = "banChatMember";
private static final String CHATID_FIELD = "chat_id";
@ -66,10 +69,6 @@ public class BanChatMember extends BotApiMethodBoolean {
@JsonProperty(REVOKEMESSAGES_FIELD)
private Boolean revokeMessages;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@JsonIgnore
public void setUntilDateInstant(Instant instant) {
@ -91,23 +90,28 @@ public class BanChatMember extends BotApiMethodBoolean {
return PATH;
}
@Override
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);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
if (chatId == null || chatId.isEmpty()) {
throw new TelegramApiValidationException("ChatId can't be empty", this);
}
if (userId == 0) {
if (userId == null || userId == 0) {
throw new TelegramApiValidationException("UserId can't be null or 0", this);
}
}
public static class BanChatMemberBuilder {
@Tolerate
public BanChatMemberBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -2,19 +2,14 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodBoolean;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.*;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
@ -32,11 +27,11 @@ import java.time.ZonedDateTime;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class BanChatSenderChat extends BotApiMethodBoolean {
public class BanChatSenderChat extends BotApiMethod<Boolean> {
public static final String PATH = "banChatSenderChat";
private static final String CHATID_FIELD = "chat_id";
@ -56,11 +51,6 @@ public class BanChatSenderChat extends BotApiMethodBoolean {
@JsonProperty(UNTILDATE_FIELD)
private Integer untilDate;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@JsonIgnore
public void setUntilDateInstant(Instant instant) {
setUntilDate((int) instant.getEpochSecond());
@ -81,6 +71,21 @@ public class BanChatSenderChat extends BotApiMethodBoolean {
return PATH;
}
@Override
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 banning chat sender", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
public void validate() throws TelegramApiValidationException {
if (chatId.isEmpty()) {
@ -90,13 +95,4 @@ public class BanChatSenderChat extends BotApiMethodBoolean {
throw new TelegramApiValidationException("SenderChatId can't be null or 0", this);
}
}
public static class BanChatSenderChatBuilder {
@Tolerate
public BanChatSenderChatBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

View File

@ -1,6 +1,7 @@
package org.telegram.telegrambots.meta.api.methods.groupadministration;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
@ -10,12 +11,14 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.ChatInviteLink;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 5.1
@ -30,7 +33,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
@Getter
@Setter
@ToString
@NoArgsConstructor(force = true)
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Builder
@ -66,10 +69,6 @@ public class CreateChatInviteLink extends BotApiMethod<ChatInviteLink> {
@JsonProperty(CREATESJOINREQUEST_FIELD)
private Boolean createsJoinRequest;
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
}
@Override
public String getMethod() {
@ -78,7 +77,17 @@ public class CreateChatInviteLink extends BotApiMethod<ChatInviteLink> {
@Override
public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, ChatInviteLink.class);
try {
ApiResponse<ChatInviteLink> result = OBJECT_MAPPER.readValue(answer,
new TypeReference<ApiResponse<ChatInviteLink>>(){});
if (result.getOk()) {
return result.getResult();
} else {
throw new TelegramApiRequestException("Error creating invite link", result);
}
} catch (IOException e) {
throw new TelegramApiRequestException("Unable to deserialize response", e);
}
}
@Override
@ -96,13 +105,4 @@ public class CreateChatInviteLink extends BotApiMethod<ChatInviteLink> {
throw new TelegramApiValidationException("MemberLimit must be between 1 and 99999", this);
}
}
public static class CreateChatInviteLinkBuilder {
@Tolerate
public CreateChatInviteLinkBuilder chatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
return this;
}
}
}

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