Merge pull request #324 from addo37/dev

Update AbilityBot and write tutorial
This commit is contained in:
Ruben Bermudez 2017-11-15 18:32:49 +01:00 committed by GitHub
commit 41be63aed0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 938 additions and 698 deletions

View File

@ -2,5 +2,13 @@
* [[Getting Started]]
* [[Errors Handling]]
* [[FAQ]]
* AbilityBot
* [[Simple Example]]
* [[Hello Ability]]
* [[Using Replies]]
* [[Database Handling]]
* [[Bot Testing]]
* [[Bot Recovery]]
* [[Advanced]]
* [[Changelog]]
* [[How To Update]]
* [[How To Update]]

View File

@ -0,0 +1,34 @@
# Advanced
This will be more of a FAQ on some important notes before you embark on your next big bot project!
## Default Abilties
It is possible to declare "DEFAULT" abilities that process non-command messages. This is quite close to a reply. If a user says "Hey there" and the default ability is implemented, it will process this input.
```java
/**
* This ability has an extra "flag". It needs a photo to activate! This feature is activated by default if there is no /command given.
*/
public Ability sayNiceToPhoto() {
return Ability.builder()
.name(DEFAULT) // DEFAULT ability is executed if user did not specify a command -> Bot needs to have access to messages (check FatherBot)
.flag(PHOTO)
.privacy(PUBLIC)
.locality(ALL)
.input(0)
.action(ctx -> silent.send("Daaaaang, what a nice photo!", ctx.chatId()))
.build();
}
```
This ability will send a *"Daaaaang, what a nice photo!"* whenever the bot receives a photo. This is one use case where replies and abilities are interchangeable.
## The Global Flag
There is a global flag in AbilityBot that restricts the kind of "updates" it can process. The default implementation is passthrough - it allows all updates to be processed.
As an example, if you want to restrict the updates to photos only, then you may do:
```java
@Override
public boolean checkGlobalFlags(Update update) {
return Flag.PHOTO;
}
```

View File

@ -0,0 +1,8 @@
# Bot Recovery
With recovery, we specifically mean recovering the DB in-case of false data being committed. This is a neat feature supported by DBContext, you can /backup and /recover your bot whenever needed.
Once you /backup, the bot will respond back with a valid JSON object that represents all the data in the DB.
On /recover, the bot will ask for the JSON file. A reply to the message with the file attached will recover the bot with the previous state DB.
Try to experiment using the counter ability introduced in [[Database Handling|Database-Handling]]!

View File

@ -0,0 +1,193 @@
# Testing
It is super important to be able to test your bot prior to "release". In this case, release would mean that you're presenting the bot to your designated audience. Nobody likes bots that are buggy, faulty and do clumsy actions.
As developers, we appreciate frameworks that provide an ease in testing. Of course, you might no tbe able to catch all bugs that can occur in production, but you'd be far more comfortable in releasing a bot that is well-tested.
## Limitations
The issue with the basic API is that all DefaultAbsSender methods (the bot methods you use to send message) are statically defined without interfacing. If you declare your bot and try to do some testing, you won't be able to know that you've executed a method... unless you actually execute it! As an example:
```java
public void sayHello() {
SendMessage snd = new SendMessage();
snd.setText("Hello!");
snd.setChatId(123);
try {
// We want to test that we actually sent out this message with the contents "Hello!"
execute(snd);
} catch (TelegramApiException e) {}
}
```
This is how you would define a method that says hello in the basic API. How do you go around testing it? If you do attempt to Junit test this method, what will you be testing? If you change the method signature to return the string sent, then you can test the hello message content. However, can you test that you've actually `executed` the command?
## Mock Testing
*This section assumes you're familiar with mock testing. Mock testing is basically replacing a real object X with a fake object Y (a mock) of the same type. By doing that, you're able to test whether certain functions were executed.*
Obviously, you can't, but there's a twist to it. You can always mock the whole bot, but with that you're also mocking the method `sayHello` when you actually need its contents and code! We need to extract the bot-sending-specific-methods into their own interface and try to mock that interface instead.
## MessageSender Interface
All ability bots declare two utility objects.
### The Sender Object
The `sender` object is an implementation of the [MessageSender](../../telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/MessageSender.java) interface. The interface mirrors
all the bot sending methods. A user can supply his own MessageSender, but the AbilityBot module specifies a [DefaultSender](../../telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/DefaultSender.java) As you might guess, the default sender is simply a proxy for the bot API methods.
### The Silent Object
The `silent` object is exactly like the sender object, but silent. Its methods return `Optional<T>`. On exception, it will be an empty optional. The sender object is provided to reduce verboseness of the code (reducing try-catch blocks with something more elegant).
## AbilityBot Testing
Let's suppose that you have an ability that says "Hello World!" declared as such:
```java
public Ability saysHelloWorld() {
return Ability.builder()
.name("hello")
.info("Says hello world!")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> {
try{
sender.execute(new SendMessage().setChatId(ctx.getChatId()).setText("Hello World!"));
} catch (TelgramApiException e){}
})
.build();
}
```
The test for this ability would be:
```java
@Test
public void canSayHelloWorld() {
Update upd = new Update();
// Create a new EndUser - EndUser is a class similar to Telegram User, but contains
// some utility methods like fullName() and shortName() for ease of use
EndUser endUser = EndUser.endUser(USER_ID, "Abbas", "Abou Daya", "addo37");
// This is the context that you're used to, it is the necessary conumer item for the ability
MessageContext context = MessageContext.newContext(upd, endUser, CHAT_ID);
// We consume a context in the lamda declaration, so we pass the context to the action logic
bot.saysHelloWorld().action().accept(context);
// We verify that the sender was called only ONCE and sent Hello World to CHAT_ID
// The sender here is a mock!
Mockito.verify(sender, times(1)).send("Hello World!", CHAT_ID);
}
```
The comments explain every step in the test. In a single assertion with Mockito, we assert that:
* We've sent the message once
* The message content was "Hello World!"
* The message was sent to a specific chat ID
There are some preparations involved before we can perform such a test. Here's the full code snippet for running this test:
```java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.db.MapDBContext;
import org.telegram.abilitybots.api.objects.EndUser;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.telegrambots.api.objects.Update;
import static org.mockito.Mockito.*;
public class ExampleBotTest {
public static final int USER_ID = 1337;
public static final long CHAT_ID = 1337L;
// Your bot handle here
private ExampleBot bot;
// Your sender here
private MessageSender sender;
@Before
public void setUp() {
// Create your bot
bot = new ExampleBot();
// Create a new sender as a mock
sender = mock(MessageSender.class);
// Set your bot sender to the mocked sender
// THIS is the line that prevents your bot from communicating with Telegram servers when it's running its own abilities
// All method calls will go through the mocked interface -> which would do nothing except logging the fact that you've called this function with the specific arguments
bot.sender = sender;
}
@Test
public void canSayHelloWorld() {
Update upd = new Update();
// Create a new EndUser - EndUser is a class similar to Telegram User, but contains
// some utility methods like fullName() and shortName() for ease of use
EndUser endUser = EndUser.endUser(USER_ID, "Abbas", "Abou Daya", "addo37");
// This is the context that you're used to, it is the necessary conumer item for the ability
MessageContext context = MessageContext.newContext(upd, endUser, CHAT_ID);
// We consume a context in the lamda declaration, so we pass the context to the action logic
bot.saysHelloWorld().action().accept(context);
// We verify that the sender was called only ONCE and sent Hello World to CHAT_ID
// The sender here is a mock!
Mockito.verify(sender, times(1)).send("Hello World!", CHAT_ID);
}
}
```
## DB Abilities
What if the ability performs a DB interaction? We don't want testing procedures to modify the database of the bot.
This is where we differentiate between an online DB and an offline DB. The online DB is the default DB when the bot is instantiated. However, AbilityBot supplies a constructor that reveals a DBContext argument. We can supply another instance of a DB (an offline one) so that the tests don't modify our online DB.
In ExampleBot, we do:
```java
public ExampleBot(DBContext db) {
super(BOT_TOKEN, BOT_USERNAME, db);
}
```
In ExampleBotTest:
```java
public class ExampleBotTest {
...
private DBContext db;
private MessageSender sender;
@Before
public void setUp() {
// Offline instance will get deleted at JVM shutdown
db = MapDBContext.offlineInstance("test");
bot = new ExampleBot(db);
...
}
...
// We should clear the DB after every test as such
@After
public void tearDown() {
db.clear();
}
}
```
## Silent Testing
As mentioned before, we also have another object that is able to send messages silently called `silent`. The constructor of the silent sender requires a MessageSender object. If your abilities use the `silent` object, be sure to:
```java
public class ExampleBotTest {
...
private DBContext db;
private MessageSender sender;
@Before
public void setUp() {
bot = new ExampleBot(db);
sender = mock(MessageSender.class);
bot.silent = new SilentSender(sender);
...
}
...
}
```
Do note that in your test assertions, don't use the silent object. Mocked assertion require the mock object. If you recall, the silent object uses the sender object, so your tests will still be correct if you're asserting on the `sender` object rather than the silent one.

View File

@ -0,0 +1,57 @@
# Database Handling
AbilityBots come with an embedded DB. Users are free to implement their own databases via implementing the [DBContext](../../telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/DBContext.java) class.
The abstraction has multiple constructors to accommodate user-defined implementations of [DBContext](../../telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/DBContext.java) and [MessageSender](../../telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/MessageSender.java). We'll talk about the message sender interface in the [[Bot Testing|Bot-Testing]] section.
## Example
We'll be introducing an ability that maintains a special counter for every user. At every /increment, the user will receive a message with the previous number + 1. We'll initially start from zero and increment upwards.
```java
/**
* Use the database to fetch a count per user and increments.
* <p>
* Use /count to experiment with this ability.
*/
public Ability useDatabaseToCountPerUser() {
return Ability.builder()
.name("count")
.info("Increments a counter per user")
.privacy(PUBLIC)
.locality(ALL)
.input(0)
.action(ctx -> {
// db.getMap takes in a string, this must be unique and the same everytime you want to call the exact same map
// TODO: Using integer as a key in this db map is not recommended, it won't be serialized/deserialized properly if you ever decide to recover/backup db
Map<String, Integer> countMap = db.getMap("COUNTERS");
int userId = ctx.user().id();
// Get and increment counter, put it back in the map
Integer counter = countMap.compute(String.valueOf(userId), (id, count) -> count == null ? 1 : ++count);
/*
Without lambdas implementation of incrementing
int counter;
if (countMap.containsKey(userId))
counter = countMap.get(userId) + 1;
else
counter = 1;
countMap.put(userId, counter);
*/
// Send formatted will enable markdown
String message = String.format("%s, your count is now *%d*!", ctx.user().shortName(), counter);
silent.send(message, ctx.chatId());
})
.build();
}
```
After successfully adding that ability to your bot, try to /count and watch as the number increases at every message.
Other important functions in the `db` object:
* getSet - gets a set of data
* getList - gets a list of data
* summary - gets a summary of the present structs
Be sure to check out [DBContext](../../telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/DBContext.java) for all the implemented methods.

View File

@ -0,0 +1,117 @@
Motivation
----------
After implementing your own bot via the basic API, you'll quickly realize how verbose it is. Once you get multiple commands up and running, your routing logic and handling per command start to become cumbersome.
Dealing with a basic API has its advantages and disadvantages. Obviously, there's nothing hidden. If it's there on Telegram, it's here in the Java API. However, can we do better than just a basic API?
When you want to implement a feature in your bot, you start asking these questions:
* The **WHO**?
* Who is going to use this feature? Should they be allowed to use all the features?
* The **WHAT**?
* Under what conditions should I allow this feature?
* Should the message have a photo? A document? Oh, maybe a callback query?
* The **HOW**?
* If my bot crashes, how can I resume my operation?
* Should I utilize a DB?
* How can I separate logic execution of different features?
* How can I unit-test my feature outside of Telegram?
Every time you write a command or a feature, you will need to answer these questions and ensure that your feature logic works.
Ability
----------------------
Simply put, the abilities module was developed to make your life easier. Whether you're counting numbers, fetching images or handling large data, AbilityBot is here to augment your development.
The AbilityBot abstraction intends to provide the following:
* New feature is a new **Ability**, a new method - no fuss, zero overhead, no cross-code with other features
* Argument length on a command is as easy as changing a single integer
* Privacy settings per Ability - access levels to Abilities! User | Admin | Creator
* Embedded database - available for every declared ability
* Proxy sender interface - enhances testability; accurate results pre-release
Alongside these exciting core features of the AbilityBot, the following have been introduced:
* The bot automatically maintains an up-to-date set of all the users who have contacted the bot
* Backup and recovery for the DB
* Ban and unban users from accessing your bots
* Promote and demote users as bot administrators
Abstraction
--------------
The AbilityBot abstraction defines a new object, named **Ability**. An ability combines conditions, flags, action, post-action and replies.
As an example, here is a code-snippet of an ability that creates a ***/hello*** command:
```java
public Ability sayHelloWorld() {
return Ability
.builder()
.name("hello")
.info("says hello world!")
.input(0)
.locality(USER)
.privacy(ADMIN)
.action(ctx -> silent.send("Hello world!", ctx.chatId()))
.post(ctx -> silent.send("Bye world!", ctx.chatId()))
.build();
}
```
Here is a breakdown of the above code snippet:
* *.name()* - the name of the ability (essentially, this is the command)
* *.info()* - provides information for the command
* More on this later, but it basically centralizes command information in-code.
* *.input()* - the number of input arguments needed, 0 is for do-not-care
* *.locality()* - this answers where you want the ability to be available
* In GROUP, USER private chats or ALL (both)
* *.privacy()* - this answers who you want to access your ability
* CREATOR, ADMIN, or everyone as PUBLIC
* *.action()* - the feature logic resides here (a lambda function that takes a *MessageContext*)
* *MessageContext* provides fast accessors for the **chatId**, **user** and the underlying **update**. It also conforms to the specifications of the basic API.
* *.post()* - the logic executed **after** your main action finishes execution
The `silent` object is created with every AbilityBot. It provides helper and utility functions that execute "silently". In this context, silent execution of bot API methods are ones that don't throw an exception. However, all methods in silent return an Optional object. If an exception occurs, the optional would be empty. The developer would still be able to
manage errors by checking for the presence of the optional `.isPresent()`. This decreases verboseness while still being able to execute routines correctly.
Do note that:
* You can still access the bot's methods and functions inside the lambda function in your action definition. That includes all the DefaultAbsSender methods execute, executeAsync, setChatPhoto, etc....
* `silent` uses another accessible object named `sender`. Refer to [[Bot Testing|Bot-Testing]] for the main use case of sender as an interface to all bot methods.
With abilities, you can specify the context of the feature. If you only want the command to be available for groups, then you can set `.locality(GROUP)`. If it is a very sensitive command that only admins should have access to, then set `.privacy(ADMIN)`.
This allows for abilities with protection guarantees on who can use it and where it can be used.
All abilities have access to the following important methods.
* `users()` - Returns a map of ID -> User
* `userIds()` - Returns a map of Username -> ID
* `blacklist()` - Returns a set of IDs of banned users
* `admins()` - Returns a set of IDs of bot administrators
`users()` and `userIds()` accumulate data of all the users who have contacted your bot. Even when a user changes some information (like his or her nickname), the bot will be able to detect the change and update its DB accordingly.
The following is a snippet of how this ability would look like with the plain basic API.
```java
@Override
public void onUpdateReceived(Update update) {
// Global checks...
// Switch, if, logic to route to hello world method
// Execute method
}
public void sayHelloWorld(Update update) {
if (!update.hasMessage() || !update.getMessage().isUserMessage() || !update.getMessage().hasText() || update.getMessage.getText().isEmpty())
return;
User maybeAdmin = update.getMessage().getFrom();
/* Query DB for if the user is an admin, can be SQL, Reddis, Ignite, etc...
If user is not an admin, then return here.
*/
SendMessage snd = new SendMessage();
snd.setChatId(update.getMessage().getChatId());
snd.setText("Hello world!");
try {
execute(snd);
} catch (TelegramApiException e) {
BotLogger.error("Could not send message", TAG, e);
}
}
```
I will leave you the choice to decide between the two snippets as to which is more **readable**, **writable** and **testable**.

View File

@ -0,0 +1,117 @@
# AbilityBot
This section of the tutorial will present a barebone example on creating your first AbilityBot! It is highly recommended to write your very first bot via the [[Getting Started|Getting-Started]]. That will give you a sense of how the basic API allows you to handle commands and features.
## Dependencies
As with any Java project, you will need to set your dependencies.
* **Maven**
```xml
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-abilties</artifactId>
<version>3.4</version>
</dependency>
```
* **Gradle**
```groovy
compile group: 'org.telegram', name: 'telegrambots-abilties', version: '3.4'
```
* [JitPack](https://jitpack.io/#rubenlagus/TelegramBots)
* [Plain Imports/Jars](https://github.com/rubenlagus/TelegramBots/releases)
## Bot Declaration
To use the abilities module, you will need to extend AbilityBot.
```java
import org.telegram.abilitybots.api.bot.AbilityBot;
public class HelloBot extends AbilityBot {
...
}
```
## Bot Implementation
Bot token and nickname are passed via the constructor and don't require an override.
```java
public HelloBot(String token, String username) {
super(token, username);
}
```
However, since the token and username of a bot are usually constants, you can do the following:
```java
public static String BOT_TOKEN = "...";
public static String BOT_USERNAME = "...";
public HelloBot() {
super(BOT_TOKEN, BOT_USERNAME);
}
```
AbilityBot forces a single implementation of creator ID. This ID corresponds to you, the bot developer. The bot needs to know its master since it has sensitive commands that only the master can use.
So, if your Telegram ID Is 123456789, then add the following method:
```java
@Override
public int creatorId() {
return 123456789;
}
```
That's it to have a valid, compilable and ready to be deployed bot. However, your bot doesn't have a single command to use. Let's declare one!
## Hello Ability
To add a feature to your bot, you add an ability. That's it! No routing from onUpdateReceived, no separate checks and no crossovers. Let's write our first ability that simply says hello!
```java
public Ability sayHelloWorld() {
return Ability
.builder()
.name("hello")
.info("says hello world!")
.locality(ALL)
.privacy(PUBLIC)
.action(ctx -> silent.send("Hello world!", ctx.chatId()))
.build();
}
```
Save your questions for later! Abilities are described in detail in the following sections of the tutorial.
## Running Your Bot
Running the bot is just like running the regular Telegram bots. Create a Java class similar to the one below.
```java
public class Application {
public static void main(String[] args) {
// Initializes dependencies necessary for the base bot - Guice
ApiContextInitializer.init();
// Create the TelegramBotsApi object to register your bots
TelegramBotsApi botsApi = new TelegramBotsApi();
try {
// Register your newly created AbilityBot
botsApi.registerBot(new HelloBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
```
If you're in doubt that you're missing some code, the full code example can be inspected [here](https://github.com/addo37/ExampleBots/tree/master/src/main/java/org/telegram/examplebots).
## Testing Your Bot
Go ahead and "/hello" to your bot. It should respond back with "Hello World!".
Since you've implemented an AbilityBot, you get **factory abilities** as well. Try:
* /commands - Prints all commands supported by the bot
* This will essentially print "hello - says hello world!". Yes! This is the information we supplied to the ability. The bot prints the commands in the format accepted by BotFather. So, whenever you change, add or remove commands, you can simply /commands and forward that message to BotFather.
* /claim - Claims this bot
* /backup - returns a backup of the bot database
* /recover - recovers the database
* /promote @username - promotes user to bot admin
* /demote @username - demotes bot admin to user
* /ban @username - bans the user from accessing your bot commands and features
* /unban @username - lifts the ban from the user
## 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?
The following sections of the tutorial will describe in detail **abilities** and **replies**. It will also bring into attention how to effectively in-code test your bot, handle the embedded DB and administer your user access levels.

View File

@ -0,0 +1,77 @@
# Replies
A reply is AbilityBot's swiss army knife. It comes in two variants and is able to handle all possible use cases.
## Standalone Reply
Standalone replies are replies declared on their own without being attached to an ability. Here's an example of a possible reply declaration:
```java
/**
* A reply that says "yuck" to all images sent to the bot.
*/
public Reply sayYuckOnImage() {
// getChatId is a public utility function in rg.telegram.abilitybots.api.util.AbilityUtils
Consumer<Update> action = upd -> silent.send("Yuck", getChatId(upd));
return Reply.of(upd, Flag.PHOTO)
}
```
Let's break this down. Replies require a lambda function (consumer) that is able to consume our update. In this case, our consumer simply fetches the chatId
from the update and sends a "Yuck" message. `Reply.of(upd)` would be enough. However, replies accept a var-arg of type `Predicate<Update>`. These predicates are the necessary conditions so that the bot acts the reply. We specify Flag.PHOTO to let the bot know
that we only want the reply to act on images only! The Flag is a public enum at your disposal. It contains other conditionals like checking for videos, messages, voice, documents, etc...
## Ability Reply
In exactly the same manner, you are able to attach replies to abilities. This way you can localize replies that relate to the same ability.
```java
public Ability playWithMe() {
String playMessage = "Play with me!";
return Ability.builder()
.name("play")
.info("Do you want to play with me?")
.privacy(PUBLIC)
.locality(ALL)
.input(0)
.action(ctx -> sender.forceReply(playMessage, ctx.chatId()))
// The signature of a reply is -> (Consumer<Update> action, Predicate<Update>... conditions)
// So, we first declare the action that takes an update (NOT A MESSAGECONTEXT) like the action above
// The reason of that is that a reply can be so versatile depending on the message, context becomes an inefficient wrapping
.reply(upd -> {
// Prints to console
System.out.println("I'm in a reply!");
// Sends message
sender.send("It's been nice playing with you!", upd.getMessage().getChatId());
},
// Now we start declaring conditions, MESSAGE is a member of the enum Flag class
// That class contains out-of-the-box predicates for your replies!
// MESSAGE means that the update must have a message
// This is imported statically, Flag.MESSAGE
MESSAGE,
// REPLY means that the update must be a reply, Flag.REPLY
REPLY,
// A new predicate user-defined
// The reply must be to the bot
isReplyToBot(),
// If we process similar logic in other abilities, then we have to make this reply specific to this message
// The reply is to the playMessage
isReplyToMessage(playMessage)
)
// You can add more replies by calling .reply(...)
.build();
}
private Predicate<Update> isReplyToMessage(String message) {
return upd -> {
Message reply = upd.getMessage().getReplyToMessage();
return reply.hasText() && reply.getText().equalsIgnoreCase(message);
};
}
private Predicate<Update> isReplyToBot() {
return upd -> upd.getMessage().getReplyToMessage().getFrom().getUserName().equalsIgnoreCase(getBotUsername());
}
```
In this example, we showcase how we can supply our own predicates. The two new predicates are `isReplyToMessage` and `isReplyToBot`.
The checks are made so that, once you execute your logic there is no need to check for the validity of the reply.
They were all made once the action logic is being executed.

View File

@ -3,8 +3,9 @@ package org.telegram.abilitybots.api.bot;
import org.apache.commons.io.IOUtils;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.*;
import org.telegram.abilitybots.api.sender.DefaultMessageSender;
import org.telegram.abilitybots.api.sender.DefaultSender;
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;
@ -110,6 +111,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
// DB and sender
protected final DBContext db;
protected MessageSender sender;
protected SilentSender silent;
// Bot token and username
private final String botToken;
@ -121,13 +123,16 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
// Reply registry
private List<Reply> replies;
public abstract int creatorId();
protected AbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions botOptions) {
super(botOptions);
this.botToken = botToken;
this.botUsername = botUsername;
this.db = db;
this.sender = new DefaultMessageSender(this);
this.sender = new DefaultSender(this);
silent = new SilentSender(sender);
registerAbilities();
}
@ -144,8 +149,6 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
this(botToken, botUsername, onlineInstance(botUsername));
}
public abstract int creatorId();
/**
* @return the map of ID -> EndUser
*/
@ -217,15 +220,15 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
}
/**
* Test the update against the provided global flags. The default implementation requires a {@link Flag#MESSAGE}.
* Test the update against the provided global flags. The default implementation is a passthrough to all updates.
* <p>
* This method should be <b>overridden</b> if the user wants updates that don't require a MESSAGE to pass through.
* This method should be <b>overridden</b> if the user wants to restrict bot usage to only certain updates.
*
* @param update a Telegram {@link Update}
* @return <tt>true</tt> if the update satisfies the global flags
*/
protected boolean checkGlobalFlags(Update update) {
return MESSAGE.test(update);
return true;
}
/**
@ -268,7 +271,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
try {
return getUser(username).id();
} catch (IllegalStateException ex) {
sender.send(format("Sorry, I could not find the user [%s].", username), chatId);
silent.send(format("Sorry, I could not find the user [%s].", username), chatId);
throw propagate(ex);
}
}
@ -307,7 +310,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
.reduce((a, b) -> format("%s%n%s", a, b))
.orElse("No public commands found.");
sender.send(commands, ctx.chatId());
silent.send(commands, ctx.chatId());
})
.build();
}
@ -360,7 +363,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> sender.forceReply(RECOVERY_MESSAGE, ctx.chatId()))
.action(ctx -> silent.forceReply(RECOVERY_MESSAGE, ctx.chatId()))
.reply(update -> {
Long chatId = update.getMessage().getChatId();
String fileId = update.getMessage().getDocument().getFileId();
@ -368,13 +371,13 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
try (FileReader reader = new FileReader(downloadFileWithId(fileId))) {
String backupData = IOUtils.toString(reader);
if (db.recover(backupData)) {
sender.send(RECOVER_SUCCESS, chatId);
silent.send(RECOVER_SUCCESS, chatId);
} else {
sender.send("Oops, something went wrong during recovery.", chatId);
silent.send("Oops, something went wrong during recovery.", chatId);
}
} catch (Exception e) {
BotLogger.error("Could not recover DB from backup", TAG, e);
sender.send("I have failed to recover.", chatId);
silent.send("I have failed to recover.", chatId);
}
}, MESSAGE, DOCUMENT, REPLY, isReplyTo(RECOVERY_MESSAGE))
.build();
@ -410,10 +413,10 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
Set<Integer> blacklist = blacklist();
if (blacklist.contains(userId))
sender.sendMd(format("%s is already *banned*.", bannedUser), ctx.chatId());
silent.sendMd(format("%s is already *banned*.", bannedUser), ctx.chatId());
else {
blacklist.add(userId);
sender.sendMd(format("%s is now *banned*.", bannedUser), ctx.chatId());
silent.sendMd(format("%s is now *banned*.", bannedUser), ctx.chatId());
}
})
.post(commitTo(db))
@ -438,9 +441,9 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
Set<Integer> blacklist = blacklist();
if (!blacklist.remove(userId))
sender.sendMd(format("@%s is *not* on the *blacklist*.", username), ctx.chatId());
silent.sendMd(format("@%s is *not* on the *blacklist*.", username), ctx.chatId());
else {
sender.sendMd(format("@%s, your ban has been *lifted*.", username), ctx.chatId());
silent.sendMd(format("@%s, your ban has been *lifted*.", username), ctx.chatId());
}
})
.post(commitTo(db))
@ -462,10 +465,10 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
Set<Integer> admins = admins();
if (admins.contains(userId))
sender.sendMd(format("@%s is already an *admin*.", username), ctx.chatId());
silent.sendMd(format("@%s is already an *admin*.", username), ctx.chatId());
else {
admins.add(userId);
sender.sendMd(format("@%s has been *promoted*.", username), ctx.chatId());
silent.sendMd(format("@%s has been *promoted*.", username), ctx.chatId());
}
}).post(commitTo(db))
.build();
@ -486,9 +489,9 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
Set<Integer> admins = admins();
if (admins.remove(userId)) {
sender.sendMd(format("@%s has been *demoted*.", username), ctx.chatId());
silent.sendMd(format("@%s has been *demoted*.", username), ctx.chatId());
} else {
sender.sendMd(format("@%s is *not* an *admin*.", username), ctx.chatId());
silent.sendMd(format("@%s is *not* an *admin*.", username), ctx.chatId());
}
})
.post(commitTo(db))
@ -513,10 +516,10 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
long chatId = ctx.chatId();
if (admins.contains(id))
sender.send("You're already my master.", chatId);
silent.send("You're already my master.", chatId);
else {
admins.add(id);
sender.send("You're now my master.", chatId);
silent.send("You're now my master.", chatId);
}
} else {
// This is not a joke
@ -614,7 +617,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
boolean isOk = abilityTokens == 0 || (tokens.length > 0 && tokens.length == abilityTokens);
if (!isOk)
sender.send(String.format("Sorry, this feature requires %d additional %s.", abilityTokens, abilityTokens == 1 ? "input" : "inputs"), getChatId(trio.a()));
silent.send(String.format("Sorry, this feature requires %d additional %s.", abilityTokens, abilityTokens == 1 ? "input" : "inputs"), getChatId(trio.a()));
return isOk;
}
@ -626,7 +629,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
boolean isOk = abilityLocality == ALL || locality == abilityLocality;
if (!isOk)
sender.send(String.format("Sorry, %s-only feature.", abilityLocality.toString().toLowerCase()), getChatId(trio.a()));
silent.send(String.format("Sorry, %s-only feature.", abilityLocality.toString().toLowerCase()), getChatId(trio.a()));
return isOk;
}
@ -641,7 +644,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
boolean isOk = privacy.compareTo(trio.b().privacy()) >= 0;
if (!isOk)
sender.send(String.format("Sorry, %s-only feature.", trio.b().privacy().toString().toLowerCase()), getChatId(trio.a()));
silent.send(String.format("Sorry, %s-only feature.", trio.b().privacy().toString().toLowerCase()), getChatId(trio.a()));
return isOk;
}
@ -730,7 +733,7 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
boolean checkMessageFlags(Trio<Update, Ability, String[]> trio) {
Ability ability = trio.b();
Update update = trio.a();
// The following variable is required to avoid bug #JDK-8044546
BiFunction<Boolean, Predicate<Update>, Boolean> flagAnd = (flag, nextFlag) -> flag && nextFlag.test(update);
return ability.flags().stream()
@ -738,6 +741,6 @@ public abstract class AbilityBot extends TelegramLongPollingBot {
}
private File downloadFileWithId(String fileId) throws TelegramApiException {
return sender.downloadFile(sender.getFile(new GetFile().setFileId(fileId)));
return sender.downloadFile(sender.execute(new GetFile().setFileId(fileId)));
}
}

View File

@ -149,7 +149,7 @@ public final class Ability {
private Consumer<MessageContext> consumer;
private Consumer<MessageContext> postConsumer;
private List<Reply> replies;
private Flag[] flags;
private Predicate<Update>[] flags;
private AbilityBuilder() {
replies = newArrayList();
@ -170,7 +170,7 @@ public final class Ability {
return this;
}
public AbilityBuilder flag(Flag... flags) {
public AbilityBuilder flag(Predicate<Update>... flags) {
this.flags = flags;
return this;
}

View File

@ -1,493 +0,0 @@
package org.telegram.abilitybots.api.sender;
import org.telegram.telegrambots.api.methods.*;
import org.telegram.telegrambots.api.methods.games.GetGameHighScores;
import org.telegram.telegrambots.api.methods.games.SetGameScore;
import org.telegram.telegrambots.api.methods.groupadministration.*;
import org.telegram.telegrambots.api.methods.pinnedmessages.PinChatMessage;
import org.telegram.telegrambots.api.methods.pinnedmessages.UnpinChatMessage;
import org.telegram.telegrambots.api.methods.send.*;
import org.telegram.telegrambots.api.methods.updates.DeleteWebhook;
import org.telegram.telegrambots.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageCaption;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageReplyMarkup;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.api.objects.*;
import org.telegram.telegrambots.api.objects.games.GameHighScore;
import org.telegram.telegrambots.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.logging.BotLogger;
import org.telegram.telegrambots.updateshandlers.DownloadFileCallback;
import org.telegram.telegrambots.updateshandlers.SentCallback;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
/**
* The default implementation of the {@link MessageSender}. This serves as a proxy to the {@link DefaultAbsSender} methods.
* <p>Most of the methods below will be directly calling the bot's similar functions. However, there are some methods introduced to ease sending messages such as:</p>
* <ol>
* <li>{@link DefaultMessageSender#sendMd(String, long)} - with markdown</li>
* <li>{@link DefaultMessageSender#send(String, long)} - without markdown</li>
* </ol>
*
* @author Abbas Abou Daya
*/
public class DefaultMessageSender implements MessageSender {
private static final String TAG = MessageSender.class.getName();
private DefaultAbsSender bot;
public DefaultMessageSender(DefaultAbsSender bot) {
this.bot = bot;
}
@Override
public Optional<Message> send(String message, long id) {
return doSendMessage(message, id, false);
}
@Override
public Optional<Message> sendMd(String message, long id) {
return doSendMessage(message, id, true);
}
@Override
public Optional<Message> forceReply(String message, long id) {
SendMessage msg = new SendMessage();
msg.setText(message);
msg.setChatId(id);
msg.setReplyMarkup(new ForceReplyKeyboard());
return optionalSendMessage(msg);
}
@Override
public Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException {
return bot.execute(answerInlineQuery);
}
@Override
public Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException {
return bot.execute(sendChatAction);
}
@Override
public Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException {
return bot.execute(forwardMessage);
}
@Override
public Message sendLocation(SendLocation sendLocation) throws TelegramApiException {
return bot.execute(sendLocation);
}
@Override
public Message sendVenue(SendVenue sendVenue) throws TelegramApiException {
return bot.execute(sendVenue);
}
@Override
public Message sendContact(SendContact sendContact) throws TelegramApiException {
return bot.execute(sendContact);
}
@Override
public Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException {
return bot.execute(kickChatMember);
}
@Override
public Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException {
return bot.execute(unbanChatMember);
}
@Override
public Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException {
return bot.execute(leaveChat);
}
@Override
public Chat getChat(GetChat getChat) throws TelegramApiException {
return bot.execute(getChat);
}
@Override
public List<ChatMember> getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException {
return bot.execute(getChatAdministrators);
}
@Override
public ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException {
return bot.execute(getChatMember);
}
@Override
public Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException {
return bot.execute(getChatMemberCount);
}
@Override
public Boolean setChatPhoto(SetChatPhoto setChatPhoto) throws TelegramApiException {
return bot.setChatPhoto(setChatPhoto);
}
@Override
public Boolean deleteChatPhoto(DeleteChatPhoto deleteChatPhoto) throws TelegramApiException {
return bot.execute(deleteChatPhoto);
}
@Override
public void deleteChatPhoto(DeleteChatPhoto deleteChatPhoto, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(deleteChatPhoto, sentCallback);
}
@Override
public Boolean pinChatMessage(PinChatMessage pinChatMessage) throws TelegramApiException {
return bot.execute(pinChatMessage);
}
@Override
public void pinChatMessage(PinChatMessage pinChatMessage, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(pinChatMessage, sentCallback);
}
@Override
public Boolean unpinChatMessage(UnpinChatMessage unpinChatMessage) throws TelegramApiException {
return bot.execute(unpinChatMessage);
}
@Override
public void unpinChatMessage(UnpinChatMessage unpinChatMessage, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(unpinChatMessage, sentCallback);
}
@Override
public Boolean promoteChatMember(PromoteChatMember promoteChatMember) throws TelegramApiException {
return bot.execute(promoteChatMember);
}
@Override
public void promoteChatMember(PromoteChatMember promoteChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(promoteChatMember, sentCallback);
}
@Override
public Boolean restrictChatMember(RestrictChatMember restrictChatMember) throws TelegramApiException {
return bot.execute(restrictChatMember);
}
@Override
public void restrictChatMember(RestrictChatMember restrictChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(restrictChatMember, sentCallback);
}
@Override
public Boolean setChatDescription(SetChatDescription setChatDescription) throws TelegramApiException {
return bot.execute(setChatDescription);
}
@Override
public void setChatDescription(SetChatDescription setChatDescription, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(setChatDescription, sentCallback);
}
@Override
public Boolean setChatTite(SetChatTitle setChatTitle) throws TelegramApiException {
return bot.execute(setChatTitle);
}
@Override
public void setChatTite(SetChatTitle setChatTitle, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(setChatTitle, sentCallback);
}
@Override
public String exportChatInviteLink(ExportChatInviteLink exportChatInviteLink) throws TelegramApiException {
return bot.execute(exportChatInviteLink);
}
@Override
public void exportChatInviteLinkAsync(ExportChatInviteLink exportChatInviteLink, SentCallback<String> sentCallback) throws TelegramApiException {
bot.executeAsync(exportChatInviteLink, sentCallback);
}
@Override
public Boolean deleteMessage(DeleteMessage deleteMessage) throws TelegramApiException {
return bot.execute(deleteMessage);
}
@Override
public void deleteMessageAsync(DeleteMessage deleteMessage, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(deleteMessage, sentCallback);
}
@Override
public Serializable editMessageText(EditMessageText editMessageText) throws TelegramApiException {
return bot.execute(editMessageText);
}
@Override
public Serializable editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException {
return bot.execute(editMessageCaption);
}
@Override
public Serializable editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException {
return bot.execute(editMessageReplyMarkup);
}
@Override
public Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException {
return bot.execute(answerCallbackQuery);
}
@Override
public UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException {
return bot.execute(getUserProfilePhotos);
}
@Override
public java.io.File downloadFile(String path) throws TelegramApiException {
return bot.downloadFile(path);
}
@Override
public void downloadFileAsync(String path, DownloadFileCallback<String> callback) throws TelegramApiException {
bot.downloadFileAsync(path, callback);
}
@Override
public java.io.File downloadFile(File file) throws TelegramApiException {
return bot.downloadFile(file);
}
@Override
public void downloadFileAsync(File file, DownloadFileCallback<File> callback) throws TelegramApiException {
bot.downloadFileAsync(file, callback);
}
@Override
public File getFile(GetFile getFile) throws TelegramApiException {
return bot.execute(getFile);
}
@Override
public User getMe() throws TelegramApiException {
return bot.getMe();
}
@Override
public WebhookInfo getWebhookInfo() throws TelegramApiException {
return bot.getWebhookInfo();
}
@Override
public Serializable setGameScore(SetGameScore setGameScore) throws TelegramApiException {
return bot.execute(setGameScore);
}
@Override
public Serializable getGameHighScores(GetGameHighScores getGameHighScores) throws TelegramApiException {
return bot.execute(getGameHighScores);
}
@Override
public Message sendGame(SendGame sendGame) throws TelegramApiException {
return bot.execute(sendGame);
}
@Override
public Boolean deleteWebhook(DeleteWebhook deleteWebhook) throws TelegramApiException {
return bot.execute(deleteWebhook);
}
@Override
public Message sendMessage(SendMessage sendMessage) throws TelegramApiException {
return bot.execute(sendMessage);
}
@Override
public void sendMessageAsync(SendMessage sendMessage, SentCallback<Message> sentCallback) throws TelegramApiException {
bot.executeAsync(sendMessage, sentCallback);
}
@Override
public void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(answerInlineQuery, sentCallback);
}
@Override
public void sendChatActionAsync(SendChatAction sendChatAction, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(sendChatAction, sentCallback);
}
@Override
public void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback<Message> sentCallback) throws TelegramApiException {
bot.executeAsync(forwardMessage, sentCallback);
}
@Override
public void sendLocationAsync(SendLocation sendLocation, SentCallback<Message> sentCallback) throws TelegramApiException {
bot.executeAsync(sendLocation, sentCallback);
}
@Override
public void sendVenueAsync(SendVenue sendVenue, SentCallback<Message> sentCallback) throws TelegramApiException {
bot.executeAsync(sendVenue, sentCallback);
}
@Override
public void sendContactAsync(SendContact sendContact, SentCallback<Message> sentCallback) throws TelegramApiException {
bot.executeAsync(sendContact, sentCallback);
}
@Override
public void kickMemberAsync(KickChatMember kickChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(kickChatMember, sentCallback);
}
@Override
public void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(unbanChatMember, sentCallback);
}
@Override
public void leaveChatAsync(LeaveChat leaveChat, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(leaveChat, sentCallback);
}
@Override
public void getChatAsync(GetChat getChat, SentCallback<Chat> sentCallback) throws TelegramApiException {
bot.executeAsync(getChat, sentCallback);
}
@Override
public void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback<ArrayList<ChatMember>> sentCallback) throws TelegramApiException {
bot.executeAsync(getChatAdministrators, sentCallback);
}
@Override
public void getChatMemberAsync(GetChatMember getChatMember, SentCallback<ChatMember> sentCallback) throws TelegramApiException {
bot.executeAsync(getChatMember, sentCallback);
}
@Override
public void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback<Integer> sentCallback) throws TelegramApiException {
bot.executeAsync(getChatMemberCount, sentCallback);
}
@Override
public void editMessageTextAsync(EditMessageText editMessageText, SentCallback<Serializable> sentCallback) throws TelegramApiException {
bot.executeAsync(editMessageText, sentCallback);
}
@Override
public void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback<Serializable> sentCallback) throws TelegramApiException {
bot.executeAsync(editMessageCaption, sentCallback);
}
@Override
public void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback<Serializable> sentCallback) throws TelegramApiException {
bot.executeAsync(editMessageReplyMarkup, sentCallback);
}
@Override
public void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(answerCallbackQuery, sentCallback);
}
@Override
public void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback<UserProfilePhotos> sentCallback) throws TelegramApiException {
bot.executeAsync(getUserProfilePhotos, sentCallback);
}
@Override
public void getFileAsync(GetFile getFile, SentCallback<File> sentCallback) throws TelegramApiException {
bot.executeAsync(getFile, sentCallback);
}
@Override
public void getMeAsync(SentCallback<User> sentCallback) throws TelegramApiException {
bot.getMeAsync(sentCallback);
}
@Override
public void getWebhookInfoAsync(SentCallback<WebhookInfo> sentCallback) throws TelegramApiException {
bot.getWebhookInfoAsync(sentCallback);
}
@Override
public void setGameScoreAsync(SetGameScore setGameScore, SentCallback<Serializable> sentCallback) throws TelegramApiException {
bot.executeAsync(setGameScore, sentCallback);
}
@Override
public void getGameHighScoresAsync(GetGameHighScores getGameHighScores, SentCallback<ArrayList<GameHighScore>> sentCallback) throws TelegramApiException {
bot.executeAsync(getGameHighScores, sentCallback);
}
@Override
public void sendGameAsync(SendGame sendGame, SentCallback<Message> sentCallback) throws TelegramApiException {
bot.executeAsync(sendGame, sentCallback);
}
@Override
public void deleteWebhook(DeleteWebhook deleteWebhook, SentCallback<Boolean> sentCallback) throws TelegramApiException {
bot.executeAsync(deleteWebhook, sentCallback);
}
@Override
public Message sendDocument(SendDocument sendDocument) throws TelegramApiException {
return bot.sendDocument(sendDocument);
}
@Override
public Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException {
return bot.sendPhoto(sendPhoto);
}
@Override
public Message sendVideo(SendVideo sendVideo) throws TelegramApiException {
return bot.sendVideo(sendVideo);
}
@Override
public Message sendSticker(SendSticker sendSticker) throws TelegramApiException {
return bot.sendSticker(sendSticker);
}
@Override
public Message sendAudio(SendAudio sendAudio) throws TelegramApiException {
return bot.sendAudio(sendAudio);
}
@Override
public Message sendVoice(SendVoice sendVoice) throws TelegramApiException {
return bot.sendVoice(sendVoice);
}
private Optional<Message> doSendMessage(String txt, long groupId, boolean format) {
SendMessage smsg = new SendMessage();
smsg.setChatId(groupId);
smsg.setText(txt);
smsg.enableMarkdown(format);
return optionalSendMessage(smsg);
}
private Optional<Message> optionalSendMessage(SendMessage smsg) {
try {
return ofNullable(sendMessage(smsg));
} catch (TelegramApiException e) {
BotLogger.error("Could not send message", TAG, e);
return empty();
}
}
}

View File

@ -0,0 +1,139 @@
package org.telegram.abilitybots.api.sender;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.groupadministration.SetChatPhoto;
import org.telegram.telegrambots.api.methods.send.*;
import org.telegram.telegrambots.api.methods.stickers.AddStickerToSet;
import org.telegram.telegrambots.api.methods.stickers.CreateNewStickerSet;
import org.telegram.telegrambots.api.methods.stickers.UploadStickerFile;
import org.telegram.telegrambots.api.objects.File;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.api.objects.WebhookInfo;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.updateshandlers.DownloadFileCallback;
import org.telegram.telegrambots.updateshandlers.SentCallback;
import java.io.Serializable;
/**
* The default implementation of the {@link MessageSender}. This serves as a proxy to the {@link DefaultAbsSender} methods.
*
* @author Abbas Abou Daya
*/
public class DefaultSender implements MessageSender {
private static final String TAG = MessageSender.class.getName();
private DefaultAbsSender bot;
public DefaultSender(DefaultAbsSender bot) {
this.bot = bot;
}
@Override
public <T extends Serializable, Method extends BotApiMethod<T>, Callback extends SentCallback<T>> void executeAsync(Method method, Callback callback) throws TelegramApiException {
bot.executeAsync(method, callback);
}
@Override
public <T extends Serializable, Method extends BotApiMethod<T>> T execute(Method method) throws TelegramApiException {
return bot.execute(method);
}
@Override
public Boolean addStickerToSet(AddStickerToSet addStickerToSet) throws TelegramApiException {
return bot.addStickerToSet(addStickerToSet);
}
@Override
public Boolean createNewStickerSet(CreateNewStickerSet createNewStickerSet) throws TelegramApiException {
return bot.createNewStickerSet(createNewStickerSet);
}
@Override
public File uploadStickerFile(UploadStickerFile uploadStickerFile) throws TelegramApiException {
return bot.uploadStickerFile(uploadStickerFile);
}
@Override
public Boolean setChatPhoto(SetChatPhoto setChatPhoto) throws TelegramApiException {
return bot.setChatPhoto(setChatPhoto);
}
@Override
public java.io.File downloadFile(String path) throws TelegramApiException {
return bot.downloadFile(path);
}
@Override
public void downloadFileAsync(String path, DownloadFileCallback<String> callback) throws TelegramApiException {
bot.downloadFileAsync(path, callback);
}
@Override
public java.io.File downloadFile(File file) throws TelegramApiException {
return bot.downloadFile(file);
}
@Override
public void downloadFileAsync(File file, DownloadFileCallback<File> callback) throws TelegramApiException {
bot.downloadFileAsync(file, callback);
}
@Override
public User getMe() throws TelegramApiException {
return bot.getMe();
}
@Override
public WebhookInfo getWebhookInfo() throws TelegramApiException {
return bot.getWebhookInfo();
}
@Override
public void getMeAsync(SentCallback<User> sentCallback) throws TelegramApiException {
bot.getMeAsync(sentCallback);
}
@Override
public void getWebhookInfoAsync(SentCallback<WebhookInfo> sentCallback) throws TelegramApiException {
bot.getWebhookInfoAsync(sentCallback);
}
@Override
public Message sendDocument(SendDocument sendDocument) throws TelegramApiException {
return bot.sendDocument(sendDocument);
}
@Override
public Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException {
return bot.sendPhoto(sendPhoto);
}
@Override
public Message sendVideo(SendVideo sendVideo) throws TelegramApiException {
return bot.sendVideo(sendVideo);
}
@Override
public Message sendSticker(SendSticker sendSticker) throws TelegramApiException {
return bot.sendSticker(sendSticker);
}
@Override
public Message sendAudio(SendAudio sendAudio) throws TelegramApiException {
return bot.sendAudio(sendAudio);
}
@Override
public Message sendVoice(SendVoice sendVoice) throws TelegramApiException {
return bot.sendVoice(sendVoice);
}
@Override
public Message sendVideoNote(SendVideoNote sendVideoNote) throws TelegramApiException {
return null;
}
}

View File

@ -1,28 +1,21 @@
package org.telegram.abilitybots.api.sender;
import org.telegram.telegrambots.api.methods.*;
import org.telegram.telegrambots.api.methods.games.GetGameHighScores;
import org.telegram.telegrambots.api.methods.games.SetGameScore;
import org.telegram.telegrambots.api.methods.groupadministration.*;
import org.telegram.telegrambots.api.methods.pinnedmessages.PinChatMessage;
import org.telegram.telegrambots.api.methods.pinnedmessages.UnpinChatMessage;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.groupadministration.SetChatPhoto;
import org.telegram.telegrambots.api.methods.send.*;
import org.telegram.telegrambots.api.methods.updates.DeleteWebhook;
import org.telegram.telegrambots.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageCaption;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageReplyMarkup;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.api.objects.*;
import org.telegram.telegrambots.api.objects.games.GameHighScore;
import org.telegram.telegrambots.api.methods.stickers.AddStickerToSet;
import org.telegram.telegrambots.api.methods.stickers.CreateNewStickerSet;
import org.telegram.telegrambots.api.methods.stickers.UploadStickerFile;
import org.telegram.telegrambots.api.objects.File;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.api.objects.WebhookInfo;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.updateshandlers.DownloadFileCallback;
import org.telegram.telegrambots.updateshandlers.SentCallback;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* A sender interface that replicates {@link DefaultAbsSender} methods.
@ -30,86 +23,19 @@ import java.util.Optional;
* @author Abbas Abou Daya
*/
public interface MessageSender {
Optional<Message> send(String message, long id);
Optional<Message> sendMd(String message, long id);
<T extends Serializable, Method extends BotApiMethod<T>, Callback extends SentCallback<T>> void executeAsync(Method method, Callback callback) throws TelegramApiException;
Optional<Message> forceReply(String message, long id);
<T extends Serializable, Method extends BotApiMethod<T>> T execute(Method method) throws TelegramApiException;
Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException;
Boolean addStickerToSet(AddStickerToSet addStickerToSet) throws TelegramApiException;
Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException;
public Boolean createNewStickerSet(CreateNewStickerSet createNewStickerSet) throws TelegramApiException;
Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException;
Message sendLocation(SendLocation sendLocation) throws TelegramApiException;
Message sendVenue(SendVenue sendVenue) throws TelegramApiException;
Message sendContact(SendContact sendContact) throws TelegramApiException;
Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException;
Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException;
Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException;
Chat getChat(GetChat getChat) throws TelegramApiException;
List<ChatMember> getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException;
ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException;
Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException;
public File uploadStickerFile(UploadStickerFile uploadStickerFile) throws TelegramApiException;
Boolean setChatPhoto(SetChatPhoto setChatPhoto) throws TelegramApiException;
Boolean deleteChatPhoto(DeleteChatPhoto deleteChatPhoto) throws TelegramApiException;
void deleteChatPhoto(DeleteChatPhoto deleteChatPhoto, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Boolean pinChatMessage(PinChatMessage pinChatMessage) throws TelegramApiException;
void pinChatMessage(PinChatMessage pinChatMessage, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Boolean unpinChatMessage(UnpinChatMessage unpinChatMessage) throws TelegramApiException;
void unpinChatMessage(UnpinChatMessage unpinChatMessage, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Boolean promoteChatMember(PromoteChatMember promoteChatMember) throws TelegramApiException;
void promoteChatMember(PromoteChatMember promoteChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Boolean restrictChatMember(RestrictChatMember restrictChatMember) throws TelegramApiException;
void restrictChatMember(RestrictChatMember restrictChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Boolean setChatDescription(SetChatDescription setChatDescription) throws TelegramApiException;
void setChatDescription(SetChatDescription setChatDescription, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Boolean setChatTite(SetChatTitle setChatTitle) throws TelegramApiException;
void setChatTite(SetChatTitle setChatTitle, SentCallback<Boolean> sentCallback) throws TelegramApiException;
String exportChatInviteLink(ExportChatInviteLink exportChatInviteLink) throws TelegramApiException;
void exportChatInviteLinkAsync(ExportChatInviteLink exportChatInviteLink, SentCallback<String> sentCallback) throws TelegramApiException;
Boolean deleteMessage(DeleteMessage deleteMessage) throws TelegramApiException;
void deleteMessageAsync(DeleteMessage deleteMessage, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Serializable editMessageText(EditMessageText editMessageText) throws TelegramApiException;
Serializable editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException;
Serializable editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException;
Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException;
UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException;
java.io.File downloadFile(String path) throws TelegramApiException;
void downloadFileAsync(String path, DownloadFileCallback<String> callback) throws TelegramApiException;
@ -118,83 +44,25 @@ public interface MessageSender {
void downloadFileAsync(File file, DownloadFileCallback<File> callback) throws TelegramApiException;
File getFile(GetFile getFile) throws TelegramApiException;
User getMe() throws TelegramApiException;
WebhookInfo getWebhookInfo() throws TelegramApiException;
Serializable setGameScore(SetGameScore setGameScore) throws TelegramApiException;
Serializable getGameHighScores(GetGameHighScores getGameHighScores) throws TelegramApiException;
Message sendGame(SendGame sendGame) throws TelegramApiException;
Boolean deleteWebhook(DeleteWebhook deleteWebhook) throws TelegramApiException;
Message sendMessage(SendMessage sendMessage) throws TelegramApiException;
void sendMessageAsync(SendMessage sendMessage, SentCallback<Message> sentCallback) throws TelegramApiException;
void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback<Boolean> sentCallback) throws TelegramApiException;
void sendChatActionAsync(SendChatAction sendChatAction, SentCallback<Boolean> sentCallback) throws TelegramApiException;
void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback<Message> sentCallback) throws TelegramApiException;
void sendLocationAsync(SendLocation sendLocation, SentCallback<Message> sentCallback) throws TelegramApiException;
void sendVenueAsync(SendVenue sendVenue, SentCallback<Message> sentCallback) throws TelegramApiException;
void sendContactAsync(SendContact sendContact, SentCallback<Message> sentCallback) throws TelegramApiException;
void kickMemberAsync(KickChatMember kickChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException;
void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback<Boolean> sentCallback) throws TelegramApiException;
void leaveChatAsync(LeaveChat leaveChat, SentCallback<Boolean> sentCallback) throws TelegramApiException;
void getChatAsync(GetChat getChat, SentCallback<Chat> sentCallback) throws TelegramApiException;
void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback<ArrayList<ChatMember>> sentCallback) throws TelegramApiException;
void getChatMemberAsync(GetChatMember getChatMember, SentCallback<ChatMember> sentCallback) throws TelegramApiException;
void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback<Integer> sentCallback) throws TelegramApiException;
void editMessageTextAsync(EditMessageText editMessageText, SentCallback<Serializable> sentCallback) throws TelegramApiException;
void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback<Serializable> sentCallback) throws TelegramApiException;
void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback<Serializable> sentCallback) throws TelegramApiException;
void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback<Boolean> sentCallback) throws TelegramApiException;
void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback<UserProfilePhotos> sentCallback) throws TelegramApiException;
void getFileAsync(GetFile getFile, SentCallback<File> sentCallback) throws TelegramApiException;
void getMeAsync(SentCallback<User> sentCallback) throws TelegramApiException;
void getWebhookInfoAsync(SentCallback<WebhookInfo> sentCallback) throws TelegramApiException;
void setGameScoreAsync(SetGameScore setGameScore, SentCallback<Serializable> sentCallback) throws TelegramApiException;
void getGameHighScoresAsync(GetGameHighScores getGameHighScores, SentCallback<ArrayList<GameHighScore>> sentCallback) throws TelegramApiException;
void sendGameAsync(SendGame sendGame, SentCallback<Message> sentCallback) throws TelegramApiException;
void deleteWebhook(DeleteWebhook deleteWebhook, SentCallback<Boolean> sentCallback) throws TelegramApiException;
Message sendDocument(SendDocument sendDocument) throws TelegramApiException;
Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException;
Message sendVideo(SendVideo sendVideo) throws TelegramApiException;
Message sendSticker(SendSticker sendSticker) throws TelegramApiException;
Message sendAudio(SendAudio sendAudio) throws TelegramApiException;
Message sendVoice(SendVoice sendVoice) throws TelegramApiException;
Message sendVideoNote(SendVideoNote sendVideoNote) throws TelegramApiException;
Message sendSticker(SendSticker sendSticker) throws TelegramApiException;
}

View File

@ -0,0 +1,71 @@
package org.telegram.abilitybots.api.sender;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.logging.BotLogger;
import java.io.Serializable;
import java.util.Optional;
/**
* A silent sender that returns {@link Optional} objects upon execution. Mainly used to decrease verboseness of exception handling.
*
* @author Abbas Abou Daya
*/
public class SilentSender {
private static final String TAG = SilentSender.class.getSimpleName();
private final MessageSender sender;
public SilentSender(MessageSender sender) {
this.sender = sender;
}
public Optional<Message> send(String message, long id) {
return doSendMessage(message, id, false);
}
public Optional<Message> sendMd(String message, long id) {
return doSendMessage(message, id, true);
}
public Optional<Message> forceReply(String message, long id) {
SendMessage msg = new SendMessage();
msg.setText(message);
msg.setChatId(id);
msg.setReplyMarkup(new ForceReplyKeyboard());
return execute(msg);
}
public <T extends Serializable, Method extends BotApiMethod<T>> Optional<T> execute(Method method) {
try {
return Optional.ofNullable(sender.execute(method));
} catch (TelegramApiException e) {
BotLogger.error("Could not execute bot API method", TAG, e);
return Optional.empty();
}
}
public <T extends Serializable, Method extends BotApiMethod<T>> Optional<T> executeAsync(Method method) {
try {
return Optional.ofNullable(sender.execute(method));
} catch (TelegramApiException e) {
BotLogger.error("Could not execute bot API method", TAG, e);
return Optional.empty();
}
}
private Optional<Message> doSendMessage(String txt, long groupId, boolean format) {
SendMessage smsg = new SendMessage();
smsg.setChatId(groupId);
smsg.setText(txt);
smsg.enableMarkdown(format);
return execute(smsg);
}
}

View File

@ -2,14 +2,15 @@ package org.telegram.abilitybots.api.bot;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.*;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.sender.SilentSender;
import org.telegram.abilitybots.api.util.Pair;
import org.telegram.abilitybots.api.util.Trio;
import org.telegram.telegrambots.api.objects.*;
@ -25,9 +26,11 @@ import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;
import static java.util.Collections.emptySet;
import static org.apache.commons.io.FileUtils.deleteQuietly;
import static org.apache.commons.lang3.ArrayUtils.addAll;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.telegram.abilitybots.api.bot.AbilityBot.RECOVERY_MESSAGE;
@ -54,13 +57,18 @@ public class AbilityBotTest {
private DefaultBot bot;
private DBContext db;
private MessageSender sender;
private SilentSender silent;
@Before
public void setUp() {
db = offlineInstance("db");
bot = new DefaultBot(EMPTY, EMPTY, db);
sender = mock(MessageSender.class);
bot.setSender(sender);
silent = mock(SilentSender.class);
bot.sender = sender;
bot.silent = silent;
}
@Test
@ -69,7 +77,7 @@ public class AbilityBotTest {
bot.onUpdateReceived(update);
verify(sender, times(1)).send(format("Sorry, %s-only feature.", "admin"), MUSER.id());
verify(silent, times(1)).send(format("Sorry, %s-only feature.", "admin"), MUSER.id());
}
@Test
@ -78,7 +86,7 @@ public class AbilityBotTest {
bot.onUpdateReceived(update);
verify(sender, times(1)).send(format("Sorry, %s-only feature.", "group"), MUSER.id());
verify(silent, times(1)).send(format("Sorry, %s-only feature.", "group"), MUSER.id());
}
@ -88,7 +96,7 @@ public class AbilityBotTest {
bot.onUpdateReceived(update);
verify(sender, times(1)).send(format("Sorry, this feature requires %d additional inputs.", 4), MUSER.id());
verify(silent, times(1)).send(format("Sorry, this feature requires %d additional inputs.", 4), MUSER.id());
}
@Test
@ -97,7 +105,7 @@ public class AbilityBotTest {
// False means the update was not pushed down the stream since it has been consumed by the reply
assertFalse(bot.filterReply(update));
verify(sender, times(1)).send("reply", MUSER.id());
verify(silent, times(1)).send("reply", MUSER.id());
}
@Test
@ -105,6 +113,7 @@ public class AbilityBotTest {
MessageContext context = defaultContext();
bot.backupDB().action().accept(context);
deleteQuietly(new java.io.File("backup.json"));
verify(sender, times(1)).sendDocument(any());
}
@ -115,10 +124,10 @@ public class AbilityBotTest {
Object backup = getDbBackup();
java.io.File backupFile = createBackupFile(backup);
when(sender.downloadFile(Matchers.any(File.class))).thenReturn(backupFile);
when(sender.downloadFile(any(File.class))).thenReturn(backupFile);
bot.recoverDB().replies().get(0).actOn(update);
verify(sender, times(1)).send(RECOVER_SUCCESS, GROUP_ID);
verify(silent, times(1)).send(RECOVER_SUCCESS, GROUP_ID);
assertEquals("Bot recovered but the DB is still not in sync", db.getSet(TEST), newHashSet(TEST));
assertTrue("Could not delete backup file", backupFile.delete());
}
@ -401,13 +410,9 @@ public class AbilityBotTest {
}
@Test
public void canCheckGlobalFlags() {
public void defaultGlobalFlagIsTrue() {
Update update = mock(Update.class);
Message message = mock(Message.class);
when(update.hasMessage()).thenReturn(true);
when(update.getMessage()).thenReturn(message);
assertEquals("Unexpected result when checking for locality", true, bot.checkGlobalFlags(update));
assertEquals("Unexpected result when checking for the default global flags", true, bot.checkGlobalFlags(update));
}
@Test(expected = ArithmeticException.class)
@ -492,7 +497,7 @@ public class AbilityBotTest {
bot.reportCommands().action().accept(context);
verify(sender, times(1)).send("default - dis iz default command", GROUP_ID);
verify(silent, times(1)).send("default - dis iz default command", GROUP_ID);
}
@After

View File

@ -1,10 +1,8 @@
package org.telegram.abilitybots.api.bot;
import com.google.common.annotations.VisibleForTesting;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Ability;
import org.telegram.abilitybots.api.objects.Ability.AbilityBuilder;
import org.telegram.abilitybots.api.sender.MessageSender;
import static org.telegram.abilitybots.api.objects.Ability.builder;
import static org.telegram.abilitybots.api.objects.Flag.CALLBACK_QUERY;
@ -38,8 +36,8 @@ public class DefaultBot extends AbilityBot {
return getDefaultBuilder()
.name(DEFAULT)
.info("dis iz default command")
.reply(upd -> sender.send("reply", upd.getMessage().getChatId()), MESSAGE, update -> update.getMessage().getText().equals("must reply"))
.reply(upd -> sender.send("reply", upd.getCallbackQuery().getMessage().getChatId()), CALLBACK_QUERY)
.reply(upd -> silent.send("reply", upd.getMessage().getChatId()), MESSAGE, update -> update.getMessage().getText().equals("must reply"))
.reply(upd -> silent.send("reply", upd.getCallbackQuery().getMessage().getChatId()), CALLBACK_QUERY)
.build();
}
@ -70,9 +68,4 @@ public class DefaultBot extends AbilityBot {
public Ability testAbility() {
return getDefaultBuilder().build();
}
@VisibleForTesting
void setSender(MessageSender sender) {
this.sender = sender;
}
}

View File

@ -0,0 +1,43 @@
package org.telegram.abilitybots.api.sender;
import org.junit.Before;
import org.junit.Test;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import java.util.Optional;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SilentSenderTest {
private SilentSender silent;
private MessageSender sender;
@Before
public void setUp() {
sender = mock(MessageSender.class);
silent = new SilentSender(sender);
}
@Test
public void returnsEmptyOnError() throws TelegramApiException {
when(sender.execute(any())).thenThrow(TelegramApiException.class);
Optional execute = silent.execute(null);
assertFalse("Execution of a bot API method with execption results in a nonempty optional", execute.isPresent());
}
@Test
public void returnOptionalOnSuccess() throws TelegramApiException {
String data = "data";
when(sender.execute(any())).thenReturn(data);
Optional execute = silent.execute(null);
assertEquals("Silent execution resulted in a different object", data, execute.get());
}
}