Merge branch 'dev' into slf4j

This commit is contained in:
Ruben Bermudez 2019-10-12 01:02:15 +01:00 committed by GitHub
commit 15fe637998
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 1544 additions and 581 deletions

View File

@ -8,7 +8,10 @@
* [[Simple Example]]
* [[Hello Ability]]
* [[Using Replies]]
* [[Ability Toggle]]
* [[State Machines]]
* [[Database Handling]]
* [[Ability Extensions]]
* [[Bot Testing]]
* [[Bot Recovery]]
* [[Advanced]]

View File

@ -0,0 +1,40 @@
# Ability Extensions
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 {
public Ability () {
return Ability.builder()
.name("nice")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> silent.send("You're awesome!", ctx.chatId())
);
}
}
public class MrBadGuy implements AbilityExtension {
public Ability () {
return Ability.builder()
.name("notnice")
.privacy(PUBLIC)
.locality(ALL)
.action(ctx -> silent.send("You're horrible!", ctx.chatId())
);
}
}
public class YourAwesomeBot implements AbilityBot {
// Constructor for your bot
public AbilityExtension goodGuy() {
return new MrGoodGuy();
}
public AbilityExtension badGuy() {
return new MrBadGuy();
}
// Override creatorId
}
```

View File

@ -0,0 +1,42 @@
# Ability Toggle
Well, what if you don't like all the default abilities that AbilityBot supplies? Fear not, you are able to disable all of them, even rename them if you will!
You may pass a custom toggle to your abilitybot constructor to customize how these abilities get registered.
## The Barebone Toggle
The barebone toggle is used to **turn off** all the default abilities that come with the bot (ban, unban, demote, promte, etc...). To use the barebone toggle, call your super constructor with:
```java
import org.telegram.abilitybots.api.toggle.BareboneToggle;
public class YourAwesomeBot extends AbilityBot {
public YourAwesomeBot(String token, String username) {
BareboneToggle toggle = new BareboneToggle();
super(token, username, toggle);
}
// Override ceatorId()
}
```
Obviously, you can export this as a parameter that you can pass to your bot's constructor.
## The Custom Toggle
The custom toggle allows you to customize or turn off the names of the abilities that the abilitybot exposes.
```java
import org.telegram.abilitybots.api.toggle.CustomToggle;
public class YourAwesomeBot extends AbilityBot {
public YourAwesomeBot(String token, String username) {
CustomToggle toggle = new CustomToggle()
.turnOff("ban")
.toggle("promote", "upgrade");
super(token, username, toggle);
}
// Override ceatorId()
}
```
With these changes, the ability "ban" is no longer available and the "promote" ability has been renamed to "upgrade".
## The Default Toggle
The default toggle is automatically used if the user does not specify a toggle. The default toggle allows all the abilities to be effective and unchanged.

View File

@ -0,0 +1,134 @@
# State Machines
AbilityBot supports state machines using ReplyFlows. Internally, they set and transition the state of the user based on their actions so far.
Developers may declare this flow control in either a bottom-up or a top-down approach. If you're already familiar with what a `Reply` is, consider ReplyFlows as the cherry on top.
## Usage
A ReplyFlow can not be directly instantiated; it must be built. First, let's create
some basic replies.
```java
Reply saidLeft = Reply.of(upd ->
silent.send("Sir, I have gone left.", getChatId(upd)),
hasMessageWith("left"));
Reply saidRight = Reply.of(upd ->
silent.send("Sir, I have gone right.", getChatId(upd)),
hasMessageWith("right"));
```
The first `Reply` effectively replies to any message that has the text "left". Once such a message is received, the
bot replies with "Sir, I have gone left". Likewise, the bot acts for when "right" is encountered.
What if now, you'd like to protect those two replies behind one more reply? Let's say, the bot first should ask the user to give it directions.
This means that people can't tell your bot to turn left or right UNLESS the bot asks for directions. Let's trigger that when the user sends "wake up" to the bot!
```java
// We instantiate a ReplyFlow builder with our internal db (DBContext instance) passed
// State is always preserved in the db of the bot and remains even after termination
ReplyFlow.builder(db)
// Just like replies, a ReplyFlow can take an action, here we want to send a
// statement to prompt the user for directions!
.action(upd -> silent.send("Command me to go left or right!", getChatId(upd)))
// We should only trigger this flow when the user says "wake up"
.onlyIf(hasMessageWith("wake up"))
// The next method takes in an object of type Reply.
// Here we chain our replies together
.next(saidLeft)
// We chain one more reply, which is when the user commands your bot to go right
.next(saidRight)
// Finally, we build our ReplyFlow
.build();
```
For the sake of completeness, here's the auxiliary method `hasMessageWith`.
```java
private Predicate<Update> hasMessageWith(String msg) {
return upd -> upd.getMessage().getText().equalsIgnoreCase(msg);
}
```
To run this example in your own AbilityBot, just have a method return that ReplyFlow we just built. Yup, it's that easy, just like how you're used to
building replies and abilities.
## More Complex States
Let's say that your bot becomes naughty when the user asks it to go left. We want the bot to say "I don't know how to go left." when the user commands it to go left. We would also like to chain more commands after this state. Here's
how that's done.
We must create a new ReplyFlow that would be chained to the initial one. Here's what our left flow would look like.
```java
ReplyFlow leftflow = ReplyFlow.builder(db)
.action(upd -> silent.send("I don't know how to go left.", getChatId(upd)))
.onlyIf(hasMessageWith("left"))
.next(saidLeft)
.build();
```
And now, saidLeft reply becomes:
```java
Reply saidLeft = Reply.of(upd -> silent.send("Sir, I have gone left.", getChatId(upd)),
hasMessageWith("go left or else"));
```
Now, after your naughty bot retaliates, the user can say "go left or else" to force the bot to go left. Awesome, our logic now looks like this:
<div align="center">
![Alt text](./img/replyflow_diagram.svg)
<img src="./img/replyflow_diagram.svg">
</div>
## Complete Example
```java
public static class ReplyFlowBot extends AbilityBot {
public class ReplyFlowBot extends AbilityBot {
public ReplyFlowBot(String botToken, String botUsername) {
super(botToken, botUsername);
}
@Override
public int creatorId() {
return <YOUR ID HERE>;
}
public ReplyFlow directionFlow() {
Reply saidLeft = Reply.of(upd -> silent.send("Sir, I have gone left.", getChatId(upd)),
hasMessageWith("go left or else"));
ReplyFlow leftflow = ReplyFlow.builder(db)
.action(upd -> silent.send("I don't know how to go left.", getChatId(upd)))
.onlyIf(hasMessageWith("left"))
.next(saidLeft).build();
Reply saidRight = Reply.of(upd -> silent.send("Sir, I have gone right.", getChatId(upd)),
hasMessageWith("right"));
return ReplyFlow.builder(db)
.action(upd -> silent.send("Command me to go left or right!", getChatId(upd)))
.onlyIf(hasMessageWith("wake up"))
.next(leftflow)
.next(saidRight)
.build();
}
@NotNull
private Predicate<Update> hasMessageWith(String msg) {
return upd -> upd.getMessage().getText().equalsIgnoreCase(msg);
}
}
```
## Inline Declaration
As you can see in the above example, we used a bottom-up approach. We declared the leaf replies before we got to the root reply flow.
If you'd rather have a top-down approach, then you may declare your replies inline to achieve that.
```java
ReplyFlow.builder(db)
.action(upd -> silent.send("Command me to go left or right!", getChatId(upd)))
.onlyIf(hasMessageWith("wake up"))
.next(Reply.of(upd ->
silent.send("Sir, I have gone left.", getChatId(upd)),
hasMessageWith("left")))
.next(Reply.of(upd ->
silent.send("Sir, I have gone right.", getChatId(upd)),
hasMessageWith("right")))
.build();
```
## State Consistency
Under the hood, AbilityBot will generate integers that represent the state of the instigating user. However,
if you add more replies and reply flows, these integers may no longer be consistent. If you'd like to always have consistent state IDs, you
should always pass a unique ID to the ReplyFlow builder like so:
```java
ReplyFlow.builder(db, <ID HERE>)
```

View File

@ -32,7 +32,7 @@ public Ability playWithMe() {
.privacy(PUBLIC)
.locality(ALL)
.input(0)
.action(ctx -> sender.forceReply(playMessage, ctx.chatId()))
.action(ctx -> silent.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
@ -40,7 +40,7 @@ public Ability playWithMe() {
// 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());
silent.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!

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -1,6 +1,8 @@
package org.telegram.abilitybots.api.bot;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.toggle.AbilityToggle;
import org.telegram.abilitybots.api.toggle.DefaultToggle;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
@ -16,18 +18,34 @@ import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance;
* @author Abbas Abou Daya
*/
public abstract class AbilityBot extends BaseAbilityBot implements LongPollingBot {
protected AbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions botOptions) {
super(botToken, botUsername, db, botOptions);
protected AbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) {
super(botToken, botUsername, db, toggle, botOptions);
}
protected AbilityBot(String botToken, String botUsername, DBContext db) {
this(botToken, botUsername, db, new DefaultBotOptions());
protected AbilityBot(String botToken, String botUsername, AbilityToggle toggle, DefaultBotOptions options) {
this(botToken, botUsername, onlineInstance(botUsername), toggle, options);
}
protected AbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle) {
this(botToken, botUsername, db, toggle, new DefaultBotOptions());
}
protected AbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions options) {
this(botToken, botUsername, db, new DefaultToggle(), options);
}
protected AbilityBot(String botToken, String botUsername, DefaultBotOptions botOptions) {
this(botToken, botUsername, onlineInstance(botUsername), botOptions);
}
protected AbilityBot(String botToken, String botUsername, AbilityToggle toggle) {
this(botToken, botUsername, onlineInstance(botUsername), toggle);
}
protected AbilityBot(String botToken, String botUsername, DBContext db) {
this(botToken, botUsername, db, new DefaultToggle());
}
protected AbilityBot(String botToken, String botUsername) {
this(botToken, botUsername, onlineInstance(botUsername));
}

View File

@ -1,6 +1,8 @@
package org.telegram.abilitybots.api.bot;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.toggle.AbilityToggle;
import org.telegram.abilitybots.api.toggle.DefaultToggle;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.bots.DefaultBotOptions;
@ -21,19 +23,35 @@ public abstract class AbilityWebhookBot extends BaseAbilityBot implements Webhoo
private final String botPath;
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, DefaultBotOptions botOptions) {
super(botToken, botUsername, db, botOptions);
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) {
super(botToken, botUsername, db, toggle, botOptions);
this.botPath = botPath;
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db) {
this(botToken, botUsername, botPath, db, new DefaultBotOptions());
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, AbilityToggle toggle, DefaultBotOptions options) {
this(botToken, botUsername, botPath, onlineInstance(botUsername), toggle, options);
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, AbilityToggle toggle) {
this(botToken, botUsername, botPath, db, toggle, new DefaultBotOptions());
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, DefaultBotOptions options) {
this(botToken, botUsername, botPath, db, new DefaultToggle(), options);
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DefaultBotOptions botOptions) {
this(botToken, botUsername, botPath, onlineInstance(botUsername), botOptions);
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, AbilityToggle toggle) {
this(botToken, botUsername, botPath, onlineInstance(botUsername), toggle);
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db) {
this(botToken, botUsername, botPath, db, new DefaultToggle());
}
protected AbilityWebhookBot(String botToken, String botUsername, String botPath) {
this(botToken, botUsername, botPath, onlineInstance(botUsername));
}

View File

@ -6,18 +6,17 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
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.*;
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.toggle.AbilityToggle;
import org.telegram.abilitybots.api.util.AbilityExtension;
import org.telegram.abilitybots.api.util.AbilityUtils;
import org.telegram.abilitybots.api.util.Pair;
@ -25,85 +24,31 @@ import org.telegram.abilitybots.api.util.Trio;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.GetFile;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
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.exceptions.TelegramApiException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.MultimapBuilder.hashKeys;
import static java.lang.String.format;
import static java.time.ZonedDateTime.now;
import static java.util.Arrays.stream;
import static java.util.Comparator.comparing;
import static java.util.Objects.nonNull;
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.joining;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.telegram.abilitybots.api.objects.Ability.builder;
import static org.telegram.abilitybots.api.objects.Flag.DOCUMENT;
import static org.telegram.abilitybots.api.objects.Flag.MESSAGE;
import static org.telegram.abilitybots.api.objects.Flag.REPLY;
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.util.AbilityMessageCodes.ABILITY_BAN_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_BAN_SUCCESS;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_CLAIM_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_CLAIM_SUCCESS;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_COMMANDS_NOT_FOUND;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_DEMOTE_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_DEMOTE_SUCCESS;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_PROMOTE_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_PROMOTE_SUCCESS;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_RECOVER_ERROR;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_RECOVER_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_RECOVER_MESSAGE;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_RECOVER_SUCCESS;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_UNBAN_FAIL;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.ABILITY_UNBAN_SUCCESS;
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.AbilityMessageCodes.USER_NOT_FOUND;
import static org.telegram.abilitybots.api.util.AbilityUtils.addTag;
import static org.telegram.abilitybots.api.util.AbilityUtils.commitTo;
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.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.AbilityUtils.shortName;
import static org.telegram.abilitybots.api.util.AbilityUtils.stripTag;
import static org.telegram.abilitybots.api.objects.Privacy.*;
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.
@ -141,29 +86,21 @@ import static org.telegram.abilitybots.api.util.AbilityUtils.stripTag;
public abstract class BaseAbilityBot extends DefaultAbsSender implements AbilityExtension {
private static final Logger log = LoggerFactory.getLogger(BaseAbilityBot.class);
protected static final String DEFAULT = "default";
// DB objects
public static final String ADMINS = "ADMINS";
public static final String USERS = "USERS";
public static final String USER_ID = "USER_ID";
public static final String BLACKLIST = "BLACKLIST";
// Factory commands
protected static final String DEFAULT = "default";
protected static final String CLAIM = "claim";
protected static final String BAN = "ban";
protected static final String PROMOTE = "promote";
protected static final String DEMOTE = "demote";
protected static final String UNBAN = "unban";
protected static final String BACKUP = "backup";
protected static final String RECOVER = "recover";
protected static final String COMMANDS = "commands";
protected static final String REPORT = "report";
// DB and sender
protected final DBContext db;
protected MessageSender sender;
protected SilentSender silent;
// Ability toggle
private final AbilityToggle toggle;
// Bot token and username
private final String botToken;
private final String botUsername;
@ -176,12 +113,13 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
public abstract int creatorId();
protected BaseAbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions botOptions) {
protected BaseAbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) {
super(botOptions);
this.botToken = botToken;
this.botUsername = botUsername;
this.db = db;
this.toggle = toggle;
this.sender = new DefaultSender(this);
silent = new SilentSender(sender);
@ -281,374 +219,6 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
return true;
}
/**
* Gets the user with the specified username.
*
* @param username the username of the required user
* @return the user
*/
protected User getUser(String username) {
Integer id = userIds().get(username.toLowerCase());
if (id == null) {
throw new IllegalStateException(format("Could not find ID corresponding to username [%s]", username));
}
return getUser(id);
}
/**
* Gets the user with the specified ID.
*
* @param id the id of the required user
* @return the user
*/
protected User getUser(int id) {
User user = users().get(id);
if (user == null) {
throw new IllegalStateException(format("Could not find user corresponding to id [%d]", id));
}
return user;
}
/**
* Gets the user with the specified username. If user was not found, the bot will send a message on Telegram.
*
* @param username the username of the required user
* @param ctx the message context with the originating user
* @return the id of the user
*/
protected int getUserIdSendError(String username, MessageContext ctx) {
try {
return getUser(username).getId();
} catch (IllegalStateException ex) {
silent.send(getLocalizedMessage(USER_NOT_FOUND, ctx.user().getLanguageCode(), username), ctx.chatId());
throw ex;
}
}
/**
* <p>
* Format of the report:
* <p>
* [command1] - [description1]
* <p>
* [command2] - [description2]
* <p>
* ...
* <p>
* Once you invoke it, the bot will send the available commands to the chat. This is a public ability so anyone can invoke it.
* <p>
* Usage: <code>/commands</code>
*
* @return the ability to report commands defined by the child bot.
*/
public Ability reportCommands() {
return builder()
.name(REPORT)
.locality(ALL)
.privacy(CREATOR)
.input(0)
.action(ctx -> {
String commands = abilities.values().stream()
.filter(ability -> nonNull(ability.info()))
.map(ability -> {
String name = ability.name();
String info = ability.info();
return format("%s - %s", name, info);
})
.sorted()
.reduce((a, b) -> format("%s%n%s", a, b))
.orElse(getLocalizedMessage(ABILITY_COMMANDS_NOT_FOUND, ctx.user().getLanguageCode()));
silent.send(commands, ctx.chatId());
})
.build();
}
/**
* Default format:
* <p>
* PUBLIC
* <p>
* [command1] - [description1]
* <p>
* [command2] - [description2]
* <p>
* GROUP_ADMIN
* <p>
* [command1] - [description1]
* <p>
* ...
*
* @return the ability to print commands based on the privacy of the requesting user
*/
public Ability commands() {
return builder()
.name(COMMANDS)
.locality(USER)
.privacy(PUBLIC)
.input(0)
.action(ctx -> {
Privacy privacy = getPrivacy(ctx.update(), ctx.user().getId());
ListMultimap<Privacy, String> abilitiesPerPrivacy = abilities.values().stream()
.map(ability -> {
String name = ability.name();
String info = ability.info();
if (!isEmpty(info))
return Pair.of(ability.privacy(), format("/%s - %s", name, info));
return Pair.of(ability.privacy(), format("/%s", name));
})
.sorted(comparing(Pair::b))
.collect(() -> hashKeys().arrayListValues().build(),
(map, pair) -> map.put(pair.a(), pair.b()),
Multimap::putAll);
String commands = abilitiesPerPrivacy.asMap().entrySet().stream()
.filter(entry -> privacy.compareTo(entry.getKey()) >= 0)
.sorted(comparing(Entry::getKey))
.map(entry ->
entry.getValue().stream()
.reduce(entry.getKey().toString(), (a, b) -> format("%s\n%s", a, b))
)
.collect(joining("\n"));
if (commands.isEmpty())
commands = getLocalizedMessage(ABILITY_COMMANDS_NOT_FOUND, ctx.user().getLanguageCode());
silent.send(commands, ctx.chatId());
})
.build();
}
/**
* This backup ability returns the object defined by {@link DBContext#backup()} as a message document.
* <p>
* This is a high-profile ability and is restricted to the CREATOR only.
* <p>
* Usage: <code>/backup</code>
*
* @return the ability to back-up the database of the bot
*/
public Ability backupDB() {
return builder()
.name(BACKUP)
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> {
File backup = new File("backup.json");
try (PrintStream printStream = new PrintStream(backup)) {
printStream.print(db.backup());
sender.sendDocument(new SendDocument()
.setDocument(backup)
.setChatId(ctx.chatId())
);
} catch (FileNotFoundException e) {
log.error("Error while fetching backup", e);
} catch (TelegramApiException e) {
log.error("Error while sending document/backup file", e);
}
})
.build();
}
/**
* Recovers the bot database using {@link DBContext#recover(Object)}.
* <p>
* The bot recovery process hugely depends on the implementation of the recovery method of {@link DBContext}.
* <p>
* Usage: <code>/recover</code>
*
* @return the ability to recover the database of the bot
*/
public Ability recoverDB() {
return builder()
.name(RECOVER)
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> silent.forceReply(
getLocalizedMessage(ABILITY_RECOVER_MESSAGE, ctx.user().getLanguageCode()), ctx.chatId()))
.reply(update -> {
String replyToMsg = update.getMessage().getReplyToMessage().getText();
String recoverMessage = getLocalizedMessage(ABILITY_RECOVER_MESSAGE, AbilityUtils.getUser(update).getLanguageCode());
if (!replyToMsg.equals(recoverMessage))
return;
String fileId = update.getMessage().getDocument().getFileId();
try (FileReader reader = new FileReader(downloadFileWithId(fileId))) {
String backupData = IOUtils.toString(reader);
if (db.recover(backupData)) {
send(ABILITY_RECOVER_SUCCESS, update);
} else {
send(ABILITY_RECOVER_FAIL, update);
}
} catch (Exception e) {
log.error("Could not recover DB from backup", e);
send(ABILITY_RECOVER_ERROR, update);
}
}, MESSAGE, DOCUMENT, REPLY)
.build();
}
/**
* Banned users are accumulated in the blacklist. Use {@link DBContext#getSet(String)} with name specified by {@link BaseAbilityBot#BLACKLIST}.
* <p>
* Usage: <code>/ban @username</code>
* <p>
* <u>Note that admins who try to ban the creator, get banned.</u>
*
* @return the ability to ban the user from any kind of <b>bot interaction</b>
*/
public Ability banUser() {
return builder()
.name(BAN)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
int userId = getUserIdSendError(username, ctx);
String bannedUser;
// Protection from abuse
if (userId == creatorId()) {
userId = ctx.user().getId();
bannedUser = isNullOrEmpty(ctx.user().getUserName()) ? addTag(ctx.user().getUserName()) : shortName(ctx.user());
} else {
bannedUser = addTag(username);
}
Set<Integer> blacklist = blacklist();
if (blacklist.contains(userId))
sendMd(ABILITY_BAN_FAIL, ctx, escape(bannedUser));
else {
blacklist.add(userId);
sendMd(ABILITY_BAN_SUCCESS, ctx, escape(bannedUser));
}
})
.post(commitTo(db))
.build();
}
/**
* Usage: <code>/unban @username</code>
*
* @return the ability to unban a user
*/
public Ability unbanUser() {
return builder()
.name(UNBAN)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
Integer userId = getUserIdSendError(username, ctx);
Set<Integer> blacklist = blacklist();
if (!blacklist.remove(userId))
silent.sendMd(getLocalizedMessage(ABILITY_UNBAN_FAIL, ctx.user().getLanguageCode(), escape(username)), ctx.chatId());
else {
silent.sendMd(getLocalizedMessage(ABILITY_UNBAN_SUCCESS, ctx.user().getLanguageCode(), escape(username)), ctx.chatId());
}
})
.post(commitTo(db))
.build();
}
/**
* @return the ability to promote a user to a bot admin
*/
public Ability promoteAdmin() {
return builder()
.name(PROMOTE)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
Integer userId = getUserIdSendError(username, ctx);
Set<Integer> admins = admins();
if (admins.contains(userId))
sendMd(ABILITY_PROMOTE_FAIL, ctx, escape(username));
else {
admins.add(userId);
sendMd(ABILITY_PROMOTE_SUCCESS, ctx, escape(username));
}
}).post(commitTo(db))
.build();
}
/**
* @return the ability to demote an admin to a user
*/
public Ability demoteAdmin() {
return builder()
.name(DEMOTE)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
Integer userId = getUserIdSendError(username, ctx);
Set<Integer> admins = admins();
if (admins.remove(userId)) {
sendMd(ABILITY_DEMOTE_SUCCESS, ctx, escape(username));
} else {
sendMd(ABILITY_DEMOTE_FAIL, ctx, escape(username));
}
})
.post(commitTo(db))
.build();
}
/**
* Regular users and admins who try to claim the bot will get <b>banned</b>.
*
* @return the ability to claim yourself as the master and creator of the bot
*/
public Ability claimCreator() {
return builder()
.name(CLAIM)
.locality(ALL)
.privacy(CREATOR)
.input(0)
.action(ctx -> {
Set<Integer> admins = admins();
int id = creatorId();
if (admins.contains(id))
send(ABILITY_CLAIM_FAIL, ctx);
else {
admins.add(id);
send(ABILITY_CLAIM_SUCCESS, ctx);
}
})
.post(commitTo(db))
.build();
}
private Optional<Message> send(String message, MessageContext ctx, String... args) {
return silent.send(getLocalizedMessage(message, ctx.user().getLanguageCode(), args), ctx.chatId());
}
private Optional<Message> sendMd(String message, MessageContext ctx, String... args) {
return silent.sendMd(getLocalizedMessage(message, ctx.user().getLanguageCode(), args), ctx.chatId());
}
private Optional<Message> send(String message, Update upd) {
Long chatId = upd.getMessage().getChatId();
return silent.send(getLocalizedMessage(message, AbilityUtils.getUser(upd).getLanguageCode()), chatId);
}
/**
* Registers the declared abilities using method reflection. Also, replies are accumulated using the built abilities and standalone methods that return a Reply.
* <p>
@ -665,11 +235,19 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
// Add the bot itself as it is an AbilityExtension
extensions.add(this);
DefaultAbilities defaultAbs = new DefaultAbilities(this);
Stream<Ability> defaultAbsStream = stream(DefaultAbilities.class.getMethods())
.filter(checkReturnType(Ability.class))
.map(returnAbility(defaultAbs))
.filter(ab -> !toggle.isOff(ab))
.map(toggle::processAbility);
// Extract all abilities from every single extension instance
abilities = extensions.stream()
abilities = Stream.concat(defaultAbsStream,
extensions.stream()
.flatMap(ext -> stream(ext.getClass().getMethods())
.filter(checkReturnType(Ability.class))
.map(returnAbility(ext)))
.map(returnAbility(ext))))
// Abilities are immutable, build it respectively
.collect(ImmutableMap::<String, Ability>builder,
(b, a) -> b.put(a.name(), a),
@ -680,7 +258,8 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
Stream<Reply> extensionReplies = extensions.stream()
.flatMap(ext -> stream(ext.getClass().getMethods())
.filter(checkReturnType(Reply.class))
.map(returnReply(ext)));
.map(returnReply(ext)))
.flatMap(Reply::stream);
// Replies can be standalone or attached to abilities, fetch those too
Stream<Reply> abilityReplies = abilities.values().stream()
@ -702,14 +281,14 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
* @param clazz the type to be tested
* @return a predicate testing the return type of the method corresponding to the class parameter
*/
private Predicate<Method> checkReturnType(Class<?> clazz) {
private static Predicate<Method> checkReturnType(Class<?> clazz) {
return method -> clazz.isAssignableFrom(method.getReturnType());
}
/**
* Invokes the method and retrieves its return {@link Reply}.
*
* @param obj an bot or extension that this method is invoked with
* @param obj a bot or extension that this method is invoked with
* @return a {@link Function} which returns the {@link Reply} returned by the given method
*/
private Function<? super Method, AbilityExtension> returnExtension(Object obj) {
@ -726,10 +305,10 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
/**
* Invokes the method and retrieves its return {@link Ability}.
*
* @param obj an bot or extension that this method is invoked with
* @param obj a bot or extension that this method is invoked with
* @return a {@link Function} which returns the {@link Ability} returned by the given method
*/
private Function<? super Method, Ability> returnAbility(Object obj) {
private static Function<? super Method, Ability> returnAbility(Object obj) {
return method -> {
try {
return (Ability) method.invoke(obj);
@ -743,10 +322,10 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
/**
* Invokes the method and retrieves its return {@link Reply}.
*
* @param obj an bot or extension that this method is invoked with
* @param obj a bot or extension that this method is invoked with
* @return a {@link Function} which returns the {@link Reply} returned by the given method
*/
private Function<? super Method, Reply> returnReply(Object obj) {
private static Function<? super Method, Reply> returnReply(Object obj) {
return method -> {
try {
return (Reply) method.invoke(obj);
@ -833,7 +412,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
}
@NotNull
private Privacy getPrivacy(Update update, int id) {
Privacy getPrivacy(Update update, int id) {
return isCreator(id) ?
CREATOR : isAdmin(id) ?
ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ?
@ -938,13 +517,4 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
return ability.flags().stream()
.reduce(true, flagAnd, Boolean::logicalAnd);
}
private File downloadFileWithId(String fileId) throws TelegramApiException {
return sender.downloadFile(sender.execute(new GetFile().setFileId(fileId)));
}
private String escape(String username) {
return username.replace("_", "\\_");
}
}

View File

@ -0,0 +1,435 @@
package org.telegram.abilitybots.api.bot;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Ability;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.abilitybots.api.objects.Privacy;
import org.telegram.abilitybots.api.util.AbilityExtension;
import org.telegram.abilitybots.api.util.AbilityUtils;
import org.telegram.abilitybots.api.util.Pair;
import org.telegram.telegrambots.meta.api.methods.GetFile;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
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.exceptions.TelegramApiException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintStream;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.MultimapBuilder.hashKeys;
import static java.lang.String.format;
import static java.util.Comparator.comparing;
import static java.util.Objects.nonNull;
import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.telegram.abilitybots.api.objects.Ability.builder;
import static org.telegram.abilitybots.api.objects.Flag.*;
import static org.telegram.abilitybots.api.objects.Locality.ALL;
import static org.telegram.abilitybots.api.objects.Locality.USER;
import static org.telegram.abilitybots.api.objects.Privacy.*;
import static org.telegram.abilitybots.api.util.AbilityMessageCodes.*;
import static org.telegram.abilitybots.api.util.AbilityUtils.*;
public final class DefaultAbilities implements AbilityExtension {
// Default commands
public static final String CLAIM = "claim";
public static final String BAN = "ban";
public static final String PROMOTE = "promote";
public static final String DEMOTE = "demote";
public static final String UNBAN = "unban";
public static final String BACKUP = "backup";
public static final String RECOVER = "recover";
public static final String COMMANDS = "commands";
public static final String REPORT = "report";
private static final Logger log = LogManager.getLogger(DefaultAbilities.class);
private final BaseAbilityBot bot;
public DefaultAbilities(BaseAbilityBot bot) {
this.bot = bot;
}
/**
* <p>
* Format of the report:
* <p>
* [command1] - [description1]
* <p>
* [command2] - [description2]
* <p>
* ...
* <p>
* Once you invoke it, the bot will send the available commands to the chat. This is a public ability so anyone can invoke it.
* <p>
* Usage: <code>/commands</code>
*
* @return the ability to report commands defined by the child bot.
*/
public Ability reportCommands() {
return builder()
.name(REPORT)
.locality(ALL)
.privacy(CREATOR)
.input(0)
.action(ctx -> {
String commands = bot.abilities().values().stream()
.filter(ability -> nonNull(ability.info()))
.map(ability -> {
String name = ability.name();
String info = ability.info();
return format("%s - %s", name, info);
})
.sorted()
.reduce((a, b) -> format("%s%n%s", a, b))
.orElse(getLocalizedMessage(ABILITY_COMMANDS_NOT_FOUND, ctx.user().getLanguageCode()));
bot.silent.send(commands, ctx.chatId());
})
.build();
}
/**
* Default format:
* <p>
* PUBLIC
* <p>
* [command1] - [description1]
* <p>
* [command2] - [description2]
* <p>
* GROUP_ADMIN
* <p>
* [command1] - [description1]
* <p>
* ...
*
* @return the ability to print commands based on the privacy of the requesting user
*/
public Ability commands() {
return builder()
.name(COMMANDS)
.locality(USER)
.privacy(PUBLIC)
.input(0)
.action(ctx -> {
Privacy privacy = bot.getPrivacy(ctx.update(), ctx.user().getId());
ListMultimap<Privacy, String> abilitiesPerPrivacy = bot.abilities().values().stream()
.map(ability -> {
String name = ability.name();
String info = ability.info();
if (!isEmpty(info))
return Pair.of(ability.privacy(), format("/%s - %s", name, info));
return Pair.of(ability.privacy(), format("/%s", name));
})
.sorted(comparing(Pair::b))
.collect(() -> hashKeys().arrayListValues().build(),
(map, pair) -> map.put(pair.a(), pair.b()),
Multimap::putAll);
String commands = abilitiesPerPrivacy.asMap().entrySet().stream()
.filter(entry -> privacy.compareTo(entry.getKey()) >= 0)
.sorted(comparing(Map.Entry::getKey))
.map(entry ->
entry.getValue().stream()
.reduce(entry.getKey().toString(), (a, b) -> format("%s\n%s", a, b))
)
.collect(joining("\n"));
if (commands.isEmpty())
commands = getLocalizedMessage(ABILITY_COMMANDS_NOT_FOUND, ctx.user().getLanguageCode());
bot.silent.send(commands, ctx.chatId());
})
.build();
}
/**
* This backup ability returns the object defined by {@link DBContext#backup()} as a message document.
* <p>
* This is a high-profile ability and is restricted to the CREATOR only.
* <p>
* Usage: <code>/backup</code>
*
* @return the ability to back-up the database of the bot
*/
public Ability backupDB() {
return builder()
.name(BACKUP)
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> {
File backup = new File("backup.json");
try (PrintStream printStream = new PrintStream(backup)) {
printStream.print(bot.db.backup());
bot.sender.sendDocument(new SendDocument()
.setDocument(backup)
.setChatId(ctx.chatId())
);
} catch (FileNotFoundException e) {
log.error("Error while fetching backup", e);
} catch (TelegramApiException e) {
log.error("Error while sending document/backup file", e);
}
})
.build();
}
/**
* Recovers the bot database using {@link DBContext#recover(Object)}.
* <p>
* The bot recovery process hugely depends on the implementation of the recovery method of {@link DBContext}.
* <p>
* Usage: <code>/recover</code>
*
* @return the ability to recover the database of the bot
*/
public Ability recoverDB() {
return builder()
.name(RECOVER)
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> bot.silent.forceReply(
getLocalizedMessage(ABILITY_RECOVER_MESSAGE, ctx.user().getLanguageCode()), ctx.chatId()))
.reply(update -> {
String replyToMsg = update.getMessage().getReplyToMessage().getText();
String recoverMessage = getLocalizedMessage(ABILITY_RECOVER_MESSAGE, AbilityUtils.getUser(update).getLanguageCode());
if (!replyToMsg.equals(recoverMessage))
return;
String fileId = update.getMessage().getDocument().getFileId();
try (FileReader reader = new FileReader(downloadFileWithId(fileId))) {
String backupData = IOUtils.toString(reader);
if (bot.db.recover(backupData)) {
send(ABILITY_RECOVER_SUCCESS, update);
} else {
send(ABILITY_RECOVER_FAIL, update);
}
} catch (Exception e) {
log.error("Could not recover DB from backup", e);
send(ABILITY_RECOVER_ERROR, update);
}
}, MESSAGE, DOCUMENT, REPLY)
.build();
}
/**
* Banned users are accumulated in the blacklist. Use {@link DBContext#getSet(String)} with name specified by {@link BaseAbilityBot#BLACKLIST}.
* <p>
* Usage: <code>/ban @username</code>
* <p>
* <u>Note that admins who try to ban the creator, get banned.</u>
*
* @return the ability to ban the user from any kind of <b>bot interaction</b>
*/
public Ability banUser() {
return builder()
.name(BAN)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
int userId = getUserIdSendError(username, ctx);
String bannedUser;
// Protection from abuse
if (userId == bot.creatorId()) {
userId = ctx.user().getId();
bannedUser = isNullOrEmpty(ctx.user().getUserName()) ? addTag(ctx.user().getUserName()) : shortName(ctx.user());
} else {
bannedUser = addTag(username);
}
Set<Integer> blacklist = bot.blacklist();
if (blacklist.contains(userId))
sendMd(ABILITY_BAN_FAIL, ctx, escape(bannedUser));
else {
blacklist.add(userId);
sendMd(ABILITY_BAN_SUCCESS, ctx, escape(bannedUser));
}
})
.post(commitTo(bot.db))
.build();
}
/**
* Usage: <code>/unban @username</code>
*
* @return the ability to unban a user
*/
public Ability unbanUser() {
return builder()
.name(UNBAN)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
Integer userId = getUserIdSendError(username, ctx);
Set<Integer> blacklist = bot.blacklist();
if (!blacklist.remove(userId))
bot.silent.sendMd(getLocalizedMessage(ABILITY_UNBAN_FAIL, ctx.user().getLanguageCode(), escape(username)), ctx.chatId());
else {
bot.silent.sendMd(getLocalizedMessage(ABILITY_UNBAN_SUCCESS, ctx.user().getLanguageCode(), escape(username)), ctx.chatId());
}
})
.post(commitTo(bot.db))
.build();
}
/**
* @return the ability to promote a user to a bot admin
*/
public Ability promoteAdmin() {
return builder()
.name(PROMOTE)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
Integer userId = getUserIdSendError(username, ctx);
Set<Integer> admins = bot.admins();
if (admins.contains(userId))
sendMd(ABILITY_PROMOTE_FAIL, ctx, escape(username));
else {
admins.add(userId);
sendMd(ABILITY_PROMOTE_SUCCESS, ctx, escape(username));
}
}).post(commitTo(bot.db))
.build();
}
/**
* @return the ability to demote an admin to a user
*/
public Ability demoteAdmin() {
return builder()
.name(DEMOTE)
.locality(ALL)
.privacy(ADMIN)
.input(1)
.action(ctx -> {
String username = stripTag(ctx.firstArg());
Integer userId = getUserIdSendError(username, ctx);
Set<Integer> admins = bot.admins();
if (admins.remove(userId)) {
sendMd(ABILITY_DEMOTE_SUCCESS, ctx, escape(username));
} else {
sendMd(ABILITY_DEMOTE_FAIL, ctx, escape(username));
}
})
.post(commitTo(bot.db))
.build();
}
/**
* Regular users and admins who try to claim the bot will get <b>banned</b>.
*
* @return the ability to claim yourself as the master and creator of the bot
*/
public Ability claimCreator() {
return builder()
.name(CLAIM)
.locality(ALL)
.privacy(CREATOR)
.input(0)
.action(ctx -> {
Set<Integer> admins = bot.admins();
int id = bot.creatorId();
if (admins.contains(id))
send(ABILITY_CLAIM_FAIL, ctx);
else {
admins.add(id);
send(ABILITY_CLAIM_SUCCESS, ctx);
}
})
.post(commitTo(bot.db))
.build();
}
/**
* Gets the user with the specified username.
*
* @param username the username of the required user
* @return the user
*/
private User getUser(String username) {
Integer id = bot.userIds().get(username.toLowerCase());
if (id == null) {
throw new IllegalStateException(format("Could not find ID corresponding to username [%s]", username));
}
return getUser(id);
}
/**
* Gets the user with the specified ID.
*
* @param id the id of the required user
* @return the user
*/
private User getUser(int id) {
User user = bot.users().get(id);
if (user == null) {
throw new IllegalStateException(format("Could not find user corresponding to id [%d]", id));
}
return user;
}
/**
* Gets the user with the specified username. If user was not found, the bot will send a message on Telegram.
*
* @param username the username of the required user
* @param ctx the message context with the originating user
* @return the id of the user
*/
private int getUserIdSendError(String username, MessageContext ctx) {
try {
return getUser(username).getId();
} catch (IllegalStateException ex) {
bot.silent.send(getLocalizedMessage(USER_NOT_FOUND, ctx.user().getLanguageCode(), username), ctx.chatId());
throw ex;
}
}
private Optional<Message> send(String message, MessageContext ctx, String... args) {
return bot.silent.send(getLocalizedMessage(message, ctx.user().getLanguageCode(), args), ctx.chatId());
}
private Optional<Message> sendMd(String message, MessageContext ctx, String... args) {
return bot.silent.sendMd(getLocalizedMessage(message, ctx.user().getLanguageCode(), args), ctx.chatId());
}
private Optional<Message> send(String message, Update upd) {
Long chatId = upd.getMessage().getChatId();
return bot.silent.send(getLocalizedMessage(message, AbilityUtils.getUser(upd).getLanguageCode()), chatId);
}
protected File downloadFileWithId(String fileId) throws TelegramApiException {
return bot.sender.downloadFile(bot.sender.execute(new GetFile().setFileId(fileId)));
}
}

View File

@ -0,0 +1,45 @@
package org.telegram.abilitybots.api.db;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import java.util.Objects;
public class BackupVar<T> {
@JsonProperty("var")
private final T var;
private BackupVar(T var) {
this.var = var;
}
@JsonCreator
public static <R> BackupVar<R> createVar(@JsonProperty("var") R var) {
return new BackupVar<>(var);
}
public T var() {
return var;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BackupVar<?> backupVar = (BackupVar<?>) o;
return Objects.equals(var, backupVar.var);
}
@Override
public int hashCode() {
return Objects.hash(var);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("var", var)
.toString();
}
}

View File

@ -12,12 +12,7 @@ import org.slf4j.LoggerFactory;
import org.telegram.abilitybots.api.util.Pair;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.*;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
@ -188,15 +183,15 @@ public class MapDBContext implements DBContext {
return Pair.of(entry.getKey(), newArrayList((List) struct));
else if (struct instanceof Map)
return Pair.of(entry.getKey(), new BackupMap((Map) struct));
else
return Pair.of(entry.getKey(), struct);
else if (struct instanceof Atomic.Var)
return Pair.of(entry.getKey(), BackupVar.createVar(((Atomic.Var) struct).get()));
return Pair.of(entry.getKey(), struct);
}).collect(toMap(pair -> (String) pair.a(), Pair::b));
}
private void doRecover(Map<String, Object> backupData) {
clear();
backupData.forEach((name, value) -> {
if (value instanceof Set) {
Set entrySet = (Set) value;
getSet(name).addAll(entrySet);
@ -206,6 +201,8 @@ public class MapDBContext implements DBContext {
} else if (value instanceof List) {
List entryList = (List) value;
getList(name).addAll(entryList);
} else if (value instanceof BackupVar) {
getVar(name).set(((BackupVar) value).var());
} else {
log.error(format("Unable to identify object type during DB recovery, entry name: %s", name));
}

View File

@ -147,8 +147,8 @@ public final class Ability {
private Privacy privacy;
private Locality locality;
private int argNum;
private Consumer<MessageContext> consumer;
private Consumer<MessageContext> postConsumer;
private Consumer<MessageContext> action;
private Consumer<MessageContext> postAction;
private List<Reply> replies;
private Predicate<Update>[] flags;
@ -157,7 +157,7 @@ public final class Ability {
}
public AbilityBuilder action(Consumer<MessageContext> consumer) {
this.consumer = consumer;
this.action = consumer;
return this;
}
@ -191,8 +191,8 @@ public final class Ability {
return this;
}
public AbilityBuilder post(Consumer<MessageContext> postConsumer) {
this.postConsumer = postConsumer;
public AbilityBuilder post(Consumer<MessageContext> postAction) {
this.postAction = postAction;
return this;
}
@ -202,8 +202,21 @@ public final class Ability {
return this;
}
public AbilityBuilder basedOn(Ability ability) {
replies.clear();
replies.addAll(ability.replies());
return name(ability.name())
.info(ability.info())
.input(ability.tokens())
.locality(ability.locality())
.privacy(ability.privacy())
.action(ability.action())
.post(ability.postAction());
}
public Ability build() {
return new Ability(name, info, locality, privacy, argNum, consumer, postConsumer, replies, flags);
return new Ability(name, info, locality, privacy, argNum, action, postAction, replies, flags);
}
}
}

View File

@ -27,12 +27,12 @@ public enum Flag implements Predicate<Update> {
CHOSEN_INLINE_QUERY(Update::hasChosenInlineQuery),
// Message Flags
REPLY(update -> update.getMessage().isReply()),
DOCUMENT(upd -> upd.getMessage().hasDocument()),
TEXT(upd -> upd.getMessage().hasText()),
PHOTO(upd -> upd.getMessage().hasPhoto()),
LOCATION(upd -> upd.getMessage().hasLocation()),
CAPTION(upd -> nonNull(upd.getMessage().getCaption()));
REPLY(upd -> MESSAGE.test(upd) && upd.getMessage().isReply()),
DOCUMENT(upd -> MESSAGE.test(upd) && upd.getMessage().hasDocument()),
TEXT(upd -> MESSAGE.test(upd) && upd.getMessage().hasText()),
PHOTO(upd -> MESSAGE.test(upd) && upd.getMessage().hasPhoto()),
LOCATION(upd -> MESSAGE.test(upd) && upd.getMessage().hasLocation()),
CAPTION(upd -> MESSAGE.test(upd) && nonNull(upd.getMessage().getCaption()));
private final Predicate<Update> predicate;

View File

@ -1,14 +1,19 @@
package org.telegram.abilitybots.api.objects;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Arrays.asList;
/**
@ -18,18 +23,24 @@ import static java.util.Arrays.asList;
*
* @author Abbas Abou Daya
*/
public final class Reply {
public class Reply {
public final List<Predicate<Update>> conditions;
public final Consumer<Update> action;
private Reply(List<Predicate<Update>> conditions, Consumer<Update> action) {
this.conditions = conditions;
Reply(List<Predicate<Update>> conditions, Consumer<Update> action) {
this.conditions = ImmutableList.<Predicate<Update>>builder()
.addAll(conditions)
.build();
this.action = action;
}
public static Reply of(Consumer<Update> action, List<Predicate<Update>> conditions) {
return new Reply(conditions, action);
}
@SafeVarargs
public static Reply of(Consumer<Update> action, Predicate<Update>... conditions) {
return new Reply(asList(conditions), action);
return Reply.of(action, newArrayList(conditions));
}
public boolean isOkFor(Update update) {
@ -42,6 +53,18 @@ public final class Reply {
action.accept(update);
}
public List<Predicate<Update>> conditions() {
return conditions;
}
public Consumer<Update> action() {
return action;
}
public Stream<Reply> stream(){
return Stream.of(this);
}
@Override
public boolean equals(Object o) {
if (this == o)

View File

@ -0,0 +1,117 @@
package org.telegram.abilitybots.api.objects;
import org.jetbrains.annotations.NotNull;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.util.AbilityUtils;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static com.google.common.collect.Lists.newArrayList;
public class ReplyFlow extends Reply {
private final Set<Reply> nextReplies;
private ReplyFlow(List<Predicate<Update>> conditions, Consumer<Update> action, Set<Reply> nextReplies) {
super(conditions, action);
this.nextReplies = nextReplies;
}
public static ReplyFlowBuilder builder(DBContext db) {
return new ReplyFlowBuilder(db);
}
public static ReplyFlowBuilder builder(DBContext db, int id) {
return new ReplyFlowBuilder(db, id);
}
public Set<Reply> nextReplies() {
return nextReplies;
}
@Override
public Stream<Reply> stream() {
return Stream.concat(Stream.of(this), nextReplies.stream().flatMap(Reply::stream));
}
public static class ReplyFlowBuilder {
public static final String STATES = "user_state_replies";
private static AtomicInteger replyCounter = new AtomicInteger();
private final DBContext db;
private final int id;
private List<Predicate<Update>> conds;
private Consumer<Update> action;
private Set<Reply> nextReplies;
private ReplyFlowBuilder(DBContext db, int id) {
conds = new ArrayList<>();
nextReplies = new HashSet<>();
this.db = db;
this.id = id;
}
private ReplyFlowBuilder(DBContext db) {
this(db, replyCounter.getAndIncrement());
}
public ReplyFlowBuilder action(Consumer<Update> action) {
this.action = action;
return this;
}
public ReplyFlowBuilder onlyIf(Predicate<Update> pred) {
conds.add(pred);
return this;
}
public ReplyFlowBuilder next(Reply nextReply) {
List<Predicate<Update>> statefulConditions = toStateful(nextReply.conditions());
Consumer<Update> statefulAction = nextReply.action().andThen(upd -> {
Long chatId = AbilityUtils.getChatId(upd);
db.<Long, Integer>getMap(STATES).remove(chatId);
});
Reply statefulReply = Reply.of(statefulAction, statefulConditions);
nextReplies.add(statefulReply);
return this;
}
public ReplyFlowBuilder next(ReplyFlow nextReplyFlow) {
List<Predicate<Update>> statefulConditions = toStateful(nextReplyFlow.conditions());
ReplyFlow statefulReplyFlow = new ReplyFlow(statefulConditions, nextReplyFlow.action(), nextReplyFlow.nextReplies());
nextReplies.add(statefulReplyFlow);
return this;
}
public ReplyFlow build() {
if (action == null)
action = upd -> {};
Consumer<Update> statefulAction = action.andThen(upd -> {
Long chatId = AbilityUtils.getChatId(upd);
db.<Long, Integer>getMap(STATES).put(chatId, id);
});
return new ReplyFlow(conds, statefulAction, nextReplies);
}
@NotNull
private List<Predicate<Update>> toStateful(List<Predicate<Update>> conditions) {
List<Predicate<Update>> statefulConditions = newArrayList(conditions);
statefulConditions.add(0, upd -> {
Long chatId = AbilityUtils.getChatId(upd);
int stateId = db.<Long, Integer>getMap(STATES).getOrDefault(chatId, -1);
return id == stateId;
});
return statefulConditions;
}
}
}

View File

@ -7,6 +7,7 @@ import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.updateshandlers.SentCallback;
import java.io.Serializable;
import java.util.Optional;
@ -52,12 +53,12 @@ public class SilentSender {
}
}
public <T extends Serializable, Method extends BotApiMethod<T>> Optional<T> executeAsync(Method method) {
public <T extends Serializable, Method extends BotApiMethod<T>, Callback extends SentCallback<T>> void
executeAsync(Method method, Callback callable) {
try {
return Optional.ofNullable(sender.execute(method));
sender.executeAsync(method, callable);
} catch (TelegramApiException e) {
log.error("Could not execute bot API method", e);
return Optional.empty();
}
}

View File

@ -0,0 +1,21 @@
package org.telegram.abilitybots.api.toggle;
import org.telegram.abilitybots.api.objects.Ability;
/**
* This interface can be used to toggle or customize unwanted default abilities by the user.
*/
public interface AbilityToggle {
/**
* @param ab the target ability
* @return true if the ability has been turned off
*/
boolean isOff(Ability ab);
/**
* Abilities that are ON (and have failed the {@link AbilityToggle#isOff} condition) will be processed by this method.
* @param ab the target ability
* @return the processed ability
*/
Ability processAbility(Ability ab);
}

View File

@ -0,0 +1,20 @@
package org.telegram.abilitybots.api.toggle;
import org.telegram.abilitybots.api.objects.Ability;
/**
* This toggle can be used as-is to turn off ALL the default abilities supplied by the library.
* This is for users who are interested in the barebone functionality of AbilityBot.
*/
public class BareboneToggle implements AbilityToggle {
@Override
public boolean isOff(Ability ability) {
return true;
}
@Override
public Ability processAbility(Ability ab) {
// Should never hit this
throw new RuntimeException("Should not process any ability in a vanilla toggle");
}
}

View File

@ -0,0 +1,56 @@
package org.telegram.abilitybots.api.toggle;
import org.telegram.abilitybots.api.objects.Ability;
import java.util.HashMap;
import java.util.Map;
/**
* This custom toggle can be used to customize default abilities supplied by the library. Users can call {@link CustomToggle#toggle} to
* 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";
private final Map<String, String> baseMapping;
public CustomToggle() {
baseMapping = new HashMap<>();
}
@Override
public boolean isOff(Ability ability) {
return OFF.equalsIgnoreCase(baseMapping.get(ability.name()));
}
@Override
public Ability processAbility(Ability ability) {
if (baseMapping.containsKey(ability.name())) {
return Ability.builder()
.basedOn(ability)
.name(baseMapping.get(ability.name()))
.build();
}
return ability;
}
/**
* @param abilityName the ability you want to change
* @param targetName the final name for this ability
* @return the toggle instance
*/
public CustomToggle toggle(String abilityName, String targetName) {
baseMapping.put(abilityName, targetName);
return this;
}
/**
* @param ability the ability name you would like turned off
* @return the toggle instance
*/
public CustomToggle turnOff(String ability) {
baseMapping.put(ability, OFF);
return this;
}
}

View File

@ -0,0 +1,19 @@
package org.telegram.abilitybots.api.toggle;
import org.telegram.abilitybots.api.objects.Ability;
/**
* If the user does not supply a toggle to their constructor, the default toggle will be instantiated.
* This default toggle allows all the default abilities to be registered.
*/
public class DefaultToggle implements AbilityToggle {
@Override
public boolean isOff(Ability ability) {
return false;
}
@Override
public Ability processAbility(Ability ab) {
return ab;
}
}

View File

@ -244,4 +244,8 @@ public final class AbilityUtils {
return name.toString();
}
public static String escape(String username) {
return username.replace("_", "\\_");
}
}

View File

@ -15,7 +15,7 @@ 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.AbilityBotTest.mockContext;
import static org.telegram.abilitybots.api.bot.TestUtils.mockContext;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
class AbilityBotI18nTest {
@ -24,6 +24,7 @@ class AbilityBotI18nTest {
private DBContext db;
private NoPublicCommandsBot bot;
private DefaultAbilities defaultAbs;
private MessageSender sender;
private SilentSender silent;
@ -32,6 +33,7 @@ class AbilityBotI18nTest {
void setUp() {
db = offlineInstance("db");
bot = new NoPublicCommandsBot(EMPTY, EMPTY, db);
defaultAbs = new DefaultAbilities(bot);
sender = mock(MessageSender.class);
silent = mock(SilentSender.class);
@ -50,7 +52,7 @@ class AbilityBotI18nTest {
void missingPublicCommandsLocalizedInEnglishByDefault() {
MessageContext context = mockContext(NO_LANGUAGE_USER);
bot.reportCommands().action().accept(context);
defaultAbs.reportCommands().action().accept(context);
verify(silent, times(1))
.send("No available commands found.", NO_LANGUAGE_USER.getId());
@ -60,7 +62,7 @@ class AbilityBotI18nTest {
void missingPublicCommandsLocalizedInItalian() {
MessageContext context = mockContext(ITALIAN_USER);
bot.reportCommands().action().accept(context);
defaultAbs.reportCommands().action().accept(context);
verify(silent, times(1))
.send("Non sono presenti comandi disponibile.", ITALIAN_USER.getId());

View File

@ -15,12 +15,7 @@ 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.meta.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.meta.api.objects.ChatMember;
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.*;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.io.BufferedWriter;
@ -39,15 +34,12 @@ import static java.util.Optional.empty;
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.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.telegram.abilitybots.api.bot.DefaultBot.getDefaultBuilder;
import static org.telegram.abilitybots.api.bot.TestUtils.*;
import static org.telegram.abilitybots.api.bot.TestUtils.CREATOR;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
import static org.telegram.abilitybots.api.objects.Flag.DOCUMENT;
import static org.telegram.abilitybots.api.objects.Flag.MESSAGE;
@ -65,10 +57,9 @@ public class AbilityBotTest {
private static final long GROUP_ID = 10L;
private static final String TEST = "test";
private static final String[] TEXT = {TEST};
public static final User USER = new User(1, "first", false, "last", "username", null);
public static final User CREATOR = new User(1337, "creatorFirst", false, "creatorLast", "creatorUsername", null);
private DefaultBot bot;
private DefaultAbilities defaultAbs;
private DBContext db;
private MessageSender sender;
private SilentSender silent;
@ -77,6 +68,7 @@ public class AbilityBotTest {
void setUp() {
db = offlineInstance("db");
bot = new DefaultBot(EMPTY, EMPTY, db);
defaultAbs = new DefaultAbilities(bot);
sender = mock(MessageSender.class);
silent = mock(SilentSender.class);
@ -93,7 +85,7 @@ public class AbilityBotTest {
@Test
void sendsPrivacyViolation() {
Update update = mockFullUpdate(USER, "/admin");
Update update = mockFullUpdate(bot, USER, "/admin");
bot.onUpdateReceived(update);
@ -102,7 +94,7 @@ public class AbilityBotTest {
@Test
void sendsLocalityViolation() {
Update update = mockFullUpdate(USER, "/group");
Update update = mockFullUpdate(bot, USER, "/group");
bot.onUpdateReceived(update);
@ -112,7 +104,7 @@ public class AbilityBotTest {
@Test
void sendsInputArgsViolation() {
Update update = mockFullUpdate(USER, "/count 1 2 3");
Update update = mockFullUpdate(bot, USER, "/count 1 2 3");
bot.onUpdateReceived(update);
@ -121,7 +113,7 @@ public class AbilityBotTest {
@Test
void canProcessRepliesIfSatisfyRequirements() {
Update update = mockFullUpdate(USER, "must reply");
Update update = mockFullUpdate(bot, USER, "must reply");
// False means the update was not pushed down the stream since it has been consumed by the reply
assertFalse(bot.filterReply(update));
@ -132,7 +124,7 @@ public class AbilityBotTest {
void canBackupDB() throws TelegramApiException {
MessageContext context = defaultContext();
bot.backupDB().action().accept(context);
defaultAbs.backupDB().action().accept(context);
deleteQuietly(new java.io.File("backup.json"));
verify(sender, times(1)).sendDocument(any());
@ -147,7 +139,7 @@ public class AbilityBotTest {
// Support for null parameter matching since due to mocking API changes
when(sender.downloadFile(ArgumentMatchers.<File>isNull())).thenReturn(backupFile);
bot.recoverDB().replies().get(0).actOn(update);
defaultAbs.recoverDB().replies().get(0).actOn(update);
verify(silent, times(1)).send(RECOVER_SUCCESS, GROUP_ID);
assertEquals(db.getSet(TEST), newHashSet(TEST), "Bot recovered but the DB is still not in sync");
@ -169,7 +161,7 @@ public class AbilityBotTest {
MessageContext context = defaultContext();
bot.demoteAdmin().action().accept(context);
defaultAbs.demoteAdmin().action().accept(context);
Set<Integer> actual = bot.admins();
Set<Integer> expected = emptySet();
@ -182,7 +174,7 @@ public class AbilityBotTest {
MessageContext context = defaultContext();
bot.promoteAdmin().action().accept(context);
defaultAbs.promoteAdmin().action().accept(context);
Set<Integer> actual = bot.admins();
Set<Integer> expected = newHashSet(USER.getId());
@ -194,7 +186,7 @@ public class AbilityBotTest {
addUsers(USER);
MessageContext context = defaultContext();
bot.banUser().action().accept(context);
defaultAbs.banUser().action().accept(context);
Set<Integer> actual = bot.blacklist();
Set<Integer> expected = newHashSet(USER.getId());
@ -208,7 +200,7 @@ public class AbilityBotTest {
MessageContext context = defaultContext();
bot.unbanUser().action().accept(context);
defaultAbs.unbanUser().action().accept(context);
Set<Integer> actual = bot.blacklist();
Set<Integer> expected = newHashSet();
@ -225,7 +217,7 @@ public class AbilityBotTest {
addUsers(USER, CREATOR);
MessageContext context = mockContext(USER, GROUP_ID, CREATOR.getUserName());
bot.banUser().action().accept(context);
defaultAbs.banUser().action().accept(context);
Set<Integer> actual = bot.blacklist();
Set<Integer> expected = newHashSet(USER.getId());
@ -243,7 +235,7 @@ public class AbilityBotTest {
void creatorCanClaimBot() {
MessageContext context = mockContext(CREATOR, GROUP_ID);
bot.claimCreator().action().accept(context);
defaultAbs.claimCreator().action().accept(context);
Set<Integer> actual = bot.admins();
Set<Integer> expected = newHashSet(CREATOR.getId());
@ -312,7 +304,7 @@ public class AbilityBotTest {
@Test
void canCheckInput() {
Update update = mockFullUpdate(USER, "/something");
Update update = mockFullUpdate(bot, USER, "/something");
Ability abilityWithOneInput = getDefaultBuilder()
.build();
Ability abilityWithZeroInput = getDefaultBuilder()
@ -544,30 +536,11 @@ public class AbilityBotTest {
void canReportCommands() {
MessageContext context = mockContext(USER, GROUP_ID);
bot.reportCommands().action().accept(context);
defaultAbs.reportCommands().action().accept(context);
verify(silent, times(1)).send("default - dis iz default command", GROUP_ID);
}
@NotNull
static MessageContext mockContext(User user) {
return mockContext(user, user.getId());
}
@NotNull
static MessageContext mockContext(User user, long groupId, String... args) {
Update update = mock(Update.class);
Message message = mock(Message.class);
when(update.hasMessage()).thenReturn(true);
when(update.getMessage()).thenReturn(message);
when(message.getFrom()).thenReturn(user);
when(message.hasText()).thenReturn(true);
return newContext(update, user, groupId, args);
}
@Test
void canPrintCommandsBasedOnPrivacy() {
Update update = mock(Update.class);
@ -578,7 +551,7 @@ public class AbilityBotTest {
when(message.hasText()).thenReturn(true);
MessageContext creatorCtx = newContext(update, CREATOR, GROUP_ID);
bot.commands().action().accept(creatorCtx);
defaultAbs.commands().action().accept(creatorCtx);
String expected = "PUBLIC\n/commands\n/count\n/default - dis iz default command\n/group\n/test\nADMIN\n/admin\n/ban\n/demote\n/promote\n/unban\nCREATOR\n/backup\n/claim\n/recover\n/report";
verify(silent, times(1)).send(expected, GROUP_ID);
@ -595,33 +568,12 @@ public class AbilityBotTest {
MessageContext userCtx = newContext(update, USER, GROUP_ID);
bot.commands().action().accept(userCtx);
defaultAbs.commands().action().accept(userCtx);
String expected = "PUBLIC\n/commands\n/count\n/default - dis iz default command\n/group\n/test";
verify(silent, times(1)).send(expected, GROUP_ID);
}
@NotNull
private Update mockFullUpdate(User user, String args) {
bot.users().put(USER.getId(), USER);
bot.users().put(CREATOR.getId(), CREATOR);
bot.userIds().put(CREATOR.getUserName(), CREATOR.getId());
bot.userIds().put(USER.getUserName(), USER.getId());
bot.admins().add(CREATOR.getId());
Update update = mock(Update.class);
when(update.hasMessage()).thenReturn(true);
Message message = mock(Message.class);
when(message.getFrom()).thenReturn(user);
when(message.getText()).thenReturn(args);
when(message.hasText()).thenReturn(true);
when(message.isUserMessage()).thenReturn(true);
when(message.getChatId()).thenReturn((long) user.getId());
when(update.getMessage()).thenReturn(message);
return update;
}
private void mockUser(Update update, Message message, User user) {
when(update.hasMessage()).thenReturn(true);
when(update.getMessage()).thenReturn(message);

View File

@ -3,6 +3,7 @@ package org.telegram.abilitybots.api.bot;
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.toggle.AbilityToggle;
import static org.telegram.abilitybots.api.objects.Ability.builder;
import static org.telegram.abilitybots.api.objects.Flag.CALLBACK_QUERY;
@ -17,6 +18,10 @@ public class DefaultBot extends AbilityBot {
super(token, username, db);
}
public DefaultBot(String token, String username, DBContext db, AbilityToggle toggle) {
super(token, username, db, toggle);
}
public static AbilityBuilder getDefaultBuilder() {
return builder()
.name("test")

View File

@ -0,0 +1,145 @@
package org.telegram.abilitybots.api.bot;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Reply;
import org.telegram.abilitybots.api.objects.ReplyFlow;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.sender.SilentSender;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.io.IOException;
import java.util.function.Predicate;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.telegram.abilitybots.api.bot.TestUtils.USER;
import static org.telegram.abilitybots.api.bot.TestUtils.mockFullUpdate;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
import static org.telegram.abilitybots.api.objects.ReplyFlow.ReplyFlowBuilder.STATES;
import static org.telegram.abilitybots.api.util.AbilityUtils.getChatId;
public class ReplyFlowTest {
private static final int INITIAL_STATE = 1;
private static final int INTERIM_STATE = 2;
private DBContext db;
private ReplyFlowBot bot;
private MessageSender sender;
private SilentSender silent;
@BeforeEach
void setUp() {
db = offlineInstance("db");
bot = new ReplyFlowBot(EMPTY, EMPTY, db);
sender = mock(MessageSender.class);
silent = mock(SilentSender.class);
bot.sender = sender;
bot.silent = silent;
}
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
}
@Test
void doesNotReplyIfFirstReplyFlowDoesNotMatch() {
Update update = mockFullUpdate(bot, USER, "this is not supported");
long chatId = getChatId(update);
assertTrue(bot.filterReply(update));
verify(silent, never()).send("Command me to go left or right!", chatId);
}
@Test
void doesNotReplyIfLaterRepliesAreAttemptedButUserNotInRightState() {
Update update = mockFullUpdate(bot, USER, "left");
long chatId = getChatId(update);
db.<Long, Integer>getMap(STATES).put(chatId, INTERIM_STATE);
assertTrue(bot.filterReply(update));
verify(silent, never()).send("Sir, I have gone left.", chatId);
}
@Test
void repliesIfFirstReplyFlowMatches() {
Update update = mockFullUpdate(bot, USER, "wake up");
long chatId = getChatId(update);
assertFalse(bot.filterReply(update));
verify(silent, only()).send("Command me to go left or right!", chatId);
assertEquals(INITIAL_STATE, db.<Long, Integer>getMap(STATES).get(chatId), "User is not in the proper initial state");
}
@Test
void stateIsNotResetOnFaultyReply() {
Update update = mockFullUpdate(bot, USER, "leffffft");
long chatId = getChatId(update);
db.<Long, Integer>getMap(STATES).put(chatId, INITIAL_STATE);
assertTrue(bot.filterReply(update));
verify(silent, never()).send("I don't know how to go left.", chatId);
assertEquals(INITIAL_STATE, db.<Long, Integer>getMap(STATES).get(chatId), "User is no longer in the initial state after faulty reply");
}
@Test
void terminalRepliesResetState() {
Update update = mockFullUpdate(bot, USER, "go left or else");
long chatId = getChatId(update);
db.<Long, Integer>getMap(STATES).put(chatId, INTERIM_STATE);
assertFalse(bot.filterReply(update));
verify(silent, only()).send("Sir, I have gone left.", chatId);
assertFalse(db.<Long, Integer>getMap(STATES).containsKey(chatId), "User still has state after terminal reply");
}
public static class ReplyFlowBot extends AbilityBot {
private ReplyFlowBot(String botToken, String botUsername, DBContext db) {
super(botToken, botUsername, db);
}
@Override
public int creatorId() {
return 0;
}
public ReplyFlow directionFlow() {
Reply saidLeft = Reply.of(upd -> silent.send("Sir, I have gone left.", getChatId(upd)),
hasMessageWith("go left or else"));
ReplyFlow leftflow = ReplyFlow.builder(db, 2)
.action(upd -> silent.send("I don't know how to go left.", getChatId(upd)))
.onlyIf(hasMessageWith("left"))
.next(saidLeft).build();
Reply saidRight = Reply.of(upd -> silent.send("Sir, I have gone right.", getChatId(upd)),
hasMessageWith("right"));
return ReplyFlow.builder(db, 1)
.action(upd -> silent.send("Command me to go left or right!", getChatId(upd)))
.onlyIf(hasMessageWith("wake up"))
.next(leftflow)
.next(saidRight)
.build();
}
@NotNull
private Predicate<Update> hasMessageWith(String msg) {
return upd -> upd.getMessage().getText().equalsIgnoreCase(msg);
}
}
}

View File

@ -0,0 +1,60 @@
package org.telegram.abilitybots.api.bot;
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(1, "first", false, "last", "username", null);
public static final User CREATOR = new User(1337, "creatorFirst", false, "creatorLast", "creatorUsername", null);
private TestUtils() {
}
@NotNull
static Update mockFullUpdate(AbilityBot bot, User user, String args) {
bot.users().put(USER.getId(), USER);
bot.users().put(CREATOR.getId(), CREATOR);
bot.userIds().put(CREATOR.getUserName(), CREATOR.getId());
bot.userIds().put(USER.getUserName(), USER.getId());
bot.admins().add(CREATOR.getId());
Update update = mock(Update.class);
when(update.hasMessage()).thenReturn(true);
Message message = mock(Message.class);
when(message.getFrom()).thenReturn(user);
when(message.getText()).thenReturn(args);
when(message.hasText()).thenReturn(true);
when(message.isUserMessage()).thenReturn(true);
when(message.getChatId()).thenReturn((long) user.getId());
when(update.getMessage()).thenReturn(message);
return update;
}
@NotNull
static MessageContext mockContext(User user, long groupId, String... args) {
Update update = mock(Update.class);
Message message = mock(Message.class);
when(update.hasMessage()).thenReturn(true);
when(update.getMessage()).thenReturn(message);
when(message.getFrom()).thenReturn(user);
when(message.hasText()).thenReturn(true);
return newContext(update, user, groupId, args);
}
@NotNull
static MessageContext mockContext(User user) {
return mockContext(user, user.getId());
}
}

View File

@ -12,12 +12,13 @@ import java.util.Set;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.Sets.toImmutableEnumSet;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.telegram.abilitybots.api.bot.AbilityBotTest.CREATOR;
import static org.telegram.abilitybots.api.bot.AbilityBotTest.USER;
import static org.telegram.abilitybots.api.bot.TestUtils.CREATOR;
import static org.telegram.abilitybots.api.bot.TestUtils.USER;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
class MapDBContextTest {
@ -38,6 +39,24 @@ class MapDBContextTest {
db.close();
}
@Test
void canRecoverVar() {
Var<String> test = db.getVar(TEST);
String val = "abilitybot";
test.set(val);
Object backup = db.backup();
db.clear();
// db.clear does not clear atomic variables
// TODO: get clear to remove all non-collection variables in DB
test.set("somevalue");
boolean recovered = db.recover(backup);
String recoveredVal = db.<String>getVar(TEST).get();
assertTrue(recovered, "Could not recover JSON backup file");
assertEquals(val, recoveredVal, "Could not properly recover val from Var in DB");
}
@Test
void canRecoverDB() {
Map<Integer, User> users = db.getMap(USERS);

View File

@ -2,15 +2,19 @@ package org.telegram.abilitybots.api.sender;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.updateshandlers.SentCallback;
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.when;
import static org.mockito.Mockito.*;
class SilentSenderTest {
private SilentSender silent;
@ -40,4 +44,34 @@ class SilentSenderTest {
assertEquals(data, execute.get(), "Silent execution resulted in a different object");
}
@Test
void callsAsyncVariantOfExecute() throws TelegramApiException {
SendMessage methodObject = new SendMessage();
NoOpCallback callback = new NoOpCallback();
silent.executeAsync(methodObject, callback);
verify(sender, only()).executeAsync(methodObject, callback);
}
private class NoOpCallback implements SentCallback<Message> {
@Override
public void onResult(BotApiMethod<Message> method, Message response) {
}
@Override
public void onError(BotApiMethod<Message> method, TelegramApiRequestException apiException) {
}
@Override
public void onException(BotApiMethod<Message> method, Exception exception) {
}
}
;
}

View File

@ -0,0 +1,47 @@
package org.telegram.abilitybots.api.toggle;
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.telegram.abilitybots.api.bot.DefaultAbilities;
import org.telegram.abilitybots.api.bot.DefaultBot;
import org.telegram.abilitybots.api.db.DBContext;
import java.io.IOException;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.jupiter.api.Assertions.*;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
public class BareboneToggleTest {
private DBContext db;
private AbilityToggle toggle;
private DefaultBot bareboneBot;
private DefaultAbilities defaultAbs;
@BeforeEach
void setUp() {
db = offlineInstance("db");
toggle = new BareboneToggle();
bareboneBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
defaultAbs = new DefaultAbilities(bareboneBot);
}
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
}
@Test
public void turnsOffAllAbilities() {
assertFalse(bareboneBot.abilities().containsKey(DefaultAbilities.CLAIM));
}
@Test
public void throwsOnProcessingAbility() {
Assertions.assertThrows(RuntimeException.class, () -> toggle.processAbility(defaultAbs.claimCreator()));
}
}

View File

@ -0,0 +1,51 @@
package org.telegram.abilitybots.api.toggle;
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.telegram.abilitybots.api.bot.DefaultAbilities;
import org.telegram.abilitybots.api.bot.DefaultBot;
import org.telegram.abilitybots.api.db.DBContext;
import java.io.IOException;
import static org.apache.commons.lang3.StringUtils.EMPTY;
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 DefaultAbilities defaultAbs;
@BeforeEach
void setUp() {
db = offlineInstance("db");
defaultAbs = new DefaultAbilities(customBot);
}
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
}
@Test
public void canTurnOffAbilities() {
toggle = new CustomToggle().turnOff(DefaultAbilities.CLAIM);
customBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
assertFalse(customBot.abilities().containsKey(DefaultAbilities.CLAIM));
}
@Test
public void canProcessAbilities() {
String targetName = DefaultAbilities.CLAIM + "1toggle";
toggle = new CustomToggle().toggle(DefaultAbilities.CLAIM, targetName);
customBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
assertTrue(customBot.abilities().containsKey(targetName));
}
}

View File

@ -0,0 +1,69 @@
package org.telegram.abilitybots.api.toggle;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.telegram.abilitybots.api.bot.DefaultAbilities;
import org.telegram.abilitybots.api.bot.DefaultBot;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.Ability;
import java.io.IOException;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.jupiter.api.Assertions.*;
import static org.telegram.abilitybots.api.bot.DefaultAbilities.*;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
class DefaultToggleTest {
private DBContext db;
private AbilityToggle toggle;
private DefaultBot defaultBot;
private DefaultAbilities defaultAbs;
@BeforeEach
void setUp() {
db = offlineInstance("db");
defaultAbs = new DefaultAbilities(defaultBot);
}
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
}
@Test
public void claimsEveryAbilityIsOn() {
Ability random = DefaultBot.getDefaultBuilder()
.name("randomsomethingrandom").build();
toggle = new DefaultToggle();
defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
assertFalse(toggle.isOff(random));
}
@Test
public void passedSameAbilityRefOnProcess() {
Ability random = DefaultBot.getDefaultBuilder()
.name("randomsomethingrandom").build();
toggle = new DefaultToggle();
defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
assertSame(random, toggle.processAbility(random), "Toggle returned a different ability");
}
@Test
public void allAbilitiesAreRegistered() {
toggle = new DefaultToggle();
defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle);
Set<String> defaultNames = newHashSet(
CLAIM, BAN, UNBAN,
PROMOTE, DEMOTE, RECOVER,
BACKUP, REPORT, COMMANDS);
assertTrue(defaultBot.abilities().keySet().containsAll(defaultNames), "Toggle returned a different ability");
}
}

View File

@ -414,7 +414,7 @@ public abstract class DefaultAbsSender extends AbsSender {
return sendAudio.deserializeResponse(sendHttpPostRequest(httppost));
} catch (IOException e) {
throw new TelegramApiException("Unable to send sticker", e);
throw new TelegramApiException("Unable to send audio", e);
}
}