commit
608581ce67
@ -1,6 +1,16 @@
|
||||
### <a id="5.1.0"></a>5.1.0 ###
|
||||
1. Update Api version [5.1](https://core.telegram.org/bots/api-changelog#march-9-2021)
|
||||
2. Bug fixing: #832, #841, #844, #851, #857
|
||||
3. Update Spring boot version 2.4.3
|
||||
4. Update Gradle docs
|
||||
5. Added CommandMessage to extensions
|
||||
6. Abilities: Inject bot instance to reply update consumer support for multiple reply declarations.
|
||||
|
||||
**[[How to update to version 5.1.0|How-To-Update#5.1.0]]**
|
||||
|
||||
### <a id="5.0.1"></a>5.0.1 ###
|
||||
1. Fixing couple of bugs from 5.0.0
|
||||
2. Buf fixing: #794
|
||||
2. Bug fixing: #794
|
||||
3. Docs updated to reflect usage for version 5.0.0
|
||||
4. EditMessageText setChatIId(Long) is removed to keep consistency
|
||||
|
||||
|
@ -1,3 +1,6 @@
|
||||
### <a id="5.1.0"></a>To version 5.1.0 ###
|
||||
1. All users IDs fields are now Long type as per API guidelines.
|
||||
|
||||
### <a id="5.0.0"></a>To version 5.0.0 ###
|
||||
1. ApiContextInitializer.init(); has been removed and is not required anymore, instead:
|
||||
```java
|
||||
|
@ -2,7 +2,7 @@
|
||||
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 () {
|
||||
public Ability nice() {
|
||||
return Ability.builder()
|
||||
.name("nice")
|
||||
.privacy(PUBLIC)
|
||||
@ -13,7 +13,7 @@ public class MrGoodGuy implements AbilityExtension {
|
||||
}
|
||||
|
||||
public class MrBadGuy implements AbilityExtension {
|
||||
public Ability () {
|
||||
public Ability notnice() {
|
||||
return Ability.builder()
|
||||
.name("notnice")
|
||||
.privacy(PUBLIC)
|
||||
@ -51,4 +51,4 @@ It's also possible to add extensions in the constructor by using the `addExtensi
|
||||
|
||||
// Override creatorId
|
||||
}
|
||||
```
|
||||
```
|
||||
|
4
pom.xml
4
pom.xml
@ -7,7 +7,7 @@
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
|
||||
<modules>
|
||||
<module>telegrambots</module>
|
||||
@ -67,7 +67,7 @@
|
||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||
|
||||
<junit.version>5.7.0</junit.version>
|
||||
<junit.version>5.7.1</junit.version>
|
||||
<mockito.version>3.6.0</mockito.version>
|
||||
<mockitojupiter.version>3.6.0</mockitojupiter.version>
|
||||
<jacksonanotation.version>2.11.3</jacksonanotation.version>
|
||||
|
@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>telegrambots-abilities</artifactId>
|
||||
@ -84,7 +84,7 @@
|
||||
<dependency>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>telegrambots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
|
@ -58,14 +58,14 @@ public abstract class AbilityWebhookBot extends BaseAbilityBot implements Webhoo
|
||||
}
|
||||
|
||||
@Override
|
||||
public BotApiMethod onWebhookUpdateReceived(Update update) {
|
||||
public BotApiMethod<?> onWebhookUpdateReceived(Update update) {
|
||||
super.onUpdateReceived(update);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWebhook(SetWebhook setWebhook) throws TelegramApiException {
|
||||
WebhookUtils.setWebhook(this, setWebhook);
|
||||
WebhookUtils.setWebhook(this, this, setWebhook);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -113,7 +113,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
// Reply registry
|
||||
private List<Reply> replies;
|
||||
|
||||
public abstract int creatorId();
|
||||
public abstract long creatorId();
|
||||
|
||||
protected BaseAbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) {
|
||||
super(botOptions);
|
||||
@ -155,28 +155,28 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
/**
|
||||
* @return the map of <ID,User>
|
||||
*/
|
||||
public Map<Integer, User> users() {
|
||||
public Map<Long, User> users() {
|
||||
return db.getMap(USERS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the map of <Username,ID>
|
||||
*/
|
||||
public Map<String, Integer> userIds() {
|
||||
public Map<String, Long> userIds() {
|
||||
return db.getMap(USER_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a blacklist containing all the IDs of the banned users
|
||||
*/
|
||||
public Set<Integer> blacklist() {
|
||||
public Set<Long> blacklist() {
|
||||
return db.getSet(BLACKLIST);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return an admin set of all the IDs of bot administrators
|
||||
*/
|
||||
public Set<Integer> admins() {
|
||||
public Set<Long> admins() {
|
||||
return db.getSet(ADMINS);
|
||||
}
|
||||
|
||||
@ -246,29 +246,29 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
return botUsername;
|
||||
}
|
||||
|
||||
public Privacy getPrivacy(Update update, int id) {
|
||||
public Privacy getPrivacy(Update update, long id) {
|
||||
return isCreator(id) ?
|
||||
CREATOR : isAdmin(id) ?
|
||||
ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ?
|
||||
GROUP_ADMIN : PUBLIC;
|
||||
}
|
||||
|
||||
public boolean isGroupAdmin(Update update, int id) {
|
||||
public boolean isGroupAdmin(Update update, long id) {
|
||||
return isGroupAdmin(getChatId(update), id);
|
||||
}
|
||||
|
||||
public boolean isGroupAdmin(long chatId, int id) {
|
||||
public boolean isGroupAdmin(long chatId, long id) {
|
||||
GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build();
|
||||
return silent.execute(admins)
|
||||
.orElse(new ArrayList<>()).stream()
|
||||
.anyMatch(member -> member.getUser().getId() == id);
|
||||
}
|
||||
|
||||
public boolean isCreator(int id) {
|
||||
public boolean isCreator(long id) {
|
||||
return id == creatorId();
|
||||
}
|
||||
|
||||
public boolean isAdmin(Integer id) {
|
||||
public boolean isAdmin(long id) {
|
||||
return admins().contains(id);
|
||||
}
|
||||
|
||||
@ -350,16 +350,25 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
.map(returnReply(ext)))
|
||||
.flatMap(Reply::stream);
|
||||
|
||||
// Extract all replies from extension instances methods, returning ReplyCollection
|
||||
Stream<Reply> extensionCollectionReplies = extensions.stream()
|
||||
.flatMap(extension -> stream(extension.getClass().getMethods())
|
||||
.filter(checkReturnType(ReplyCollection.class))
|
||||
.map(returnReplyCollection(extension))
|
||||
.flatMap(ReplyCollection::stream));
|
||||
|
||||
// Replies can be standalone or attached to abilities, fetch those too
|
||||
Stream<Reply> abilityReplies = abilities.values().stream()
|
||||
.flatMap(ability -> ability.replies().stream())
|
||||
.flatMap(Reply::stream);
|
||||
|
||||
// Now create the replies registry (list)
|
||||
replies = Stream.concat(abilityReplies, extensionReplies).collect(
|
||||
ImmutableList::<Reply>builder,
|
||||
Builder::add,
|
||||
(b1, b2) -> b1.addAll(b2.build()))
|
||||
replies = Stream.of(abilityReplies, extensionReplies, extensionCollectionReplies)
|
||||
.flatMap(replyStream -> replyStream)
|
||||
.collect(
|
||||
ImmutableList::<Reply>builder,
|
||||
Builder::add,
|
||||
(b1, b2) -> b1.addAll(b2.build()))
|
||||
.build();
|
||||
} catch (IllegalStateException e) {
|
||||
log.error("Duplicate names found while registering abilities. Make sure that the abilities declared don't clash with the reserved ones.", e);
|
||||
@ -439,6 +448,23 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the method and retrieves its return {@link ReplyCollection}.
|
||||
*
|
||||
* @param obj a bot or extension that this method is invoked with
|
||||
* @return a {@link Function} which returns the {@link ReplyCollection} returned by the given method
|
||||
*/
|
||||
private static Function<? super Method, ReplyCollection> returnReplyCollection(Object obj) {
|
||||
return method -> {
|
||||
try {
|
||||
return (ReplyCollection) method.invoke(obj);
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
log.error("Could not add Reply Collection", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void postConsumption(Pair<MessageContext, Ability> pair) {
|
||||
ofNullable(pair.b().postAction())
|
||||
.ifPresent(consumer -> consumer.accept(pair.a()));
|
||||
@ -482,7 +508,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
return true;
|
||||
}
|
||||
|
||||
int id = user.getId();
|
||||
long id = user.getId();
|
||||
return id == creatorId() || !blacklist().contains(id);
|
||||
}
|
||||
|
||||
@ -523,7 +549,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
Update update = trio.a();
|
||||
User user = AbilityUtils.getUser(update);
|
||||
Privacy privacy;
|
||||
int id = user.getId();
|
||||
long id = user.getId();
|
||||
|
||||
privacy = getPrivacy(update, id);
|
||||
|
||||
@ -625,7 +651,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
return replies.stream()
|
||||
.filter(reply -> runSilently(() -> reply.isOkFor(update), reply.name()))
|
||||
.map(reply -> runSilently(() -> {
|
||||
reply.actOn(update);
|
||||
reply.actOn(this, update);
|
||||
updateReplyStats(reply);
|
||||
return false;
|
||||
}, reply.name()))
|
||||
@ -651,4 +677,4 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
|
||||
return ability.flags().stream()
|
||||
.reduce(true, flagAnd, Boolean::logicalAnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -254,7 +254,7 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
.input(0)
|
||||
.action(ctx -> bot.silent.forceReply(
|
||||
getLocalizedMessage(ABILITY_RECOVER_MESSAGE, ctx.user().getLanguageCode()), ctx.chatId()))
|
||||
.reply(update -> {
|
||||
.reply((bot, update) -> {
|
||||
String replyToMsg = update.getMessage().getReplyToMessage().getText();
|
||||
String recoverMessage = getLocalizedMessage(ABILITY_RECOVER_MESSAGE, AbilityUtils.getUser(update).getLanguageCode());
|
||||
if (!replyToMsg.equals(recoverMessage))
|
||||
@ -293,7 +293,7 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
.input(1)
|
||||
.action(ctx -> {
|
||||
String username = stripTag(ctx.firstArg());
|
||||
int userId = getUserIdSendError(username, ctx);
|
||||
long userId = getUserIdSendError(username, ctx);
|
||||
String bannedUser;
|
||||
|
||||
// Protection from abuse
|
||||
@ -304,7 +304,7 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
bannedUser = addTag(username);
|
||||
}
|
||||
|
||||
Set<Integer> blacklist = bot.blacklist();
|
||||
Set<Long> blacklist = bot.blacklist();
|
||||
if (blacklist.contains(userId))
|
||||
sendMd(ABILITY_BAN_FAIL, ctx, escape(bannedUser));
|
||||
else {
|
||||
@ -328,9 +328,9 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
.input(1)
|
||||
.action(ctx -> {
|
||||
String username = stripTag(ctx.firstArg());
|
||||
Integer userId = getUserIdSendError(username, ctx);
|
||||
Long userId = getUserIdSendError(username, ctx);
|
||||
|
||||
Set<Integer> blacklist = bot.blacklist();
|
||||
Set<Long> blacklist = bot.blacklist();
|
||||
|
||||
if (!blacklist.remove(userId))
|
||||
bot.silent.sendMd(getLocalizedMessage(ABILITY_UNBAN_FAIL, ctx.user().getLanguageCode(), escape(username)), ctx.chatId());
|
||||
@ -352,9 +352,9 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
.input(1)
|
||||
.action(ctx -> {
|
||||
String username = stripTag(ctx.firstArg());
|
||||
Integer userId = getUserIdSendError(username, ctx);
|
||||
Long userId = getUserIdSendError(username, ctx);
|
||||
|
||||
Set<Integer> admins = bot.admins();
|
||||
Set<Long> admins = bot.admins();
|
||||
if (admins.contains(userId))
|
||||
sendMd(ABILITY_PROMOTE_FAIL, ctx, escape(username));
|
||||
else {
|
||||
@ -376,9 +376,9 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
.input(1)
|
||||
.action(ctx -> {
|
||||
String username = stripTag(ctx.firstArg());
|
||||
Integer userId = getUserIdSendError(username, ctx);
|
||||
Long userId = getUserIdSendError(username, ctx);
|
||||
|
||||
Set<Integer> admins = bot.admins();
|
||||
Set<Long> admins = bot.admins();
|
||||
if (admins.remove(userId)) {
|
||||
sendMd(ABILITY_DEMOTE_SUCCESS, ctx, escape(username));
|
||||
} else {
|
||||
@ -400,8 +400,8 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
.privacy(CREATOR)
|
||||
.input(0)
|
||||
.action(ctx -> {
|
||||
Set<Integer> admins = bot.admins();
|
||||
int id = bot.creatorId();
|
||||
Set<Long> admins = bot.admins();
|
||||
long id = bot.creatorId();
|
||||
|
||||
if (admins.contains(id))
|
||||
send(ABILITY_CLAIM_FAIL, ctx);
|
||||
@ -420,7 +420,7 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
* @return the user
|
||||
*/
|
||||
private User getUser(String username) {
|
||||
Integer id = bot.userIds().get(username.toLowerCase());
|
||||
Long id = bot.userIds().get(username.toLowerCase());
|
||||
if (id == null) {
|
||||
throw new IllegalStateException(format("Could not find ID corresponding to username [%s]", username));
|
||||
}
|
||||
@ -434,7 +434,7 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
* @param id the id of the required user
|
||||
* @return the user
|
||||
*/
|
||||
private User getUser(int id) {
|
||||
private User getUser(long id) {
|
||||
User user = bot.users().get(id);
|
||||
if (user == null) {
|
||||
throw new IllegalStateException(format("Could not find user corresponding to id [%d]", id));
|
||||
@ -450,7 +450,7 @@ public final class DefaultAbilities implements AbilityExtension {
|
||||
* @param ctx the message context with the originating user
|
||||
* @return the id of the user
|
||||
*/
|
||||
private int getUserIdSendError(String username, MessageContext ctx) {
|
||||
private long getUserIdSendError(String username, MessageContext ctx) {
|
||||
try {
|
||||
return getUser(username).getId();
|
||||
} catch (IllegalStateException ex) {
|
||||
|
@ -4,10 +4,12 @@ import com.google.common.base.MoreObjects;
|
||||
import com.google.common.base.Objects;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@ -208,12 +210,22 @@ public final class Ability {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please use {@link #reply(BiConsumer, Predicate[])}
|
||||
*/
|
||||
@Deprecated
|
||||
@SafeVarargs
|
||||
public final AbilityBuilder reply(Consumer<Update> action, Predicate<Update>... conditions) {
|
||||
replies.add(Reply.of(action, conditions));
|
||||
return this;
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public final AbilityBuilder reply(BiConsumer<BaseAbilityBot, Update> action, Predicate<Update>... conditions) {
|
||||
replies.add(Reply.of(action, conditions));
|
||||
return this;
|
||||
}
|
||||
|
||||
public final AbilityBuilder reply(Reply reply) {
|
||||
replies.add(reply);
|
||||
return this;
|
||||
|
@ -29,6 +29,9 @@ public enum Flag implements Predicate<Update> {
|
||||
PRECHECKOUT_QUERY(Update::hasPreCheckoutQuery),
|
||||
POLL(Update::hasPoll),
|
||||
POLL_ANSWER(Update::hasPollAnswer),
|
||||
MY_CHAT_MEMBER(Update::hasMyChatMember),
|
||||
CHAT_MEMBER(Update::hasChatMember),
|
||||
|
||||
|
||||
// Message Flags
|
||||
REPLY(upd -> MESSAGE.test(upd) && upd.getMessage().isReply()),
|
||||
|
@ -2,10 +2,12 @@ package org.telegram.abilitybots.api.objects;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
@ -22,18 +24,41 @@ import static com.google.common.collect.Lists.newArrayList;
|
||||
*/
|
||||
public class Reply {
|
||||
public final List<Predicate<Update>> conditions;
|
||||
public final Consumer<Update> action;
|
||||
public final BiConsumer<BaseAbilityBot, Update> action;
|
||||
private boolean statsEnabled;
|
||||
private String name;
|
||||
|
||||
Reply(List<Predicate<Update>> conditions, Consumer<Update> action) {
|
||||
Reply(List<Predicate<Update>> conditions, BiConsumer<BaseAbilityBot, Update> action) {
|
||||
this.conditions = ImmutableList.<Predicate<Update>>builder()
|
||||
.addAll(conditions)
|
||||
.build();
|
||||
.addAll(conditions)
|
||||
.build();
|
||||
this.action = action;
|
||||
statsEnabled = false;
|
||||
}
|
||||
|
||||
Reply(List<Predicate<Update>> conditions, BiConsumer<BaseAbilityBot, Update> action, String name) {
|
||||
this(conditions, action);
|
||||
if (Objects.nonNull(name)) {
|
||||
enableStats(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please use {@link #Reply(List, BiConsumer)}
|
||||
*/
|
||||
@Deprecated
|
||||
Reply(List<Predicate<Update>> conditions, Consumer<Update> action) {
|
||||
this.conditions = ImmutableList.<Predicate<Update>>builder()
|
||||
.addAll(conditions)
|
||||
.build();
|
||||
this.action = ((baseAbilityBot, update) -> action.accept(update));
|
||||
statsEnabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please use {@link #Reply(List, BiConsumer, String)}
|
||||
*/
|
||||
@Deprecated
|
||||
Reply(List<Predicate<Update>> conditions, Consumer<Update> action, String name) {
|
||||
this(conditions, action);
|
||||
if (Objects.nonNull(name)) {
|
||||
@ -41,10 +66,27 @@ public class Reply {
|
||||
}
|
||||
}
|
||||
|
||||
public static Reply of(BiConsumer<BaseAbilityBot, Update> action, List<Predicate<Update>> conditions) {
|
||||
return new Reply(conditions, action);
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static Reply of(BiConsumer<BaseAbilityBot, Update> action, Predicate<Update>... conditions) {
|
||||
return Reply.of(action, newArrayList(conditions));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please use {@link #of(BiConsumer, List)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static Reply of(Consumer<Update> action, List<Predicate<Update>> conditions) {
|
||||
return new Reply(conditions, action);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please use {@link #of(BiConsumer, Predicate[])}
|
||||
*/
|
||||
@Deprecated
|
||||
@SafeVarargs
|
||||
public static Reply of(Consumer<Update> action, Predicate<Update>... conditions) {
|
||||
return Reply.of(action, newArrayList(conditions));
|
||||
@ -56,15 +98,15 @@ public class Reply {
|
||||
return conditions.stream().reduce(true, stateAnd, Boolean::logicalAnd);
|
||||
}
|
||||
|
||||
public void actOn(Update update) {
|
||||
action.accept(update);
|
||||
public void actOn(BaseAbilityBot bot, Update update) {
|
||||
action.accept(bot, update);
|
||||
}
|
||||
|
||||
public List<Predicate<Update>> conditions() {
|
||||
return conditions;
|
||||
}
|
||||
|
||||
public Consumer<Update> action() {
|
||||
public BiConsumer<BaseAbilityBot, Update> action() {
|
||||
return action;
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,32 @@
|
||||
package org.telegram.abilitybots.api.objects;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.google.common.collect.Lists.newArrayList;
|
||||
|
||||
/**
|
||||
* A wrapping object containing Replies. Return this in your bot class to get replies registered.
|
||||
*
|
||||
* @see Reply
|
||||
*/
|
||||
public class ReplyCollection {
|
||||
|
||||
public final Collection<Reply> replies;
|
||||
|
||||
public ReplyCollection(Collection<Reply> replies) {
|
||||
this.replies = replies;
|
||||
}
|
||||
|
||||
public Collection<Reply> getReplies() {
|
||||
return replies;
|
||||
}
|
||||
|
||||
public Stream<Reply> stream(){
|
||||
return replies.stream();
|
||||
}
|
||||
|
||||
public static ReplyCollection of(Reply... replies){
|
||||
return new ReplyCollection(newArrayList(replies));
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
package org.telegram.abilitybots.api.objects;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
||||
import org.telegram.abilitybots.api.db.DBContext;
|
||||
import org.telegram.abilitybots.api.util.AbilityUtils;
|
||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||
@ -10,6 +11,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
@ -20,7 +22,7 @@ public class ReplyFlow extends Reply {
|
||||
|
||||
private final Set<Reply> nextReplies;
|
||||
|
||||
private ReplyFlow(List<Predicate<Update>> conditions, Consumer<Update> action, Set<Reply> nextReplies, String name) {
|
||||
private ReplyFlow(List<Predicate<Update>> conditions, BiConsumer<BaseAbilityBot, Update> action, Set<Reply> nextReplies, String name) {
|
||||
super(conditions, action, name);
|
||||
this.nextReplies = nextReplies;
|
||||
}
|
||||
@ -48,7 +50,7 @@ public class ReplyFlow extends Reply {
|
||||
private final DBContext db;
|
||||
private final int id;
|
||||
private List<Predicate<Update>> conds;
|
||||
private Consumer<Update> action;
|
||||
private BiConsumer<BaseAbilityBot, Update> action;
|
||||
private Set<Reply> nextReplies;
|
||||
private String name;
|
||||
|
||||
@ -63,7 +65,16 @@ public class ReplyFlow extends Reply {
|
||||
this(db, replyCounter.getAndIncrement());
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please use {@link #action(BiConsumer)}
|
||||
*/
|
||||
@Deprecated
|
||||
public ReplyFlowBuilder action(Consumer<Update> action) {
|
||||
this.action = (bot, update) -> action.accept(update);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ReplyFlowBuilder action(BiConsumer<BaseAbilityBot, Update> action) {
|
||||
this.action = action;
|
||||
return this;
|
||||
}
|
||||
@ -80,7 +91,7 @@ public class ReplyFlow extends Reply {
|
||||
|
||||
public ReplyFlowBuilder next(Reply nextReply) {
|
||||
List<Predicate<Update>> statefulConditions = toStateful(nextReply.conditions());
|
||||
Consumer<Update> statefulAction = nextReply.action().andThen(upd -> {
|
||||
BiConsumer<BaseAbilityBot, Update> statefulAction = nextReply.action().andThen((unused, upd) -> {
|
||||
Long chatId = AbilityUtils.getChatId(upd);
|
||||
db.<Long, Integer>getMap(STATES).remove(chatId);
|
||||
});
|
||||
@ -100,16 +111,16 @@ public class ReplyFlow extends Reply {
|
||||
|
||||
public ReplyFlow build() {
|
||||
if (action == null)
|
||||
action = upd -> {};
|
||||
action = (bot, upd) -> {};
|
||||
|
||||
Consumer<Update> statefulAction;
|
||||
BiConsumer<BaseAbilityBot, Update> statefulAction;
|
||||
if (nextReplies.size() > 0) {
|
||||
statefulAction = action.andThen(upd -> {
|
||||
statefulAction = action.andThen((bot, upd) -> {
|
||||
Long chatId = AbilityUtils.getChatId(upd);
|
||||
db.<Long, Integer>getMap(STATES).put(chatId, id);
|
||||
});
|
||||
} else {
|
||||
statefulAction = action.andThen(upd -> {
|
||||
statefulAction = action.andThen((bot, upd) -> {
|
||||
Long chatId = AbilityUtils.getChatId(upd);
|
||||
db.<Long, Integer>getMap(STATES).remove(chatId);
|
||||
});
|
||||
|
@ -25,7 +25,7 @@ import static org.telegram.abilitybots.api.objects.Flag.*;
|
||||
* Helper and utility methods
|
||||
*/
|
||||
public final class AbilityUtils {
|
||||
public static User EMPTY_USER = new User(0, "", false);
|
||||
public static User EMPTY_USER = new User(0L, "", false);
|
||||
|
||||
private AbilityUtils() {
|
||||
|
||||
@ -82,6 +82,10 @@ public final class AbilityUtils {
|
||||
return update.getPreCheckoutQuery().getFrom();
|
||||
} else if (POLL_ANSWER.test(update)) {
|
||||
return update.getPollAnswer().getUser();
|
||||
} else if (MY_CHAT_MEMBER.test(update)) {
|
||||
return update.getMyChatMember().getFrom();
|
||||
} else if (CHAT_MEMBER.test(update)) {
|
||||
return update.getChatMember().getFrom();
|
||||
} else if (POLL.test(update)) {
|
||||
return EMPTY_USER;
|
||||
} else {
|
||||
@ -146,7 +150,7 @@ public final class AbilityUtils {
|
||||
} else if (CALLBACK_QUERY.test(update)) {
|
||||
return update.getCallbackQuery().getMessage().getChatId();
|
||||
} else if (INLINE_QUERY.test(update)) {
|
||||
return (long) update.getInlineQuery().getFrom().getId();
|
||||
return update.getInlineQuery().getFrom().getId();
|
||||
} else if (CHANNEL_POST.test(update)) {
|
||||
return update.getChannelPost().getChatId();
|
||||
} else if (EDITED_CHANNEL_POST.test(update)) {
|
||||
@ -154,15 +158,19 @@ public final class AbilityUtils {
|
||||
} else if (EDITED_MESSAGE.test(update)) {
|
||||
return update.getEditedMessage().getChatId();
|
||||
} else if (CHOSEN_INLINE_QUERY.test(update)) {
|
||||
return (long) update.getChosenInlineQuery().getFrom().getId();
|
||||
return update.getChosenInlineQuery().getFrom().getId();
|
||||
} else if (SHIPPING_QUERY.test(update)) {
|
||||
return (long) update.getShippingQuery().getFrom().getId();
|
||||
return update.getShippingQuery().getFrom().getId();
|
||||
} else if (PRECHECKOUT_QUERY.test(update)) {
|
||||
return (long) update.getPreCheckoutQuery().getFrom().getId();
|
||||
return update.getPreCheckoutQuery().getFrom().getId();
|
||||
} else if (POLL_ANSWER.test(update)) {
|
||||
return (long) update.getPollAnswer().getUser().getId();
|
||||
return update.getPollAnswer().getUser().getId();
|
||||
} else if (POLL.test(update)) {
|
||||
return (long) EMPTY_USER.getId();
|
||||
return EMPTY_USER.getId();
|
||||
} else if (MY_CHAT_MEMBER.test(update)) {
|
||||
return update.getMyChatMember().getChat().getId();
|
||||
} else if (CHAT_MEMBER.test(update)) {
|
||||
return update.getChatMember().getChat().getId();
|
||||
} else {
|
||||
throw new IllegalStateException("Could not retrieve originating chat ID from update");
|
||||
}
|
||||
|
@ -19,8 +19,8 @@ import static org.telegram.abilitybots.api.bot.TestUtils.mockContext;
|
||||
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
|
||||
|
||||
class AbilityBotI18nTest {
|
||||
private static final User NO_LANGUAGE_USER = new User(1, "first", false, "last", "username", null, false, false, false);
|
||||
private static final User ITALIAN_USER = new User(2, "first", false, "last", "username", "it-IT", false, false, false);
|
||||
private static final User NO_LANGUAGE_USER = new User(1L, "first", false, "last", "username", null, false, false, false);
|
||||
private static final User ITALIAN_USER = new User(2L, "first", false, "last", "username", "it-IT", false, false, false);
|
||||
|
||||
private DBContext db;
|
||||
private NoPublicCommandsBot bot;
|
||||
@ -76,7 +76,7 @@ class AbilityBotI18nTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int creatorId() {
|
||||
public long creatorId() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
@ -40,7 +40,7 @@ import static org.apache.commons.lang3.StringUtils.EMPTY;
|
||||
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.DefaultBot.*;
|
||||
import static org.telegram.abilitybots.api.bot.TestUtils.CREATOR;
|
||||
import static org.telegram.abilitybots.api.bot.TestUtils.*;
|
||||
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
|
||||
@ -210,7 +210,7 @@ public class AbilityBotTest {
|
||||
// Support for null parameter matching since due to mocking API changes
|
||||
when(sender.downloadFile(ArgumentMatchers.<File>isNull())).thenReturn(backupFile);
|
||||
|
||||
defaultAbs.recoverDB().replies().get(0).actOn(update);
|
||||
defaultAbs.recoverDB().replies().get(0).actOn(bot, 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");
|
||||
@ -234,8 +234,8 @@ public class AbilityBotTest {
|
||||
|
||||
defaultAbs.demoteAdmin().action().accept(context);
|
||||
|
||||
Set<Integer> actual = bot.admins();
|
||||
Set<Integer> expected = emptySet();
|
||||
Set<Long> actual = bot.admins();
|
||||
Set<Long> expected = emptySet();
|
||||
assertEquals(expected, actual, "Could not sudont super-admin");
|
||||
}
|
||||
|
||||
@ -247,8 +247,8 @@ public class AbilityBotTest {
|
||||
|
||||
defaultAbs.promoteAdmin().action().accept(context);
|
||||
|
||||
Set<Integer> actual = bot.admins();
|
||||
Set<Integer> expected = newHashSet(USER.getId());
|
||||
Set<Long> actual = bot.admins();
|
||||
Set<Long> expected = newHashSet(USER.getId());
|
||||
assertEquals(expected, actual, "Could not sudo user");
|
||||
}
|
||||
|
||||
@ -259,8 +259,8 @@ public class AbilityBotTest {
|
||||
|
||||
defaultAbs.banUser().action().accept(context);
|
||||
|
||||
Set<Integer> actual = bot.blacklist();
|
||||
Set<Integer> expected = newHashSet(USER.getId());
|
||||
Set<Long> actual = bot.blacklist();
|
||||
Set<Long> expected = newHashSet(USER.getId());
|
||||
assertEquals(expected, actual, "The ban was not emplaced");
|
||||
}
|
||||
|
||||
@ -273,8 +273,8 @@ public class AbilityBotTest {
|
||||
|
||||
defaultAbs.unbanUser().action().accept(context);
|
||||
|
||||
Set<Integer> actual = bot.blacklist();
|
||||
Set<Integer> expected = newHashSet();
|
||||
Set<Long> actual = bot.blacklist();
|
||||
Set<Long> expected = newHashSet();
|
||||
assertEquals(expected, actual, "The ban was not lifted");
|
||||
}
|
||||
|
||||
@ -290,8 +290,8 @@ public class AbilityBotTest {
|
||||
|
||||
defaultAbs.banUser().action().accept(context);
|
||||
|
||||
Set<Integer> actual = bot.blacklist();
|
||||
Set<Integer> expected = newHashSet(USER.getId());
|
||||
Set<Long> actual = bot.blacklist();
|
||||
Set<Long> expected = newHashSet(USER.getId());
|
||||
assertEquals(expected, actual, "Impostor was not added to the blacklist");
|
||||
}
|
||||
|
||||
@ -308,8 +308,8 @@ public class AbilityBotTest {
|
||||
|
||||
defaultAbs.claimCreator().action().accept(context);
|
||||
|
||||
Set<Integer> actual = bot.admins();
|
||||
Set<Integer> expected = newHashSet(CREATOR.getId());
|
||||
Set<Long> actual = bot.admins();
|
||||
Set<Long> expected = newHashSet(CREATOR.getId());
|
||||
assertEquals(expected, actual, "Creator was not properly added to the super admins set");
|
||||
}
|
||||
|
||||
@ -335,8 +335,8 @@ public class AbilityBotTest {
|
||||
|
||||
bot.addUser(update);
|
||||
|
||||
Map<String, Integer> expectedUserIds = ImmutableMap.of(USER.getUserName(), USER.getId());
|
||||
Map<Integer, User> expectedUsers = ImmutableMap.of(USER.getId(), USER);
|
||||
Map<String, Long> expectedUserIds = ImmutableMap.of(USER.getUserName(), USER.getId());
|
||||
Map<Long, User> expectedUsers = ImmutableMap.of(USER.getId(), USER);
|
||||
assertEquals(expectedUserIds, bot.userIds(), "User was not added");
|
||||
assertEquals(expectedUsers, bot.users(), "User was not added");
|
||||
}
|
||||
@ -350,15 +350,15 @@ public class AbilityBotTest {
|
||||
String newUsername = USER.getUserName() + "-test";
|
||||
String newFirstName = USER.getFirstName() + "-test";
|
||||
String newLastName = USER.getLastName() + "-test";
|
||||
int sameId = USER.getId();
|
||||
long sameId = USER.getId();
|
||||
User changedUser = new User(sameId, newFirstName, false, newLastName, newUsername, "en", false, false, false);
|
||||
|
||||
mockAlternateUser(update, message, changedUser);
|
||||
|
||||
bot.addUser(update);
|
||||
|
||||
Map<String, Integer> expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId());
|
||||
Map<Integer, User> expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser);
|
||||
Map<String, Long> expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId());
|
||||
Map<Long, User> expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser);
|
||||
assertEquals(bot.userIds(), expectedUserIds, "User was not properly edited");
|
||||
assertEquals(expectedUsers, expectedUsers, "User was not properly edited");
|
||||
}
|
||||
@ -661,6 +661,30 @@ public class AbilityBotTest {
|
||||
verify(silent, times(1)).send(expected, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void canProcessRepliesRegisteredInCollection() {
|
||||
Update firstUpdate = mock(Update.class);
|
||||
Message firstMessage = mock(Message.class);
|
||||
when(firstMessage.getText()).thenReturn(FIRST_REPLY_KEY_MESSAGE);
|
||||
when(firstMessage.getChatId()).thenReturn(1L);
|
||||
|
||||
Update secondUpdate = mock(Update.class);
|
||||
Message secondMessage = mock(Message.class);
|
||||
when(secondMessage.getText()).thenReturn(SECOND_REPLY_KEY_MESSAGE);
|
||||
when(secondMessage.getChatId()).thenReturn(1L);
|
||||
|
||||
mockUser(firstUpdate, firstMessage, USER);
|
||||
mockUser(secondUpdate, secondMessage, USER);
|
||||
|
||||
|
||||
bot.onUpdateReceived(firstUpdate);
|
||||
bot.onUpdateReceived(secondUpdate);
|
||||
|
||||
verify(silent, times(2)).send(anyString(), anyLong());
|
||||
verify(silent, times(1)).send("first reply answer", 1);
|
||||
verify(silent, times(1)).send("second reply answer", 1);
|
||||
}
|
||||
|
||||
private void handlesAllUpdates(Consumer<Update> utilMethod) {
|
||||
Arrays.stream(Update.class.getMethods())
|
||||
// filter to all these methods of hasXXX (hasPoll, hasMessage, etc...)
|
||||
|
@ -22,7 +22,7 @@ import static org.telegram.abilitybots.api.objects.Locality.ALL;
|
||||
import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC;
|
||||
|
||||
public class ContinuousTextTest {
|
||||
private static final User USER = new User(1, "first", false);
|
||||
private static final User USER = new User(1L, "first", false);
|
||||
|
||||
private DBContext db;
|
||||
|
||||
@ -71,7 +71,7 @@ public class ContinuousTextTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int creatorId() {
|
||||
public long creatorId() {
|
||||
return 1337;
|
||||
}
|
||||
|
||||
|
@ -5,6 +5,7 @@ import org.telegram.abilitybots.api.objects.Ability;
|
||||
import org.telegram.abilitybots.api.objects.Ability.AbilityBuilder;
|
||||
import org.telegram.abilitybots.api.objects.Flag;
|
||||
import org.telegram.abilitybots.api.objects.Reply;
|
||||
import org.telegram.abilitybots.api.objects.ReplyCollection;
|
||||
import org.telegram.abilitybots.api.toggle.AbilityToggle;
|
||||
|
||||
import static org.telegram.abilitybots.api.objects.Ability.builder;
|
||||
@ -15,6 +16,8 @@ import static org.telegram.abilitybots.api.objects.Privacy.ADMIN;
|
||||
import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC;
|
||||
|
||||
public class DefaultBot extends AbilityBot {
|
||||
public static final String FIRST_REPLY_KEY_MESSAGE = "first reply key string";
|
||||
public static final String SECOND_REPLY_KEY_MESSAGE = "second reply key string";
|
||||
|
||||
public DefaultBot(String token, String username, DBContext db) {
|
||||
super(token, username, db);
|
||||
@ -35,16 +38,16 @@ public class DefaultBot extends AbilityBot {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int creatorId() {
|
||||
return 1337;
|
||||
public long creatorId() {
|
||||
return 1337L;
|
||||
}
|
||||
|
||||
public Ability defaultAbility() {
|
||||
return getDefaultBuilder()
|
||||
.name(DEFAULT)
|
||||
.info("dis iz default command")
|
||||
.reply(Reply.of(upd -> silent.send("reply", upd.getMessage().getChatId()), MESSAGE, update -> update.getMessage().getText().equals("must reply")).enableStats("mustreply"))
|
||||
.reply(upd -> silent.send("reply", upd.getCallbackQuery().getMessage().getChatId()), CALLBACK_QUERY)
|
||||
.reply(Reply.of((bot, upd) -> silent.send("reply", upd.getMessage().getChatId()), MESSAGE, update -> update.getMessage().getText().equals("must reply")).enableStats("mustreply"))
|
||||
.reply((bot, upd) -> silent.send("reply", upd.getCallbackQuery().getMessage().getChatId()), CALLBACK_QUERY)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ -75,11 +78,24 @@ public class DefaultBot extends AbilityBot {
|
||||
|
||||
public Reply channelPostReply() {
|
||||
return Reply.of(
|
||||
upd -> silent.send("test channel post", upd.getChannelPost().getChatId()), Flag.CHANNEL_POST
|
||||
(bot, upd) -> silent.send("test channel post", upd.getChannelPost().getChatId()), Flag.CHANNEL_POST
|
||||
);
|
||||
}
|
||||
|
||||
public ReplyCollection createReplyCollection() {
|
||||
return ReplyCollection.of(
|
||||
Reply.of(
|
||||
upd -> silent.send("first reply answer", upd.getMessage().getChatId()),
|
||||
update -> update.getMessage().getText().equalsIgnoreCase(FIRST_REPLY_KEY_MESSAGE)
|
||||
),
|
||||
Reply.of(
|
||||
upd -> silent.send("second reply answer", upd.getMessage().getChatId()),
|
||||
update -> update.getMessage().getText().equalsIgnoreCase(SECOND_REPLY_KEY_MESSAGE)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public Ability testAbility() {
|
||||
return getDefaultBuilder().build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -47,7 +47,7 @@ class ExtensionTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int creatorId() {
|
||||
public long creatorId() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
@ -158,24 +158,24 @@ public class ReplyFlowTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int creatorId() {
|
||||
public long creatorId() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public ReplyFlow directionFlow() {
|
||||
Reply saidLeft = Reply.of(upd -> silent.send("Sir, I have gone left.", getChatId(upd)),
|
||||
Reply saidLeft = Reply.of((bot, 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)))
|
||||
.action((bot, 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)),
|
||||
Reply saidRight = Reply.of((bot, 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)))
|
||||
.action((bot, upd) -> silent.send("Command me to go left or right!", getChatId(upd)))
|
||||
.onlyIf(hasMessageWith("wake up"))
|
||||
.next(leftflow)
|
||||
.next(saidRight)
|
||||
@ -184,10 +184,10 @@ public class ReplyFlowTest {
|
||||
|
||||
public Reply errantReply() {
|
||||
return Reply.of(
|
||||
upd -> {
|
||||
(bot, upd) -> {
|
||||
throw new RuntimeException("Throwing an exception inside the update consumer");
|
||||
},
|
||||
upd -> {
|
||||
(upd) -> {
|
||||
throw new RuntimeException("Throwing an exception inside the reply conditions (flags)");
|
||||
});
|
||||
}
|
||||
@ -195,7 +195,7 @@ public class ReplyFlowTest {
|
||||
public Ability replyFlowsWithAbility() {
|
||||
Reply replyWithVk = ReplyFlow.builder(db, 2)
|
||||
.enableStats("SECOND")
|
||||
.action(upd -> {
|
||||
.action((bot, upd) -> {
|
||||
silent.send("Second reply", upd.getMessage().getChatId());
|
||||
})
|
||||
.onlyIf(hasMessageWith("two"))
|
||||
@ -203,7 +203,7 @@ public class ReplyFlowTest {
|
||||
|
||||
Reply replyWithNickname = ReplyFlow.builder(db, 1)
|
||||
.enableStats("FIRST")
|
||||
.action(upd -> {
|
||||
.action((bot, upd) -> {
|
||||
silent.send("First reply", upd.getMessage().getChatId());
|
||||
})
|
||||
.onlyIf(hasMessageWith("one"))
|
||||
|
@ -11,8 +11,8 @@ 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, false, false, false);
|
||||
public static final User CREATOR = new User(1337, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false);
|
||||
public static final User USER = new User(1L, "first", false, "last", "username", null, false, false, false);
|
||||
public static final User CREATOR = new User(1337L, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false);
|
||||
|
||||
private TestUtils() {
|
||||
|
||||
|
@ -12,7 +12,6 @@ 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;
|
||||
@ -59,22 +58,22 @@ class MapDBContextTest {
|
||||
|
||||
@Test
|
||||
void canRecoverDB() {
|
||||
Map<Integer, User> users = db.getMap(USERS);
|
||||
Map<String, Integer> userIds = db.getMap(USER_ID);
|
||||
Map<Long, User> users = db.getMap(USERS);
|
||||
Map<String, Long> userIds = db.getMap(USER_ID);
|
||||
users.put(CREATOR.getId(), CREATOR);
|
||||
users.put(USER.getId(), USER);
|
||||
userIds.put(CREATOR.getUserName(), CREATOR.getId());
|
||||
userIds.put(USER.getUserName(), USER.getId());
|
||||
|
||||
db.getSet("AYRE").add(123123);
|
||||
Map<Integer, User> originalUsers = newHashMap(users);
|
||||
Map<Long, User> originalUsers = newHashMap(users);
|
||||
String beforeBackupInfo = db.info(USERS);
|
||||
|
||||
Object jsonBackup = db.backup();
|
||||
db.clear();
|
||||
boolean recovered = db.recover(jsonBackup);
|
||||
|
||||
Map<Integer, User> recoveredUsers = db.getMap(USERS);
|
||||
Map<Long, User> recoveredUsers = db.getMap(USERS);
|
||||
String afterRecoveryInfo = db.info(USERS);
|
||||
|
||||
assertTrue(recovered, "Could not recover database successfully");
|
||||
|
@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>telegrambots-chat-session-bot</artifactId>
|
||||
@ -84,7 +84,7 @@
|
||||
<dependency>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>telegrambots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
|
||||
|
@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>telegrambotsextensions</artifactId>
|
||||
@ -75,7 +75,7 @@
|
||||
<dependency>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>telegrambots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>telegrambots-meta</artifactId>
|
||||
|
@ -1,9 +1,11 @@
|
||||
package org.telegram.telegrambots.meta;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||
import org.telegram.telegrambots.meta.generics.BotSession;
|
||||
import org.telegram.telegrambots.meta.generics.LongPollingBot;
|
||||
import org.telegram.telegrambots.meta.generics.TelegramBot;
|
||||
import org.telegram.telegrambots.meta.generics.Webhook;
|
||||
import org.telegram.telegrambots.meta.generics.WebhookBot;
|
||||
|
||||
@ -15,8 +17,6 @@ import java.lang.reflect.InvocationTargetException;
|
||||
* Bots manager
|
||||
*/
|
||||
public class TelegramBotsApi {
|
||||
private static final String webhookUrlFormat = "{0}callback/";
|
||||
|
||||
Class<? extends BotSession> botSessionClass;
|
||||
private boolean useWebhook; ///< True to enable webhook usage
|
||||
private Webhook webhook; ///< Webhook instance
|
||||
@ -55,6 +55,12 @@ public class TelegramBotsApi {
|
||||
* @param bot the bot to register
|
||||
*/
|
||||
public BotSession registerBot(LongPollingBot bot) throws TelegramApiException {
|
||||
if (bot == null) {
|
||||
throw new TelegramApiException("Parameter bot can not be null");
|
||||
}
|
||||
if (!validateBotUsernameAndToken(bot)) {
|
||||
throw new TelegramApiException("Bot token and username can't be empty");
|
||||
}
|
||||
bot.onRegister();
|
||||
bot.clearWebhook();
|
||||
BotSession session;
|
||||
@ -74,18 +80,33 @@ public class TelegramBotsApi {
|
||||
* Register a bot in the api that will receive updates using webhook method
|
||||
* @param bot Bot to register
|
||||
* @param setWebhook Set webhook request to initialize the bot
|
||||
*
|
||||
* @apiNote The webhook url will be appended with `/callback/bot.getBotPath()` at the end
|
||||
*/
|
||||
public void registerBot(WebhookBot bot, SetWebhook setWebhook) throws TelegramApiException {
|
||||
if (setWebhook == null) {
|
||||
throw new TelegramApiException("Parameter setWebhook can not be null or empty");
|
||||
throw new TelegramApiException("Parameter setWebhook can not be null");
|
||||
}
|
||||
if (useWebhook) {
|
||||
if (webhook == null) {
|
||||
throw new TelegramApiException("This instance doesn't support Webhook bot, use correct constructor");
|
||||
}
|
||||
if (!validateBotUsernameAndToken(bot)) {
|
||||
throw new TelegramApiException("Bot token and username can't be empty");
|
||||
}
|
||||
bot.onRegister();
|
||||
webhook.registerWebhook(bot);
|
||||
bot.setWebhook(setWebhook);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the username and token are presented
|
||||
* @param telegramBot bot to register
|
||||
* @return False if username or token are empty or null, true otherwise
|
||||
*/
|
||||
private boolean validateBotUsernameAndToken(TelegramBot telegramBot) {
|
||||
return !Strings.isNullOrEmpty(telegramBot.getBotToken()) &&
|
||||
!Strings.isNullOrEmpty(telegramBot.getBotUsername());
|
||||
}
|
||||
}
|
||||
|
@ -41,7 +41,7 @@ public class GetUserProfilePhotos extends BotApiMethod<UserProfilePhotos> {
|
||||
|
||||
@JsonProperty(USERID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Unique identifier of the target user
|
||||
private Long userId; ///< Unique identifier of the target user
|
||||
/**
|
||||
* Optional. Sequential number of the first photo to be returned. By default, all photos are returned.
|
||||
*/
|
||||
|
@ -41,7 +41,7 @@ public class SetPassportDataErrors extends BotApiMethod<Boolean> {
|
||||
|
||||
@JsonProperty(USERID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< User identifier
|
||||
private Long userId; ///< User identifier
|
||||
@JsonProperty(ERRORS_FIELD)
|
||||
@NonNull
|
||||
@Singular
|
||||
|
@ -74,7 +74,7 @@ public class GetGameHighScores extends BotApiMethod<ArrayList<GameHighScore>> {
|
||||
private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message
|
||||
@JsonProperty(USER_ID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///<Target user id
|
||||
private Long userId; ///<Target user id
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
|
@ -77,7 +77,7 @@ public class SetGameScore extends BotApiMethod<Serializable> {
|
||||
private Boolean disableEditMessage; ///< Optional Pass True, if the game message should not be automatically edited to include the current scoreboard. Defaults to False
|
||||
@JsonProperty(USER_ID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< User identifier
|
||||
private Long userId; ///< User identifier
|
||||
@JsonProperty(SCORE_FIELD)
|
||||
@NonNull
|
||||
private Integer score; ///< New score, must be positive
|
||||
|
@ -0,0 +1,90 @@
|
||||
package org.telegram.telegrambots.meta.api.methods.groupadministration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
|
||||
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
|
||||
import org.telegram.telegrambots.meta.api.objects.ChatInviteLink;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* Use this method to create an additional invite link for a chat.
|
||||
*
|
||||
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
|
||||
*
|
||||
* The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@RequiredArgsConstructor
|
||||
@Builder
|
||||
public class CreateChatInviteLink extends BotApiMethod<ChatInviteLink> {
|
||||
public static final String PATH = "createChatInviteLink";
|
||||
|
||||
private static final String CHATID_FIELD = "chat_id";
|
||||
private static final String EXPIREDATE_FIELD = "expire_date";
|
||||
private static final String MEMBERLIMIT_FIELD = "member_limit";
|
||||
|
||||
@JsonProperty(CHATID_FIELD)
|
||||
@NonNull
|
||||
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
|
||||
@JsonProperty(EXPIREDATE_FIELD)
|
||||
private Integer expireDate; ///< Optional. Point in time (Unix timestamp) when the link will expire
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
|
||||
*/
|
||||
@JsonProperty(MEMBERLIMIT_FIELD)
|
||||
private Integer memberLimit;
|
||||
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
return PATH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException {
|
||||
try {
|
||||
ApiResponse<ChatInviteLink> result = OBJECT_MAPPER.readValue(answer,
|
||||
new TypeReference<ApiResponse<ChatInviteLink>>(){});
|
||||
if (result.getOk()) {
|
||||
return result.getResult();
|
||||
} else {
|
||||
throw new TelegramApiRequestException("Error creating invite link", result);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new TelegramApiRequestException("Unable to deserialize response", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate() throws TelegramApiValidationException {
|
||||
if (chatId == null || chatId.isEmpty()) {
|
||||
throw new TelegramApiValidationException("ChatId can't be empty", this);
|
||||
}
|
||||
if (memberLimit != null && (memberLimit < 1 || memberLimit > 99999)) {
|
||||
throw new TelegramApiValidationException("MemberLimit must be between 1 and 99999", this);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
package org.telegram.telegrambots.meta.api.methods.groupadministration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.google.common.base.Strings;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
|
||||
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
|
||||
import org.telegram.telegrambots.meta.api.objects.ChatInviteLink;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* Use this method to edit a non-primary invite link created by the bot.
|
||||
*
|
||||
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
|
||||
*
|
||||
* Returns the edited invite link as a ChatInviteLink object.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@RequiredArgsConstructor
|
||||
@Builder
|
||||
public class EditChatInviteLink extends BotApiMethod<ChatInviteLink> {
|
||||
public static final String PATH = "createChatInviteLink";
|
||||
|
||||
private static final String CHATID_FIELD = "chat_id";
|
||||
private static final String INVITELINK_FIELD = "invite_link";
|
||||
private static final String EXPIREDATE_FIELD = "expire_date";
|
||||
private static final String MEMBERLIMIT_FIELD = "member_limit";
|
||||
|
||||
@JsonProperty(CHATID_FIELD)
|
||||
@NonNull
|
||||
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
|
||||
@JsonProperty(INVITELINK_FIELD)
|
||||
@NonNull
|
||||
private String inviteLink; ///< The invite link to edit
|
||||
@JsonProperty(EXPIREDATE_FIELD)
|
||||
private Integer expireDate; ///< Optional. Point in time (Unix timestamp) when the link will expire
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
|
||||
*/
|
||||
@JsonProperty(MEMBERLIMIT_FIELD)
|
||||
private Integer memberLimit;
|
||||
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
return PATH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException {
|
||||
try {
|
||||
ApiResponse<ChatInviteLink> result = OBJECT_MAPPER.readValue(answer,
|
||||
new TypeReference<ApiResponse<ChatInviteLink>>(){});
|
||||
if (result.getOk()) {
|
||||
return result.getResult();
|
||||
} else {
|
||||
throw new TelegramApiRequestException("Error creating invite link", result);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new TelegramApiRequestException("Unable to deserialize response", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate() throws TelegramApiValidationException {
|
||||
if (Strings.isNullOrEmpty(chatId)) {
|
||||
throw new TelegramApiValidationException("ChatId can't be empty", this);
|
||||
}
|
||||
if (Strings.isNullOrEmpty(inviteLink)) {
|
||||
throw new TelegramApiValidationException("InviteLink can't be empty", this);
|
||||
}
|
||||
if (memberLimit != null && (memberLimit < 1 || memberLimit > 99999)) {
|
||||
throw new TelegramApiValidationException("MemberLimit must be between 1 and 99999", this);
|
||||
}
|
||||
}
|
||||
}
|
@ -20,8 +20,16 @@ import java.io.IOException;
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 3.1
|
||||
* Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the
|
||||
* chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success.
|
||||
* Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked.
|
||||
*
|
||||
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
|
||||
*
|
||||
* Returns the new invite link as String on success.
|
||||
*
|
||||
* @apiNote Each administrator in a chat generates their own invite links.
|
||||
* Bots can't use invite links generated by other administrators.
|
||||
* If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method.
|
||||
* If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@ -37,7 +45,7 @@ public class ExportChatInviteLink extends BotApiMethod<String> {
|
||||
|
||||
@JsonProperty(CHATID_FIELD)
|
||||
@NonNull
|
||||
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
|
||||
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
|
@ -42,7 +42,7 @@ public class GetChatMember extends BotApiMethod<ChatMember> {
|
||||
private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels)
|
||||
@JsonProperty(USERID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Unique identifier of the target user
|
||||
private Long userId; ///< Unique identifier of the target user
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
|
@ -47,15 +47,28 @@ public class KickChatMember extends BotApiMethod<Boolean> {
|
||||
private static final String CHATID_FIELD = "chat_id";
|
||||
private static final String USER_ID_FIELD = "user_id";
|
||||
private static final String UNTILDATE_FIELD = "until_date";
|
||||
private static final String REVOKEMESSAGES_FIELD = "revoke_messages";
|
||||
|
||||
@JsonProperty(CHATID_FIELD)
|
||||
@NonNull
|
||||
private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels)
|
||||
@JsonProperty(USER_ID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Required. Unique identifier of the target user
|
||||
private Long userId; ///< Required. Unique identifier of the target user
|
||||
@JsonProperty(UNTILDATE_FIELD)
|
||||
private Integer untilDate; ///< Optional. Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever
|
||||
/**
|
||||
* Optional
|
||||
*
|
||||
* Pass True to delete all messages from the chat for the user that is being removed.
|
||||
*
|
||||
* If False, the user will be able to see messages in the group that were sent before the user was removed.
|
||||
*
|
||||
* Always True for supergroups and channels.
|
||||
*/
|
||||
@JsonProperty(REVOKEMESSAGES_FIELD)
|
||||
private Boolean revokeMessages;
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
public void setUntilDateInstant(Instant instant) {
|
||||
|
@ -48,13 +48,15 @@ public class PromoteChatMember extends BotApiMethod<Boolean> {
|
||||
private static final String CANPINMESSAGES_FIELD = "can_pin_messages";
|
||||
private static final String CANPROMOTEMEMBERS_FIELD = "can_promote_members";
|
||||
private static final String ISANONYMOUS_FIELD = "is_anonymous";
|
||||
private static final String CANMANAGECHAT_FIELD = "can_manage_chat";
|
||||
private static final String CANMANAGEVOICECHATS_FIELD = "can_manage_voice_chats";
|
||||
|
||||
@JsonProperty(CHATID_FIELD)
|
||||
@NonNull
|
||||
private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels)
|
||||
@JsonProperty(USER_ID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Required. Unique identifier of the target user
|
||||
private Long userId; ///< Required. Unique identifier of the target user
|
||||
@JsonProperty(CANCHANGEINFORMATION_FIELD)
|
||||
private Boolean canChangeInformation; ///< Optional. Pass True, if the administrator can change chat title, photo and other settings
|
||||
@JsonProperty(CANPOSTMESSAGES_FIELD)
|
||||
@ -73,6 +75,23 @@ public class PromoteChatMember extends BotApiMethod<Boolean> {
|
||||
private Boolean canPromoteMembers; ///< Optional. Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administators that were appointed by the him)
|
||||
@JsonProperty(ISANONYMOUS_FIELD)
|
||||
private Boolean isAnonymous; ///< Optional. Pass True, if the administrator's presence in the chat is hidden
|
||||
/**
|
||||
* Optional
|
||||
*
|
||||
* Pass True, if the administrator can access the chat event log, chat statistics, message statistics in channels,
|
||||
* see channel members, see anonymous administrators in supergoups and ignore slow mode.
|
||||
*
|
||||
* Implied by any other administrator privilege
|
||||
*/
|
||||
@JsonProperty(CANMANAGECHAT_FIELD)
|
||||
private Boolean canManageChat;
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Pass True, if the administrator can manage voice chats, supergroups only
|
||||
*/
|
||||
@JsonProperty(CANMANAGEVOICECHATS_FIELD)
|
||||
private Boolean canManageVoiceChats;
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
|
@ -57,7 +57,7 @@ public class RestrictChatMember extends BotApiMethod<Boolean> {
|
||||
private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels)
|
||||
@JsonProperty(USER_ID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Required. Unique identifier of the target user
|
||||
private Long userId; ///< Required. Unique identifier of the target user
|
||||
/**
|
||||
* Optional
|
||||
* Date when restrictions will be lifted for the user, unix time.
|
||||
|
@ -0,0 +1,83 @@
|
||||
package org.telegram.telegrambots.meta.api.methods.groupadministration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.google.common.base.Strings;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.NonNull;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
|
||||
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
|
||||
import org.telegram.telegrambots.meta.api.objects.ChatInviteLink;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* Use this method to revoke an invite link created by the bot.
|
||||
*
|
||||
* If the primary link is revoked, a new link is automatically generated.
|
||||
*
|
||||
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
|
||||
*
|
||||
* Returns the revoked invite link as ChatInviteLink object.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class RevokeChatInviteLink extends BotApiMethod<ChatInviteLink> {
|
||||
public static final String PATH = "createChatInviteLink";
|
||||
|
||||
private static final String CHATID_FIELD = "chat_id";
|
||||
private static final String INVITELINK_FIELD = "invite_link";
|
||||
|
||||
@JsonProperty(CHATID_FIELD)
|
||||
@NonNull
|
||||
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
|
||||
@JsonProperty(INVITELINK_FIELD)
|
||||
@NonNull
|
||||
private String inviteLink; ///< The invite link to revoke
|
||||
|
||||
@Override
|
||||
public String getMethod() {
|
||||
return PATH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException {
|
||||
try {
|
||||
ApiResponse<ChatInviteLink> result = OBJECT_MAPPER.readValue(answer,
|
||||
new TypeReference<ApiResponse<ChatInviteLink>>(){});
|
||||
if (result.getOk()) {
|
||||
return result.getResult();
|
||||
} else {
|
||||
throw new TelegramApiRequestException("Error creating invite link", result);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new TelegramApiRequestException("Unable to deserialize response", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate() throws TelegramApiValidationException {
|
||||
if (Strings.isNullOrEmpty(chatId)) {
|
||||
throw new TelegramApiValidationException("ChatId can't be empty", this);
|
||||
}
|
||||
if (Strings.isNullOrEmpty(inviteLink)) {
|
||||
throw new TelegramApiValidationException("InviteLink can't be empty", this);
|
||||
}
|
||||
}
|
||||
}
|
@ -42,7 +42,7 @@ public class SetChatAdministratorCustomTitle extends BotApiMethod<Boolean> {
|
||||
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
|
||||
@JsonProperty(USERID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Unique identifier of the target user
|
||||
private Long userId; ///< Unique identifier of the target user
|
||||
@JsonProperty(CUSTOMTITLE_FIELD)
|
||||
@NonNull
|
||||
private String customTitle; ///< New custom title for the administrator; 0-16 characters, emoji are not allowed
|
||||
|
@ -50,7 +50,7 @@ public class UnbanChatMember extends BotApiMethod<Boolean> {
|
||||
private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels)
|
||||
@JsonProperty(USERID_FIELD)
|
||||
@NonNull
|
||||
private Integer userId; ///< Required. Unique identifier of the target user
|
||||
private Long userId; ///< Required. Unique identifier of the target user
|
||||
@JsonProperty(ONLYISBANNED_FIELD)
|
||||
private Boolean onlyIfBanned; ///< Optional. Do nothing if the user is not banned
|
||||
|
||||
|
@ -57,8 +57,6 @@ public class SendAudio extends PartialBotApiMethod<Message> {
|
||||
public static final String CAPTION_ENTITIES_FIELD = "caption_entities";
|
||||
public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply";
|
||||
|
||||
@NonNull
|
||||
private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender
|
||||
@NonNull
|
||||
private String chatId; ///< Unique identifier for the chat to send the message to (or Username fro channels)
|
||||
@NonNull
|
||||
@ -70,6 +68,7 @@ public class SendAudio extends PartialBotApiMethod<Message> {
|
||||
private String title; ///< Optional. Title of sent audio
|
||||
private String caption; ///< Optional. Audio caption (may also be used when resending documents by file_id), 0-200 characters
|
||||
private String parseMode; ///< Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.
|
||||
private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender
|
||||
/**
|
||||
* Optional.
|
||||
* Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
|
@ -37,7 +37,7 @@ import java.util.List;
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class SendDice extends BotApiMethod<Message> {
|
||||
private static final List<String> VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("🎲", "🎯", "🏀", "⚽", "🎰"));
|
||||
private static final List<String> VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("🎲", "🎯", "🏀", "⚽", "🎳", "🎰"));
|
||||
|
||||
public static final String PATH = "sendDice";
|
||||
|
||||
@ -52,13 +52,17 @@ public class SendDice extends BotApiMethod<Message> {
|
||||
@NonNull
|
||||
private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername)
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Emoji on which the dice throw animation is based.
|
||||
* Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, or “🎰”.
|
||||
* Dice can have values 1-6 for “🎲” and “🎯”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”.
|
||||
*
|
||||
* Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.
|
||||
*
|
||||
* Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”.
|
||||
*
|
||||
* Defaults to “🎲”
|
||||
*/
|
||||
@JsonProperty(EMOJI_FIELD)
|
||||
@NonNull
|
||||
private String emoji;
|
||||
@JsonProperty(DISABLENOTIFICATION_FIELD)
|
||||
private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound.
|
||||
|
@ -48,7 +48,7 @@ public class AddStickerToSet extends PartialBotApiMethod<Boolean> {
|
||||
public static final String MASKPOSITION_FIELD = "mask_position";
|
||||
|
||||
@NonNull
|
||||
private Integer userId; ///< User identifier of sticker set owner
|
||||
private Long userId; ///< User identifier of sticker set owner
|
||||
@NonNull
|
||||
private String name; ///< Sticker set name
|
||||
@NonNull
|
||||
|
@ -47,7 +47,7 @@ public class CreateNewStickerSet extends PartialBotApiMethod<Boolean> {
|
||||
public static final String MASKPOSITION_FIELD = "mask_position";
|
||||
|
||||
@NonNull
|
||||
private Integer userId; ///< User identifier of created sticker set owner
|
||||
private Long userId; ///< User identifier of created sticker set owner
|
||||
/**
|
||||
* Name of sticker set, to be used in t.me/addstickers/<name> URLs.
|
||||
* Can contain only english letters, digits and underscores.
|
||||
|
@ -40,7 +40,7 @@ public class SetStickerSetThumb extends BotApiMethod<Boolean> {
|
||||
@NonNull
|
||||
private String name; ///< Sticker set name
|
||||
@NonNull
|
||||
private Integer userId; ///< User identifier of the sticker set owner
|
||||
private Long userId; ///< User identifier of the sticker set owner
|
||||
/**
|
||||
* A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px,
|
||||
* or a TGS animation with the thumbnail up to 32 kilobytes in size;
|
||||
|
@ -38,7 +38,7 @@ public class UploadStickerFile extends PartialBotApiMethod<File> {
|
||||
public static final String PNGSTICKER_FIELD = "png_sticker";
|
||||
|
||||
@NonNull
|
||||
private Integer userId; ///< User identifier of sticker file owner
|
||||
private Long userId; ///< User identifier of sticker file owner
|
||||
/**
|
||||
* Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px,
|
||||
* and either width or height must be exactly 512px. More info on Sending Files »
|
||||
|
@ -50,7 +50,7 @@ public class SetWebhook extends BotApiMethod<Boolean> {
|
||||
|
||||
@JsonProperty(URL_FIELD)
|
||||
@NonNull
|
||||
private String url; ///< Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration
|
||||
private String url; ///< HTTPS url to send updates to. Use an empty string to remove webhook integration
|
||||
@JsonProperty(CERTIFICATE_FIELD)
|
||||
private InputFile certificate; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked
|
||||
/**
|
||||
|
@ -45,6 +45,7 @@ public class Chat implements BotApiObject {
|
||||
private static final String SLOWMODEDELAY_FIELD = "slow_mode_delay";
|
||||
private static final String LINKEDCHATID_FIELD = "linked_chat_id";
|
||||
private static final String LOCATION_FIELD = "location";
|
||||
private static final String MESSAGEAUTODELETETIME_FIELD = "message_auto_delete_time";
|
||||
|
||||
private static final String USERCHATTYPE = "private";
|
||||
private static final String GROUPCHATTYPE = "group";
|
||||
@ -80,14 +81,8 @@ public class Chat implements BotApiObject {
|
||||
private ChatPhoto photo; ///< Optional. Chat photo. Returned only in getChat.
|
||||
@JsonProperty(DESCRIPTION_FIELD)
|
||||
private String description; ///< Optional. Description, for groups, supergroups and channel chats. Returned only in getChat.
|
||||
/**
|
||||
* Optional. Chat invite link, for groups, supergroups and channel chats.
|
||||
* Each administrator in a chat generates their own invite links, so the bot must first generate the link using
|
||||
* exportChatInviteLink.
|
||||
* Each Returned only in getChat.
|
||||
*/
|
||||
@JsonProperty(INVITELINK_FIELD)
|
||||
private String inviteLink;
|
||||
private String inviteLink; ///< Optional. Primary invite link, for groups, supergroups and channel chats. Returned only in getChat.
|
||||
@JsonProperty(PINNEDMESSAGE_FIELD)
|
||||
private Message pinnedMessage; ///< Optional. The most recent pinned message (by sending date). Returned only in getChat.
|
||||
@JsonProperty(STICKERSETNAME_FIELD)
|
||||
@ -119,6 +114,9 @@ public class Chat implements BotApiObject {
|
||||
private Long linkedChatId;
|
||||
@JsonProperty(LOCATION_FIELD)
|
||||
private ChatLocation location; ///< Optional. For supergroups, the location to which the supergroup is connected. Returned only in getChat.
|
||||
@JsonProperty(MESSAGEAUTODELETETIME_FIELD)
|
||||
private Integer messageAutoDeleteTime; ///< Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in getChat.
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
public Boolean isGroupChat() {
|
||||
|
@ -0,0 +1,53 @@
|
||||
package org.telegram.telegrambots.meta.api.objects;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* Represents an invite link for a chat.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatInviteLink implements BotApiObject {
|
||||
private static final String INVITELINK_FIELD = "invite_link";
|
||||
private static final String CREATOR_FIELD = "creator";
|
||||
private static final String ISPRIMARY_FIELD = "is_primary";
|
||||
private static final String ISREVOKED_FIELD = "is_revoked";
|
||||
private static final String EXPIREDATE_FIELD = "expire_date";
|
||||
private static final String MEMBERLIMIT_FIELD = "member_limit";
|
||||
|
||||
/**
|
||||
* The invite link.
|
||||
* If the link was created by another chat administrator, then the second part of the link will be replaced with “…”.
|
||||
*/
|
||||
@JsonProperty(INVITELINK_FIELD)
|
||||
private String inviteLink;
|
||||
@JsonProperty(CREATOR_FIELD)
|
||||
private User creator; ///< Creator of the link
|
||||
@JsonProperty(ISPRIMARY_FIELD)
|
||||
private Boolean isPrimary; ///< True, if the link is primary
|
||||
@JsonProperty(ISREVOKED_FIELD)
|
||||
private Boolean isRevoked; ///< True, if the link is revoked
|
||||
@JsonProperty(EXPIREDATE_FIELD)
|
||||
private Integer expireDate; ///< Optional. Point in time (Unix timestamp) when the link will expire or has been expired
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
|
||||
*/
|
||||
@JsonProperty(MEMBERLIMIT_FIELD)
|
||||
private Integer memberLimit;
|
||||
}
|
@ -43,6 +43,8 @@ public class ChatMember implements BotApiObject {
|
||||
private static final String ISMEMBER_FIELD = "is_member";
|
||||
private static final String CUSTOMTITLE_FIELD = "custom_title";
|
||||
private static final String ISANONYMOUS_FIELD = "is_anonymous";
|
||||
private static final String CANMANAGECHAT_FIELD = "can_manage_chat";
|
||||
private static final String CANMANAGEVOICECHATS_FIELD = "can_manage_voice_chats";
|
||||
|
||||
@JsonProperty(USER_FIELD)
|
||||
private User user; ///< Information about the user
|
||||
@ -84,6 +86,27 @@ public class ChatMember implements BotApiObject {
|
||||
private String customTitle; ///< Optional. Owner and administrators only. Custom title for this user
|
||||
@JsonProperty(ISANONYMOUS_FIELD)
|
||||
private Boolean isAnonymous; ///< Optional. Owner and administrators only. True, if the user's presence in the chat is hidden
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Administrators only.
|
||||
*
|
||||
* True, if the administrator can access the chat event log, chat statistics, message statistics in channels,
|
||||
* see channel members, see anonymous administrators in supergoups and ignore slow mode.
|
||||
*
|
||||
* Implied by any other administrator privilege
|
||||
*/
|
||||
@JsonProperty(CANMANAGECHAT_FIELD)
|
||||
private Boolean canManageChat;
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* Administrators only.
|
||||
*
|
||||
* True, if the administrator can manage voice chats; groups and supergroups only
|
||||
*/
|
||||
@JsonProperty(CANMANAGEVOICECHATS_FIELD)
|
||||
private Boolean canManageVoiceChats;
|
||||
|
||||
public Instant getUntilDateAsInstant() {
|
||||
if (untilDate == null) {
|
||||
|
@ -0,0 +1,44 @@
|
||||
package org.telegram.telegrambots.meta.api.objects;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
* This object represents changes in the status of a chat member.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatMemberUpdated implements BotApiObject {
|
||||
private static final String CHAT_FIELD = "chat";
|
||||
private static final String FROM_FIELD = "from";
|
||||
private static final String DATE_FIELD = "date";
|
||||
private static final String OLDCHATMEMBER_FIELD = "old_chat_member";
|
||||
private static final String NEWCHATMEMBER_FIELD = "new_chat_member";
|
||||
private static final String INVITELINK_FIELD = "invite_link";
|
||||
|
||||
@JsonProperty(CHAT_FIELD)
|
||||
private Chat chat; ///< Chat the user belongs to
|
||||
@JsonProperty(FROM_FIELD)
|
||||
private User from; ///< Performer of the action, which resulted in the change
|
||||
@JsonProperty(DATE_FIELD)
|
||||
private Integer date; ///< Date the change was done in Unix time
|
||||
@JsonProperty(OLDCHATMEMBER_FIELD)
|
||||
private ChatMember oldChatMember; ///< Previous information about the chat member
|
||||
@JsonProperty(NEWCHATMEMBER_FIELD)
|
||||
private ChatMember newChatMember; ///< New information about the chat member
|
||||
@JsonProperty(INVITELINK_FIELD)
|
||||
private ChatInviteLink inviteLink; ///< Optional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only.
|
||||
|
||||
}
|
@ -34,8 +34,15 @@ public class Contact implements BotApiObject {
|
||||
private String firstName; ///< Contact's first name
|
||||
@JsonProperty(LASTNAME_FIELD)
|
||||
private String lastName; ///< Optional. Contact's last name
|
||||
/**
|
||||
* Optional.
|
||||
* Contact's user identifier in Telegram.
|
||||
*
|
||||
* @apiNote This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it.
|
||||
* But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
|
||||
*/
|
||||
@JsonProperty(USERID_FIELD)
|
||||
private Integer userID; ///< Optional. Contact's user identifier in Telegram
|
||||
private Long userId; ///< Optional. Contact's user identifier in Telegram
|
||||
@JsonProperty(VCARD_FIELD)
|
||||
private String vCard; ///< Optional. Additional data about the contact in the form of a vCard
|
||||
}
|
||||
|
@ -25,9 +25,9 @@ public class Dice implements BotApiObject {
|
||||
private static final String EMOJI_FIELD = "emoji";
|
||||
|
||||
/**
|
||||
* Value of the dice:
|
||||
* 1-6 for “🎲” and “🎯” base emoji
|
||||
* 1-5 for “🏀” and “⚽” base emoji
|
||||
* Value of the dice,
|
||||
* 1-6 for “🎲”, “🎯” and “🎳” base emoji,
|
||||
* 1-5 for “🏀” and “⚽” base emoji,
|
||||
* 1-64 for “🎰” base emoji
|
||||
*/
|
||||
@JsonProperty(VALUE_FIELD)
|
||||
|
@ -17,6 +17,9 @@ import org.telegram.telegrambots.meta.api.objects.payments.SuccessfulPayment;
|
||||
import org.telegram.telegrambots.meta.api.objects.polls.Poll;
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
|
||||
import org.telegram.telegrambots.meta.api.objects.stickers.Sticker;
|
||||
import org.telegram.telegrambots.meta.api.objects.voicechat.VoiceChatEnded;
|
||||
import org.telegram.telegrambots.meta.api.objects.voicechat.VoiceChatParticipantsInvited;
|
||||
import org.telegram.telegrambots.meta.api.objects.voicechat.VoiceChatStarted;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@ -84,6 +87,10 @@ public class Message implements BotApiObject {
|
||||
private static final String VIABOT_FIELD = "via_bot";
|
||||
private static final String SENDERCHAT_FIELD = "sender_chat";
|
||||
private static final String PROXIMITYALERTTRIGGERED_FIELD = "proximity_alert_triggered";
|
||||
private static final String MESSAGEAUTODELETETIMERCHANGED_FIELD = "message_auto_delete_timer_changed\t";
|
||||
private static final String VOICECHATSTARTED_FIELD = "voice_chat_started";
|
||||
private static final String VOICECHATENDED_FIELD = "voice_chat_ended";
|
||||
private static final String VOICECHATPARTICIPANTSINVITED_FIELD = "voice_chat_participants_invited";
|
||||
|
||||
@JsonProperty(MESSAGEID_FIELD)
|
||||
private Integer messageId; ///< Integer Unique message identifier
|
||||
@ -251,6 +258,15 @@ public class Message implements BotApiObject {
|
||||
*/
|
||||
@JsonProperty(PROXIMITYALERTTRIGGERED_FIELD)
|
||||
private ProximityAlertTriggered proximityAlertTriggered;
|
||||
@JsonProperty(MESSAGEAUTODELETETIMERCHANGED_FIELD)
|
||||
private MessageAutoDeleteTimerChanged messageAutoDeleteTimerChanged; ///< Optional. Service message: auto-delete timer settings changed in the chat
|
||||
@JsonProperty(VOICECHATSTARTED_FIELD)
|
||||
private VoiceChatStarted voiceChatStarted; ///< Optional. Service message: voice chat started
|
||||
@JsonProperty(VOICECHATENDED_FIELD)
|
||||
private VoiceChatEnded voiceChatEnded; ///< Optional. Service message: voice chat ended
|
||||
@JsonProperty(VOICECHATPARTICIPANTSINVITED_FIELD)
|
||||
private VoiceChatParticipantsInvited voiceChatParticipantsInvited; ///< Optional. Service message: new members invited to a voice chat
|
||||
|
||||
|
||||
public List<MessageEntity> getEntities() {
|
||||
if (entities != null) {
|
||||
@ -413,4 +429,24 @@ public class Message implements BotApiObject {
|
||||
public boolean hasReplyMarkup() {
|
||||
return replyMarkup != null;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
private boolean hasMessageAutoDeleteTimerChanged() {
|
||||
return messageAutoDeleteTimerChanged != null;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
private boolean hasVoiceChatStarted() {
|
||||
return voiceChatStarted != null;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
private boolean hasVoiceChatEnded() {
|
||||
return voiceChatEnded != null;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
private boolean hasVoiceChatParticipantsInvited() {
|
||||
return voiceChatParticipantsInvited != null;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,29 @@
|
||||
package org.telegram.telegrambots.meta.api.objects;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* This object represents a service message about a change in auto-delete timer settings.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MessageAutoDeleteTimerChanged implements BotApiObject {
|
||||
private static final String MESSAGEAUTODELETETIME_FIELD = "message_auto_delete_time";
|
||||
|
||||
@JsonProperty(MESSAGEAUTODELETETIME_FIELD)
|
||||
private Integer messageAutoDeleteTime; ///< New auto-delete time for messages in the chat
|
||||
}
|
@ -42,6 +42,8 @@ public class Update implements BotApiObject {
|
||||
private static final String PRE_CHECKOUT_QUERY_FIELD = "pre_checkout_query";
|
||||
private static final String POLL_FIELD = "poll";
|
||||
private static final String POLLANSWER_FIELD = "poll_answer";
|
||||
private static final String MYCHATMEMBER_FIELD = "my_chat_member";
|
||||
private static final String CHATMEMBER_FIELD = "chat_member";
|
||||
|
||||
@JsonProperty(UPDATEID_FIELD)
|
||||
private Integer updateId;
|
||||
@ -73,6 +75,22 @@ public class Update implements BotApiObject {
|
||||
*/
|
||||
@JsonProperty(POLLANSWER_FIELD)
|
||||
private PollAnswer pollAnswer;
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* The bot's chat member status was updated in a chat.
|
||||
* For private chats, this update is received only when the bot is blocked or unblocked by the user.
|
||||
*/
|
||||
@JsonProperty(MYCHATMEMBER_FIELD)
|
||||
private ChatMemberUpdated myChatMember;
|
||||
/**
|
||||
* Optional.
|
||||
*
|
||||
* A chat member's status was updated in a chat.
|
||||
* The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.
|
||||
*/
|
||||
@JsonProperty(CHATMEMBER_FIELD)
|
||||
private ChatMemberUpdated chatMember;
|
||||
|
||||
public boolean hasMessage() {
|
||||
return message != null;
|
||||
@ -117,4 +135,12 @@ public class Update implements BotApiObject {
|
||||
public boolean hasPollAnswer() {
|
||||
return pollAnswer != null;
|
||||
}
|
||||
|
||||
public boolean hasMyChatMember() {
|
||||
return myChatMember != null;
|
||||
}
|
||||
|
||||
public boolean hasChatMember() {
|
||||
return chatMember != null;
|
||||
}
|
||||
}
|
||||
|
@ -35,9 +35,15 @@ public class User implements BotApiObject {
|
||||
private static final String CANREADALLGROUPMESSAGES_FIELD = "can_read_all_group_messages";
|
||||
private static final String SUPPORTINLINEQUERIES_FIELD = "supports_inline_queries";
|
||||
|
||||
/**
|
||||
* Unique identifier for this user or bot.
|
||||
*
|
||||
* @apiNote This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it.
|
||||
* But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
|
||||
*/
|
||||
@JsonProperty(ID_FIELD)
|
||||
@NonNull
|
||||
private Integer id; ///< Unique identifier for this user or bot
|
||||
private Long id; ///< Unique identifier for this user or bot
|
||||
@JsonProperty(FIRSTNAME_FIELD)
|
||||
@NonNull
|
||||
private String firstName; ///< User‘s or bot’s first name
|
||||
|
@ -9,6 +9,8 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.result.serializati
|
||||
* @author Ruben Bermudez
|
||||
* @version 1.0
|
||||
* This object represents one result of an inline query.
|
||||
*
|
||||
* @apiNote All URLs passed in inline query results will be available to end users and therefore must be assumed to be public.
|
||||
*/
|
||||
@JsonDeserialize(using = InlineQueryResultDeserializer.class)
|
||||
public interface InlineQueryResult extends Validable, BotApiObject {
|
||||
|
@ -0,0 +1,29 @@
|
||||
package org.telegram.telegrambots.meta.api.objects.voicechat;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* This object represents a service message about a voice chat ended in the chat.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class VoiceChatEnded implements BotApiObject {
|
||||
private static final String DURATION_FIELD = "duration";
|
||||
|
||||
@JsonProperty(DURATION_FIELD)
|
||||
private Integer duration; ///< Voice chat duration; in seconds
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package org.telegram.telegrambots.meta.api.objects.voicechat;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
|
||||
import org.telegram.telegrambots.meta.api.objects.User;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* This object represents a service message about new members invited to a voice chat.
|
||||
*
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class VoiceChatParticipantsInvited implements BotApiObject {
|
||||
private static final String USERS_FIELD = "users";
|
||||
|
||||
@JsonProperty(USERS_FIELD)
|
||||
private List<User> users; ///< Optional. New members that were invited to the voice chat
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package org.telegram.telegrambots.meta.api.objects.voicechat;
|
||||
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
|
||||
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 5.1
|
||||
*
|
||||
* This object represents a service message about a voice chat started in the chat.
|
||||
*
|
||||
* Currently holds no information.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
public class VoiceChatStarted implements BotApiObject {
|
||||
}
|
@ -16,7 +16,7 @@ public interface WebhookBot extends TelegramBot {
|
||||
* This method is called when receiving updates via webhook
|
||||
* @param update Update received
|
||||
*/
|
||||
BotApiMethod onWebhookUpdateReceived(Update update);
|
||||
BotApiMethod<?> onWebhookUpdateReceived(Update update);
|
||||
|
||||
/**
|
||||
* Execute setWebhook method to set up the url of the webhook
|
||||
|
@ -1,5 +1,6 @@
|
||||
package org.telegram.telegrambots.meta.test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@ -28,7 +29,9 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@ -63,12 +66,24 @@ class TestDeserialization {
|
||||
"\"message\":{\"message_id\":6,\"from\":{\"id\":1234567,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"en\"},\"chat\":{\"id\":-1556359722345678,\"title\":\"test group\",\"type\":\"supergroup\"},\"date\":1604163105,\"new_chat_members\":[{\"id\":123455678,\"is_bot\":true,\"first_name\":\"Testing\",\"username\":\"TestingBot\"}]}}]}";
|
||||
|
||||
ArrayList<Update> response = new GetUpdates().deserializeResponse(updateText);
|
||||
assertEquals(11, response.size());
|
||||
|
||||
JsonNode realArray = mapper.readTree(updateText).get("result");
|
||||
|
||||
assertUpdates(response, realArray);
|
||||
}
|
||||
|
||||
private void assertUpdates(ArrayList<Update> response, JsonNode realArray) throws JsonProcessingException {
|
||||
Map<Integer, JsonNode> updateMap = new HashMap<>();
|
||||
for (int i = 0; i < realArray.size(); i++) {
|
||||
JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(response.get(i)));
|
||||
JsonNode realUpdate = realArray.get(i);
|
||||
JsonNode update = realArray.get(i);
|
||||
updateMap.put(update.get("update_id").asInt(), update);
|
||||
}
|
||||
|
||||
for (Update update : response) {
|
||||
Integer updateId = update.getUpdateId();
|
||||
JsonNode realUpdate = updateMap.get(updateId);
|
||||
JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(update));
|
||||
assertEquals(realUpdate, handledUpdate);
|
||||
}
|
||||
}
|
||||
@ -84,14 +99,10 @@ class TestDeserialization {
|
||||
"\"message\":{\"message_id\":106,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"Username\",\"language_code\":\"en\"},\"chat\":{\"id\":12345678,\"first_name\":\"FirstName\",\"username\":\"Username\",\"type\":\"private\"},\"date\":1604226480,\"document\":{\"file_name\":\"aaa.txt\",\"mime_type\":\"text/plain\",\"file_id\":\"FILEID\",\"file_unique_id\":\"AgADiQEAAjTe-VQ\",\"file_size\":2}}}]}";
|
||||
|
||||
ArrayList<Update> response = new GetUpdates().deserializeResponse(updateText);
|
||||
assertEquals(6, response.size());
|
||||
|
||||
JsonNode realArray = mapper.readTree(updateText).get("result");
|
||||
|
||||
for (int i = 0; i < realArray.size(); i++) {
|
||||
JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(response.get(i)));
|
||||
JsonNode realUpdate = realArray.get(i);
|
||||
assertEquals(realUpdate, handledUpdate);
|
||||
}
|
||||
assertUpdates(response, realArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -119,14 +130,14 @@ class TestDeserialization {
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282110,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":83,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894322,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282114,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":95,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894323,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282118,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":99,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894324,\n" +
|
||||
"\"message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800}}},{\"update_id\":259894325,\n" +
|
||||
"\"message\":{\"message_id\":10,\"from\":{\"id\":12345678,\"is_bot\":true,\"first_name\":\"Group\",\"username\":\"GroupAnonymousBot\"},\"sender_chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"proximity_alert_triggered\":{\"traveler\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"watcher\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"distance\":0}}},{\"update_id\":259894326,\n" +
|
||||
"\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894327,\n" +
|
||||
"\"message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800}}},{\"update_id\":259894325,\n" +
|
||||
"\"message\":{\"message_id\":10,\"from\":{\"id\":12345678,\"is_bot\":true,\"first_name\":\"Group\",\"username\":\"GroupAnonymousBot\"},\"sender_chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"proximity_alert_triggered\":{\"traveler\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"watcher\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"distance\":0}}},{\"update_id\":259894326,\n" +
|
||||
"\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894327,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282126,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":104,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894328,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282128,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":100,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894329,\n" +
|
||||
"\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282128,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":101,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894330,\n" +
|
||||
"\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282128,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":101,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894330,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282132,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894331,\n" +
|
||||
"\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282132,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894332,\n" +
|
||||
"\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282132,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894332,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282136,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":102,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894333,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282140,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894334,\n" +
|
||||
"\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282144,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":99,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894335,\n" +
|
||||
@ -147,14 +158,134 @@ class TestDeserialization {
|
||||
|
||||
|
||||
ArrayList<Update> response = new GetUpdates().deserializeResponse(updateText);
|
||||
assertEquals(47, response.size());
|
||||
|
||||
JsonNode realArray = mapper.readTree(updateText).get("result");
|
||||
assertUpdates(response, realArray);
|
||||
}
|
||||
|
||||
for (int i = 0; i < realArray.size(); i++) {
|
||||
JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(response.get(i)));
|
||||
JsonNode realUpdate = realArray.get(i);
|
||||
assertEquals(realUpdate, handledUpdate);
|
||||
}
|
||||
@Test
|
||||
void TestListUpdatesVoiceChat() throws Exception {
|
||||
String updateText = "{\n" +
|
||||
" \"ok\": true,\n" +
|
||||
" \"result\": [\n" +
|
||||
" {\n" +
|
||||
" \"update_id\": 259939677,\n" +
|
||||
" \"message\": {\n" +
|
||||
" \"message_id\": 1,\n" +
|
||||
" \"from\": {\n" +
|
||||
" \"id\": 1111111111111111,\n" +
|
||||
" \"is_bot\": false,\n" +
|
||||
" \"first_name\": \"TestUser\",\n" +
|
||||
" \"username\": \"TestUser\"\n" +
|
||||
" },\n" +
|
||||
" \"chat\": {\n" +
|
||||
" \"id\": -552721116,\n" +
|
||||
" \"title\": \"Random test\",\n" +
|
||||
" \"type\": \"group\",\n" +
|
||||
" \"all_members_are_administrators\": false\n" +
|
||||
" },\n" +
|
||||
" \"date\": 1615072605,\n" +
|
||||
" \"group_chat_created\": true\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" {\n" +
|
||||
" \"update_id\": 259939678,\n" +
|
||||
" \"message\": {\n" +
|
||||
" \"message_id\": 2,\n" +
|
||||
" \"from\": {\n" +
|
||||
" \"id\": 1111111111111111,\n" +
|
||||
" \"is_bot\": false,\n" +
|
||||
" \"first_name\": \"TestUser\",\n" +
|
||||
" \"username\": \"TestUser\"\n" +
|
||||
" },\n" +
|
||||
" \"chat\": {\n" +
|
||||
" \"id\": -552721116,\n" +
|
||||
" \"title\": \"Random test\",\n" +
|
||||
" \"type\": \"group\",\n" +
|
||||
" \"all_members_are_administrators\": false\n" +
|
||||
" },\n" +
|
||||
" \"date\": 1615072631,\n" +
|
||||
" \"migrate_to_chat_id\": -1001308316775\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" {\n" +
|
||||
" \"update_id\": 259939679,\n" +
|
||||
" \"message\": {\n" +
|
||||
" \"message_id\": 2,\n" +
|
||||
" \"from\": {\n" +
|
||||
" \"id\": 1111111111111111,\n" +
|
||||
" \"is_bot\": false,\n" +
|
||||
" \"first_name\": \"TestUser\",\n" +
|
||||
" \"username\": \"TestUser\"\n" +
|
||||
" },\n" +
|
||||
" \"chat\": {\n" +
|
||||
" \"id\": -1001308316775,\n" +
|
||||
" \"title\": \"Random test\",\n" +
|
||||
" \"type\": \"supergroup\"\n" +
|
||||
" },\n" +
|
||||
" \"date\": 1615072662,\n" +
|
||||
" \"voice_chat_started\": {}\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" {\n" +
|
||||
" \"update_id\": 259939680,\n" +
|
||||
" \"message\": {\n" +
|
||||
" \"message_id\": 3,\n" +
|
||||
" \"from\": {\n" +
|
||||
" \"id\": 1111111111111111,\n" +
|
||||
" \"is_bot\": false,\n" +
|
||||
" \"first_name\": \"TestUser\",\n" +
|
||||
" \"username\": \"TestUser\"\n" +
|
||||
" },\n" +
|
||||
" \"chat\": {\n" +
|
||||
" \"id\": -1001308316775,\n" +
|
||||
" \"title\": \"Random test\",\n" +
|
||||
" \"type\": \"supergroup\"\n" +
|
||||
" },\n" +
|
||||
" \"date\": 1615072671,\n" +
|
||||
" \"voice_chat_participants_invited\": {\n" +
|
||||
" \"users\": [\n" +
|
||||
" {\n" +
|
||||
" \"id\": 222222222222222,\n" +
|
||||
" \"is_bot\": false,\n" +
|
||||
" \"first_name\": \"Test\",\n" +
|
||||
" \"last_name\": \"User\",\n" +
|
||||
" \"username\": \"TestUser\"\n" +
|
||||
" }\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" {\n" +
|
||||
" \"update_id\": 259939681,\n" +
|
||||
" \"message\": {\n" +
|
||||
" \"message_id\": 4,\n" +
|
||||
" \"from\": {\n" +
|
||||
" \"id\": 1111111111111111,\n" +
|
||||
" \"is_bot\": false,\n" +
|
||||
" \"first_name\": \"TestUser\",\n" +
|
||||
" \"username\": \"TestUser\"\n" +
|
||||
" },\n" +
|
||||
" \"chat\": {\n" +
|
||||
" \"id\": -1001308316775,\n" +
|
||||
" \"title\": \"Random test\",\n" +
|
||||
" \"type\": \"supergroup\"\n" +
|
||||
" },\n" +
|
||||
" \"date\": 1615072919,\n" +
|
||||
" \"voice_chat_ended\": {\n" +
|
||||
" \"duration\": 257\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" ]\n" +
|
||||
"}";
|
||||
|
||||
ArrayList<Update> response = new GetUpdates().deserializeResponse(updateText);
|
||||
assertEquals(5, response.size());
|
||||
|
||||
JsonNode realArray = mapper.readTree(updateText).get("result");
|
||||
assertUpdates(response, realArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -363,7 +494,7 @@ class TestDeserialization {
|
||||
assertNotNull(forwardFrom);
|
||||
assertEquals("ForwardLastname", forwardFrom.getLastName());
|
||||
assertEquals("ForwardFirstname", forwardFrom.getFirstName());
|
||||
assertEquals(Integer.valueOf(222222), forwardFrom.getId());
|
||||
assertEquals(Long.valueOf(222222), forwardFrom.getId());
|
||||
}
|
||||
|
||||
private void assertPrivateChat(Chat chat) {
|
||||
@ -413,7 +544,7 @@ class TestDeserialization {
|
||||
|
||||
private void assertFromUser(User from) {
|
||||
assertNotNull(from);
|
||||
assertEquals((Integer) 1111111, from.getId());
|
||||
assertEquals((Long) 1111111L, from.getId());
|
||||
assertEquals("Test Lastname", from.getLastName());
|
||||
assertEquals("Test Firstname", from.getFirstName());
|
||||
assertEquals("Testusername", from.getUserName());
|
||||
|
@ -30,7 +30,7 @@ class TestSetGameScore {
|
||||
setGameScore.setDisableEditMessage(true);
|
||||
setGameScore.setMessageId(54321);
|
||||
setGameScore.setScore(12);
|
||||
setGameScore.setUserId(98765);
|
||||
setGameScore.setUserId(98765L);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>telegrambots-spring-boot-starter</artifactId>
|
||||
@ -70,7 +70,7 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
|
||||
<telegrambots.version>5.0.1</telegrambots.version>
|
||||
<telegrambots.version>5.1.0</telegrambots.version>
|
||||
<spring-boot.version>2.4.3</spring-boot.version>
|
||||
|
||||
<maven-gpg-plugin.version>1.6</maven-gpg-plugin.version>
|
||||
|
@ -4,9 +4,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.telegram.telegrambots.meta.TelegramBotsApi;
|
||||
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
|
||||
import org.telegram.telegrambots.meta.generics.BotSession;
|
||||
import org.telegram.telegrambots.meta.generics.LongPollingBot;
|
||||
|
||||
@ -56,9 +54,6 @@ public class TelegramBotInitializer implements InitializingBean {
|
||||
|
||||
private void handleAnnotatedMethod(Object bot, Method method, BotSession session) {
|
||||
try {
|
||||
TelegramApiRequestException test = new TelegramApiRequestException("Error getting updates", new ApiResponse());
|
||||
log.error(test.getMessage(), test);
|
||||
|
||||
if (method.getParameterCount() > 1) {
|
||||
log.warn(format("Method %s of Type %s has too many parameters",
|
||||
method.getName(), method.getDeclaringClass().getCanonicalName()));
|
||||
|
@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>Bots</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>telegrambots</artifactId>
|
||||
@ -92,7 +92,7 @@
|
||||
<dependency>
|
||||
<groupId>org.telegram</groupId>
|
||||
<artifactId>telegrambots-meta</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
@ -3,9 +3,9 @@ package org.telegram.telegrambots;
|
||||
/**
|
||||
* @author Ruben Bermudez
|
||||
* @version 1.0
|
||||
* @brief Constants needed for Telegram Bots API
|
||||
* @date 20 of June of 2015
|
||||
* Constants needed for Telegram Bots API
|
||||
*/
|
||||
public class Constants {
|
||||
public static final int SOCKET_TIMEOUT = 75 * 1000;
|
||||
public static final String WEBHOOK_URL_PATH = "callback";
|
||||
}
|
||||
|
@ -23,6 +23,6 @@ public abstract class TelegramWebhookBot extends DefaultAbsSender implements Web
|
||||
|
||||
@Override
|
||||
public void setWebhook(SetWebhook setWebhook) throws TelegramApiException {
|
||||
WebhookUtils.setWebhook(this, setWebhook);
|
||||
WebhookUtils.setWebhook(this, this, setWebhook);
|
||||
}
|
||||
}
|
@ -2,6 +2,7 @@ package org.telegram.telegrambots.updatesreceivers;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.telegram.telegrambots.Constants;
|
||||
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
|
||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
|
||||
@ -22,7 +23,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
* @version 1.0
|
||||
* Rest api to for webhook callback function
|
||||
*/
|
||||
@Path("callback")
|
||||
@Path(Constants.WEBHOOK_URL_PATH)
|
||||
public class RestApi {
|
||||
private static final Logger log = LoggerFactory.getLogger(RestApi.class);
|
||||
|
||||
@ -44,7 +45,7 @@ public class RestApi {
|
||||
public Response updateReceived(@PathParam("botPath") String botPath, Update update) {
|
||||
if (callbacks.containsKey(botPath)) {
|
||||
try {
|
||||
BotApiMethod response = callbacks.get(botPath).onWebhookUpdateReceived(update);
|
||||
BotApiMethod<?> response = callbacks.get(botPath).onWebhookUpdateReceived(update);
|
||||
if (response != null) {
|
||||
response.validate();
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
package org.telegram.telegrambots.util;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
@ -11,6 +12,7 @@ import org.apache.http.util.EntityUtils;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.telegram.telegrambots.Constants;
|
||||
import org.telegram.telegrambots.bots.DefaultAbsSender;
|
||||
import org.telegram.telegrambots.bots.DefaultBotOptions;
|
||||
import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder;
|
||||
@ -20,6 +22,7 @@ import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook;
|
||||
import org.telegram.telegrambots.meta.api.objects.InputFile;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
|
||||
import org.telegram.telegrambots.meta.generics.WebhookBot;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@ -43,7 +46,7 @@ public final class WebhookUtils {
|
||||
* @apiNote Telegram API parameters will be taken only from SetWebhook object
|
||||
* @apiNote Bot options will be fetched from Bot to set up the HTTP connection
|
||||
*/
|
||||
public static void setWebhook(DefaultAbsSender bot, SetWebhook setWebhook) throws TelegramApiException {
|
||||
public static void setWebhook(DefaultAbsSender bot, WebhookBot webhookBot, SetWebhook setWebhook) throws TelegramApiException {
|
||||
setWebhook.validate();
|
||||
|
||||
DefaultBotOptions botOptions = bot.getOptions();
|
||||
@ -61,7 +64,7 @@ public final class WebhookUtils {
|
||||
HttpPost httppost = new HttpPost(requestUrl);
|
||||
httppost.setConfig(requestConfig);
|
||||
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addTextBody(SetWebhook.URL_FIELD, setWebhook.getUrl(), TEXT_PLAIN_CONTENT_TYPE);
|
||||
builder.addTextBody(SetWebhook.URL_FIELD, getBotUrl(setWebhook, webhookBot), TEXT_PLAIN_CONTENT_TYPE);
|
||||
if (setWebhook.getMaxConnections() != null) {
|
||||
builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, setWebhook.getMaxConnections().toString(), TEXT_PLAIN_CONTENT_TYPE);
|
||||
}
|
||||
@ -100,10 +103,10 @@ public final class WebhookUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {{@link #setWebhook(DefaultAbsSender, SetWebhook)}} instead
|
||||
* @deprecated Use {{@link #setWebhook(DefaultAbsSender, WebhookBot, SetWebhook)}} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public static void setWebhook(DefaultAbsSender bot, String url, String publicCertificatePath) throws TelegramApiRequestException {
|
||||
public static void setWebhook(DefaultAbsSender bot, WebhookBot webhookBot, String url, String publicCertificatePath) throws TelegramApiRequestException {
|
||||
DefaultBotOptions botOptions = bot.getOptions();
|
||||
|
||||
try (CloseableHttpClient httpclient = TelegramHttpClientBuilder.build(botOptions)) {
|
||||
@ -120,7 +123,7 @@ public final class WebhookUtils {
|
||||
HttpPost httppost = new HttpPost(requestUrl);
|
||||
httppost.setConfig(requestConfig);
|
||||
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addTextBody(SetWebhook.URL_FIELD, url);
|
||||
builder.addTextBody(SetWebhook.URL_FIELD, getBotUrl(url, webhookBot.getBotPath()));
|
||||
if (botOptions.getMaxWebhookConnections() != null) {
|
||||
builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, botOptions.getMaxWebhookConnections().toString());
|
||||
}
|
||||
@ -162,4 +165,24 @@ public final class WebhookUtils {
|
||||
throw new TelegramApiRequestException("Error removing old webhook", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String getBotUrl(SetWebhook setWebhook, WebhookBot webhookBot) {
|
||||
String externalUrl = setWebhook.getUrl();
|
||||
return getBotUrl(externalUrl, webhookBot.getBotPath());
|
||||
}
|
||||
|
||||
private static String getBotUrl(String externalUrl, String botPath) {
|
||||
if (!externalUrl.endsWith("/")) {
|
||||
externalUrl += "/";
|
||||
}
|
||||
externalUrl += Constants.WEBHOOK_URL_PATH;
|
||||
if (!Strings.isNullOrEmpty(botPath)) {
|
||||
if (!botPath.startsWith("/")) {
|
||||
externalUrl += "/";
|
||||
}
|
||||
externalUrl += botPath;
|
||||
}
|
||||
|
||||
return externalUrl;
|
||||
}
|
||||
}
|
||||
|
@ -155,7 +155,7 @@ public final class BotApiMethodHelperFactory {
|
||||
return GetChatMember
|
||||
.builder()
|
||||
.chatId("12345")
|
||||
.userId(98765)
|
||||
.userId(98765L)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ -178,7 +178,7 @@ public final class BotApiMethodHelperFactory {
|
||||
.builder()
|
||||
.chatId("12345")
|
||||
.messageId(67890)
|
||||
.userId(98765)
|
||||
.userId(98765L)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ -189,7 +189,7 @@ public final class BotApiMethodHelperFactory {
|
||||
public static BotApiMethod<UserProfilePhotos> getGetUserProfilePhotos() {
|
||||
return GetUserProfilePhotos
|
||||
.builder()
|
||||
.userId(98765)
|
||||
.userId(98765L)
|
||||
.limit(10)
|
||||
.offset(3)
|
||||
.build();
|
||||
@ -203,7 +203,7 @@ public final class BotApiMethodHelperFactory {
|
||||
return KickChatMember
|
||||
.builder()
|
||||
.chatId("12345")
|
||||
.userId(98765)
|
||||
.userId(98765L)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ -344,7 +344,7 @@ public final class BotApiMethodHelperFactory {
|
||||
.inlineMessageId("12345")
|
||||
.disableEditMessage(true)
|
||||
.score(12)
|
||||
.userId(98765)
|
||||
.userId(98765L)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ -352,7 +352,7 @@ public final class BotApiMethodHelperFactory {
|
||||
return UnbanChatMember
|
||||
.builder()
|
||||
.chatId("12345")
|
||||
.userId(98765)
|
||||
.userId(98765L)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user