From 88ae4a75169816f6dcd97da9865738bd4c15a29b Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:02:32 +0200 Subject: [PATCH 01/85] Make Chat id a long attribute everywhere --- .../telegrambots/api/methods/send/SendMessage.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java index 722b8f2a..29948c0c 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java @@ -29,7 +29,7 @@ public class SendMessage extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; - private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + private long chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) private String text; ///< Text of the message to be sent private String parseMode; ///< Optional. Send Markdown, if you want Telegram apps to show bold, italic and URL text in your bot's message. private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message @@ -45,11 +45,11 @@ public class SendMessage extends BotApiMethod { super(); } - public String getChatId() { + public long getChatId() { return chatId; } - public SendMessage setChatId(String chatId) { + public SendMessage setChatId(long chatId) { this.chatId = chatId; return this; } @@ -168,7 +168,7 @@ public class SendMessage extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, chatId); + gen.writeStringField(CHATID_FIELD, Long.toHexString(chatId)); gen.writeStringField(TEXT_FIELD, text); if (parseMode != null) { From f775d5c00c4e59bf9b0b7231f89edcee42d44321 Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:07:14 +0200 Subject: [PATCH 02/85] Create and implement basic command --- .../telegrambots/api/commands/Command.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/main/java/org/telegram/telegrambots/api/commands/Command.java diff --git a/src/main/java/org/telegram/telegrambots/api/commands/Command.java b/src/main/java/org/telegram/telegrambots/api/commands/Command.java new file mode 100644 index 00000000..87c14abb --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/commands/Command.java @@ -0,0 +1,75 @@ +package org.telegram.telegrambots.api.commands; + +import org.telegram.telegrambots.bots.AbsSender; + +/** + * Representation of a command, which can be executed + * + * @author tschulz + */ +public abstract class Command extends AbsSender { + + public final static String COMMAND_INIT_CHARACTER = "/"; + public final static String COMMAND_PARAMETER_SEPERATOR = " "; + private final static int COMMAND_MAX_LENGTH = 32; + + private final String commandIdentifier; + private final String description; + private final String botToken; + + /** + * construct a command + * + * @param commandIdentifier the unique identifier of this command (e.g. the command string to enter into chat) + * @param description the description of this command + */ + public Command(String commandIdentifier, String description, String botToken) { + + if (commandIdentifier == null || commandIdentifier.isEmpty()) { + throw new IllegalArgumentException("commandIdentifier for command cannot be null or empty"); + } + + if (commandIdentifier.startsWith(COMMAND_INIT_CHARACTER)) { + commandIdentifier = commandIdentifier.substring(1); + } + + if (commandIdentifier.length() + 1 > COMMAND_MAX_LENGTH) { + throw new IllegalArgumentException("commandIdentifier cannot be longer than " + COMMAND_MAX_LENGTH + " (including " + COMMAND_INIT_CHARACTER + ")"); + } + + this.commandIdentifier = commandIdentifier.toLowerCase(); + this.description = description; + this.botToken = botToken; + } + + /** + * get the identifier of this command + * + * @return the identifier + */ + public final String getCommandIdentifier() { + return commandIdentifier; + } + + /** + * get the description of this command + * + * @return the description as String + */ + public String getDescription() { + return description; + } + + @Override + public String getBotToken() { + return botToken; + } + + /** + * execute the command + * + * @param arguments passed arguments + * @param chatId id of the chat, to be able to send replies + */ + abstract void execute(String[] arguments, long chatId); +} \ No newline at end of file From 5d0f508b5a51c6d8180bd3e850b65a7bb386435c Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:08:16 +0200 Subject: [PATCH 03/85] Create interface for the registry of all comannds of a bot --- .../api/commands/ICommandRegistery.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java diff --git a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java new file mode 100644 index 00000000..55cbe647 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java @@ -0,0 +1,42 @@ +package org.telegram.telegrambots.api.commands; + +import java.util.Map; + +/** + * + */ +public interface ICommandRegistery { + + /** + * register a command + * + * @param command the command to register + * @return whether the command could be registered, was not already registered + */ + boolean register(Command command); + + /** + * register multiple commands + * + * @param commands commands to register + * @return map with results of the command register per command + */ + Map registerAll(Command... commands); + + /** + * deregister a command + * + * @param command the command to deregister + * @return whether the command could be deregistered, was registered + */ + boolean deregister(Command command); + + /** + * deregister multiple commands + * + * @param commands commands to deregister + * @return map with results of the command deregistered per command + */ + Map deregisterAll(Command... commands); + +} \ No newline at end of file From 91191ee63b7e6c7487f03740f3cfee763f1289e6 Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:10:35 +0200 Subject: [PATCH 04/85] Add method to retrieve all registered commands --- .../telegrambots/api/commands/ICommandRegistery.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java index 55cbe647..58da1080 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java @@ -1,5 +1,6 @@ package org.telegram.telegrambots.api.commands; +import java.util.Collection; import java.util.Map; /** @@ -39,4 +40,11 @@ public interface ICommandRegistery { */ Map deregisterAll(Command... commands); + /** + * get a collection of all registered commands + * + * @return a collection of registered commands + */ + Collection getRegisteredCommands(); + } \ No newline at end of file From 2089dfbe239bf8d70f0cffb5357044b4a8589a3a Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:11:38 +0200 Subject: [PATCH 05/85] Implement basic help command, which provides an overview over all registered commands --- .../api/commands/HelpCommand.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java new file mode 100644 index 00000000..39b3d786 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java @@ -0,0 +1,37 @@ +package org.telegram.telegrambots.api.commands; + +import org.telegram.telegrambots.BotLogger; +import org.telegram.telegrambots.TelegramApiException; +import org.telegram.telegrambots.api.methods.send.SendMessage; + +/** + * standard help command, which gets registered by default, to supply a list of all available commands + * + * @author tschulz + */ +public class HelpCommand extends Command { + + private static final String LOGTAG = "HELPCOMMAND"; + private final ICommandRegistery commandRegistry; + + public HelpCommand(ICommandRegistery commandRegistry, String botToken) { + super("help", "Gives an overview over all Commands registered for this bot", botToken); + this.commandRegistry = commandRegistry; + } + + @Override + void execute(String[] arguments, long chatId) { + for (Command registeredCommand : commandRegistry.getRegisteredCommands()) { + SendMessage sendMessage = new SendMessage(); + sendMessage.setChatId(chatId); + sendMessage.enableHtml(true); + sendMessage.setText("" + registeredCommand.getCommandIdentifier() + "\n" + registeredCommand.getDescription()); + + try { + sendMessage(sendMessage); + } catch (TelegramApiException e) { + BotLogger.error("Failed to send HelpMessage", LOGTAG, e); + } + } + } +} From f2da0a65589748bd29d61e7a94674aff4697b5fe Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:12:22 +0200 Subject: [PATCH 06/85] Implement Command Registry --- .../api/commands/CommandRegistry.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java diff --git a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java new file mode 100644 index 00000000..ab9afd6f --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java @@ -0,0 +1,86 @@ +package org.telegram.telegrambots.api.commands; + +import org.telegram.telegrambots.api.objects.Message; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +/** + * @author tschulz + */ +public final class CommandRegistry implements ICommandRegistery { + + private final Map commandRegistryMap = new HashMap<>(); + + public CommandRegistry(String botToken) { + register(new HelpCommand(this, botToken)); + } + + @Override + public final boolean register(Command command) { + if (commandRegistryMap.containsKey(command.getCommandIdentifier())) { + return false; + } + commandRegistryMap.put(command.getCommandIdentifier(), command); + return true; + } + + @Override + public final Map registerAll(Command... commands) { + Map resultMap = new HashMap<>(commands.length); + for (Command command : commands) { + resultMap.put(command, register(command)); + } + return resultMap; + } + + @Override + public final boolean deregister(Command command) { + if (commandRegistryMap.containsKey(command.getCommandIdentifier())) { + commandRegistryMap.remove(command.getCommandIdentifier()); + return true; + } + return false; + } + + @Override + public final Map deregisterAll(Command... commands) { + Map resultMap = new HashMap<>(commands.length); + for (Command command : commands) { + resultMap.put(command, deregister(command)); + } + return resultMap; + } + + @Override + public final Collection getRegisteredCommands() { + return commandRegistryMap.values(); + } + + /** + * executes a command if present and replies the success + * + * @param message input message + * @return true if success or false otherwise + */ + public final boolean executeCommand(Message message) { + if (message.hasText()) { + String text = message.getText(); + if (!text.isEmpty() && text.startsWith(Command.COMMAND_INIT_CHARACTER)) { + String commandMessage = text.substring(1); + String[] commandSplit = commandMessage.split(Command.COMMAND_PARAMETER_SEPERATOR); + + String command = commandSplit[0]; + + if (commandRegistryMap.containsKey(command)) { + String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); + commandRegistryMap.get(command).execute(parameters, message.getChatId()); + return true; + } + } + } + return false; + } +} \ No newline at end of file From 10d39077eb0c994d3c1a2ef594a47fe67a96f40a Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:12:48 +0200 Subject: [PATCH 07/85] add chat command detection to message (properties field) --- .../telegram/telegrambots/api/objects/Message.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Message.java b/src/main/java/org/telegram/telegrambots/api/objects/Message.java index 126cb67f..034fe3ad 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Message.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/Message.java @@ -361,6 +361,17 @@ public class Message implements IBotApiObject { return text != null && !text.isEmpty(); } + public boolean isCommand() { + if (entities != null) { + for (MessageEntity entity : entities) { + if (entity != null && "bot_command".equals(entity.getType())) { + return text != null && !text.isEmpty(); + } + } + } + return false; + } + public boolean hasDocument() { return this.document != null; } From 92aa4e218e46eb83bbfe5e3f978069128eea0a29 Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:13:29 +0200 Subject: [PATCH 08/85] Add java doc --- src/main/java/org/telegram/telegrambots/TelegramBotsApi.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java index 19017ea1..ca8c8ea6 100644 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -123,7 +123,7 @@ public class TelegramBotsApi { /** * Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. - * @param bot + * @param bot the bot to register */ public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { setWebhook(bot.getBotToken()); From f49cb8b62f0f856acace6da90adaa786eebf0a2b Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:14:58 +0200 Subject: [PATCH 09/85] Modify TelegramLongPollingBot to support commands --- .../bots/TelegramLongPollingBot.java | 70 ++++++++++++++++++- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 7afdf9c8..0ebc3092 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -1,11 +1,77 @@ package org.telegram.telegrambots.bots; +import org.telegram.telegrambots.BotLogger; +import org.telegram.telegrambots.TelegramApiException; +import org.telegram.telegrambots.api.commands.Command; +import org.telegram.telegrambots.api.commands.CommandRegistry; +import org.telegram.telegrambots.api.commands.ICommandRegistery; +import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.Update; + +import java.util.Collection; +import java.util.Map; + /** * @author Ruben Bermudez * @version 1.0 * @brief TODO * @date 14 of January of 2016 */ -public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot { +public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistery { -} + public static final String LOGTAG = "TelegramLongPollingBot"; + private final CommandRegistry commandRegistry; + + public TelegramLongPollingBot() { + this.commandRegistry = new CommandRegistry(getBotToken()); + } + + @Override + public final void onUpdateReceived(Update update) { + if (update.hasMessage()) { + Message message = update.getMessage(); + if (message.isCommand()) { + if (!commandRegistry.executeCommand(message)) { + SendMessage sendMessage = new SendMessage(); + sendMessage.setChatId(message.getChatId()); + sendMessage.setText("The command you provided is not registered for this bot"); + try { + sendMessage(sendMessage); + } catch (TelegramApiException e) { + BotLogger.error("Cannot send message", LOGTAG, e); + } + } + return; + } + } + processNonCommandUpdate(update); + } + + @Override + public final boolean register(Command command) { + return commandRegistry.register(command); + } + + @Override + public final Map registerAll(Command... commands) { + return commandRegistry.registerAll(commands); + } + + @Override + public final boolean deregister(Command command) { + return commandRegistry.deregister(command); + } + + @Override + public final Map deregisterAll(Command... commands) { + return commandRegistry.deregisterAll(commands); + } + + @Override + public final Collection getRegisteredCommands() { + return commandRegistry.getRegisteredCommands(); + } + + public abstract void processNonCommandUpdate(Update update); +} \ No newline at end of file From 618fb80333a85c53bbedfddb4c40996f9d0154b4 Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:16:39 +0200 Subject: [PATCH 10/85] fix typo --- .../telegram/telegrambots/api/commands/CommandRegistry.java | 2 +- .../org/telegram/telegrambots/api/commands/HelpCommand.java | 4 ++-- .../{ICommandRegistery.java => ICommandRegistry.java} | 2 +- .../telegram/telegrambots/bots/TelegramLongPollingBot.java | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) rename src/main/java/org/telegram/telegrambots/api/commands/{ICommandRegistery.java => ICommandRegistry.java} (97%) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java index ab9afd6f..3cbb6b83 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java @@ -10,7 +10,7 @@ import java.util.Map; /** * @author tschulz */ -public final class CommandRegistry implements ICommandRegistery { +public final class CommandRegistry implements ICommandRegistry { private final Map commandRegistryMap = new HashMap<>(); diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java index 39b3d786..49f57407 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java @@ -12,9 +12,9 @@ import org.telegram.telegrambots.api.methods.send.SendMessage; public class HelpCommand extends Command { private static final String LOGTAG = "HELPCOMMAND"; - private final ICommandRegistery commandRegistry; + private final ICommandRegistry commandRegistry; - public HelpCommand(ICommandRegistery commandRegistry, String botToken) { + public HelpCommand(ICommandRegistry commandRegistry, String botToken) { super("help", "Gives an overview over all Commands registered for this bot", botToken); this.commandRegistry = commandRegistry; } diff --git a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java similarity index 97% rename from src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java rename to src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java index 58da1080..66db8c8c 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistery.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java @@ -6,7 +6,7 @@ import java.util.Map; /** * */ -public interface ICommandRegistery { +public interface ICommandRegistry { /** * register a command diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 0ebc3092..cd871340 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -4,7 +4,7 @@ import org.telegram.telegrambots.BotLogger; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.commands.Command; import org.telegram.telegrambots.api.commands.CommandRegistry; -import org.telegram.telegrambots.api.commands.ICommandRegistery; +import org.telegram.telegrambots.api.commands.ICommandRegistry; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.Update; @@ -18,7 +18,7 @@ import java.util.Map; * @brief TODO * @date 14 of January of 2016 */ -public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistery { +public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistry { public static final String LOGTAG = "TelegramLongPollingBot"; private final CommandRegistry commandRegistry; From 9958d677e282bcdb8fef1c975cbd3e286bcfdcb8 Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:18:41 +0200 Subject: [PATCH 11/85] add command init character to help command response --- .../org/telegram/telegrambots/api/commands/HelpCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java index 49f57407..29b1ab13 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java @@ -25,7 +25,7 @@ public class HelpCommand extends Command { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(chatId); sendMessage.enableHtml(true); - sendMessage.setText("" + registeredCommand.getCommandIdentifier() + "\n" + registeredCommand.getDescription()); + sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredCommand.getCommandIdentifier() + "\n" + registeredCommand.getDescription()); try { sendMessage(sendMessage); From 5fe18aefa34eee400f0a4bcbb98002b632f04072 Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 11:56:15 +0200 Subject: [PATCH 12/85] rename Command class and fix visibility of execute method --- .../{Command.java => BotCommand.java} | 12 +++--- .../api/commands/CommandRegistry.java | 38 +++++++++---------- .../{HelpCommand.java => HelpBotCommand.java} | 10 ++--- .../api/commands/ICommandRegistry.java | 18 ++++----- .../bots/TelegramLongPollingBot.java | 20 +++++----- 5 files changed, 49 insertions(+), 49 deletions(-) rename src/main/java/org/telegram/telegrambots/api/commands/{Command.java => BotCommand.java} (84%) rename src/main/java/org/telegram/telegrambots/api/commands/{HelpCommand.java => HelpBotCommand.java} (73%) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/Command.java b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java similarity index 84% rename from src/main/java/org/telegram/telegrambots/api/commands/Command.java rename to src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java index 87c14abb..d18c5ae1 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/Command.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java @@ -7,10 +7,10 @@ import org.telegram.telegrambots.bots.AbsSender; * * @author tschulz */ -public abstract class Command extends AbsSender { +public abstract class BotCommand extends AbsSender { public final static String COMMAND_INIT_CHARACTER = "/"; - public final static String COMMAND_PARAMETER_SEPERATOR = " "; + public final static String COMMAND_PARAMETER_SEPARATOR = " "; private final static int COMMAND_MAX_LENGTH = 32; private final String commandIdentifier; @@ -23,7 +23,7 @@ public abstract class Command extends AbsSender { * @param commandIdentifier the unique identifier of this command (e.g. the command string to enter into chat) * @param description the description of this command */ - public Command(String commandIdentifier, String description, String botToken) { + public BotCommand(String commandIdentifier, String description, String botToken) { if (commandIdentifier == null || commandIdentifier.isEmpty()) { throw new IllegalArgumentException("commandIdentifier for command cannot be null or empty"); @@ -56,12 +56,12 @@ public abstract class Command extends AbsSender { * * @return the description as String */ - public String getDescription() { + public final String getDescription() { return description; } @Override - public String getBotToken() { + public final String getBotToken() { return botToken; } @@ -71,5 +71,5 @@ public abstract class Command extends AbsSender { * @param arguments passed arguments * @param chatId id of the chat, to be able to send replies */ - abstract void execute(String[] arguments, long chatId); + public abstract void execute(String[] arguments, long chatId); } \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java index 3cbb6b83..313c06fe 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java @@ -12,50 +12,50 @@ import java.util.Map; */ public final class CommandRegistry implements ICommandRegistry { - private final Map commandRegistryMap = new HashMap<>(); + private final Map commandRegistryMap = new HashMap<>(); public CommandRegistry(String botToken) { - register(new HelpCommand(this, botToken)); + register(new HelpBotCommand(this, botToken)); } @Override - public final boolean register(Command command) { - if (commandRegistryMap.containsKey(command.getCommandIdentifier())) { + public final boolean register(BotCommand botCommand) { + if (commandRegistryMap.containsKey(botCommand.getCommandIdentifier())) { return false; } - commandRegistryMap.put(command.getCommandIdentifier(), command); + commandRegistryMap.put(botCommand.getCommandIdentifier(), botCommand); return true; } @Override - public final Map registerAll(Command... commands) { - Map resultMap = new HashMap<>(commands.length); - for (Command command : commands) { - resultMap.put(command, register(command)); + public final Map registerAll(BotCommand... botCommands) { + Map resultMap = new HashMap<>(botCommands.length); + for (BotCommand botCommand : botCommands) { + resultMap.put(botCommand, register(botCommand)); } return resultMap; } @Override - public final boolean deregister(Command command) { - if (commandRegistryMap.containsKey(command.getCommandIdentifier())) { - commandRegistryMap.remove(command.getCommandIdentifier()); + public final boolean deregister(BotCommand botCommand) { + if (commandRegistryMap.containsKey(botCommand.getCommandIdentifier())) { + commandRegistryMap.remove(botCommand.getCommandIdentifier()); return true; } return false; } @Override - public final Map deregisterAll(Command... commands) { - Map resultMap = new HashMap<>(commands.length); - for (Command command : commands) { - resultMap.put(command, deregister(command)); + public final Map deregisterAll(BotCommand... botCommands) { + Map resultMap = new HashMap<>(botCommands.length); + for (BotCommand botCommand : botCommands) { + resultMap.put(botCommand, deregister(botCommand)); } return resultMap; } @Override - public final Collection getRegisteredCommands() { + public final Collection getRegisteredCommands() { return commandRegistryMap.values(); } @@ -68,9 +68,9 @@ public final class CommandRegistry implements ICommandRegistry { public final boolean executeCommand(Message message) { if (message.hasText()) { String text = message.getText(); - if (!text.isEmpty() && text.startsWith(Command.COMMAND_INIT_CHARACTER)) { + if (!text.isEmpty() && text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { String commandMessage = text.substring(1); - String[] commandSplit = commandMessage.split(Command.COMMAND_PARAMETER_SEPERATOR); + String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR); String command = commandSplit[0]; diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java similarity index 73% rename from src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java rename to src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java index 29b1ab13..80e61af2 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java @@ -9,23 +9,23 @@ import org.telegram.telegrambots.api.methods.send.SendMessage; * * @author tschulz */ -public class HelpCommand extends Command { +public class HelpBotCommand extends BotCommand { private static final String LOGTAG = "HELPCOMMAND"; private final ICommandRegistry commandRegistry; - public HelpCommand(ICommandRegistry commandRegistry, String botToken) { + public HelpBotCommand(ICommandRegistry commandRegistry, String botToken) { super("help", "Gives an overview over all Commands registered for this bot", botToken); this.commandRegistry = commandRegistry; } @Override - void execute(String[] arguments, long chatId) { - for (Command registeredCommand : commandRegistry.getRegisteredCommands()) { + public void execute(String[] arguments, long chatId) { + for (BotCommand registeredBotCommand : commandRegistry.getRegisteredCommands()) { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(chatId); sendMessage.enableHtml(true); - sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredCommand.getCommandIdentifier() + "\n" + registeredCommand.getDescription()); + sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredBotCommand.getCommandIdentifier() + "\n" + registeredBotCommand.getDescription()); try { sendMessage(sendMessage); diff --git a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java index 66db8c8c..06db1d88 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java @@ -11,40 +11,40 @@ public interface ICommandRegistry { /** * register a command * - * @param command the command to register + * @param botCommand the command to register * @return whether the command could be registered, was not already registered */ - boolean register(Command command); + boolean register(BotCommand botCommand); /** * register multiple commands * - * @param commands commands to register + * @param botCommands commands to register * @return map with results of the command register per command */ - Map registerAll(Command... commands); + Map registerAll(BotCommand... botCommands); /** * deregister a command * - * @param command the command to deregister + * @param botCommand the command to deregister * @return whether the command could be deregistered, was registered */ - boolean deregister(Command command); + boolean deregister(BotCommand botCommand); /** * deregister multiple commands * - * @param commands commands to deregister + * @param botCommands commands to deregister * @return map with results of the command deregistered per command */ - Map deregisterAll(Command... commands); + Map deregisterAll(BotCommand... botCommands); /** * get a collection of all registered commands * * @return a collection of registered commands */ - Collection getRegisteredCommands(); + Collection getRegisteredCommands(); } \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index cd871340..d0750dc4 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -2,7 +2,7 @@ package org.telegram.telegrambots.bots; import org.telegram.telegrambots.BotLogger; import org.telegram.telegrambots.TelegramApiException; -import org.telegram.telegrambots.api.commands.Command; +import org.telegram.telegrambots.api.commands.BotCommand; import org.telegram.telegrambots.api.commands.CommandRegistry; import org.telegram.telegrambots.api.commands.ICommandRegistry; import org.telegram.telegrambots.api.methods.send.SendMessage; @@ -49,27 +49,27 @@ public abstract class TelegramLongPollingBot extends AbsSender implements ITeleg } @Override - public final boolean register(Command command) { - return commandRegistry.register(command); + public final boolean register(BotCommand botCommand) { + return commandRegistry.register(botCommand); } @Override - public final Map registerAll(Command... commands) { - return commandRegistry.registerAll(commands); + public final Map registerAll(BotCommand... botCommands) { + return commandRegistry.registerAll(botCommands); } @Override - public final boolean deregister(Command command) { - return commandRegistry.deregister(command); + public final boolean deregister(BotCommand botCommand) { + return commandRegistry.deregister(botCommand); } @Override - public final Map deregisterAll(Command... commands) { - return commandRegistry.deregisterAll(commands); + public final Map deregisterAll(BotCommand... botCommands) { + return commandRegistry.deregisterAll(botCommands); } @Override - public final Collection getRegisteredCommands() { + public final Collection getRegisteredCommands() { return commandRegistry.getRegisteredCommands(); } From 1bb4d129836cd310964b01db3fa783a28e3d1bcf Mon Sep 17 00:00:00 2001 From: tschulz Date: Fri, 20 May 2016 12:03:00 +0200 Subject: [PATCH 13/85] change chat id to chat object to be able to work with username --- .../org/telegram/telegrambots/api/commands/BotCommand.java | 5 +++-- .../telegram/telegrambots/api/commands/CommandRegistry.java | 2 +- .../telegram/telegrambots/api/commands/HelpBotCommand.java | 6 ++++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java index d18c5ae1..63ad7ee0 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java @@ -1,5 +1,6 @@ package org.telegram.telegrambots.api.commands; +import org.telegram.telegrambots.api.objects.Chat; import org.telegram.telegrambots.bots.AbsSender; /** @@ -69,7 +70,7 @@ public abstract class BotCommand extends AbsSender { * execute the command * * @param arguments passed arguments - * @param chatId id of the chat, to be able to send replies + * @param chat the chat, to be able to send replies */ - public abstract void execute(String[] arguments, long chatId); + public abstract void execute(String[] arguments, Chat chat); } \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java index 313c06fe..eb2a9209 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java @@ -76,7 +76,7 @@ public final class CommandRegistry implements ICommandRegistry { if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); - commandRegistryMap.get(command).execute(parameters, message.getChatId()); + commandRegistryMap.get(command).execute(parameters, message.getChat()); return true; } } diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java index 80e61af2..79be1245 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.commands; import org.telegram.telegrambots.BotLogger; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.api.objects.Chat; /** * standard help command, which gets registered by default, to supply a list of all available commands @@ -20,10 +21,11 @@ public class HelpBotCommand extends BotCommand { } @Override - public void execute(String[] arguments, long chatId) { + public void execute(String[] arguments, Chat chat) { + for (BotCommand registeredBotCommand : commandRegistry.getRegisteredCommands()) { SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chatId); + sendMessage.setChatId(chat.getId()); sendMessage.enableHtml(true); sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredBotCommand.getCommandIdentifier() + "\n" + registeredBotCommand.getDescription()); From 265915daf6811d405f1cf3258e9d59499e618f2f Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Fri, 20 May 2016 18:39:06 +0200 Subject: [PATCH 14/85] bring chatId of SendMessage back to String instead of Long --- .../telegrambots/api/methods/send/SendMessage.java | 8 ++++---- .../telegrambots/bots/TelegramLongPollingBot.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java index 29948c0c..722b8f2a 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java @@ -29,7 +29,7 @@ public class SendMessage extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; - private long chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) private String text; ///< Text of the message to be sent private String parseMode; ///< Optional. Send Markdown, if you want Telegram apps to show bold, italic and URL text in your bot's message. private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message @@ -45,11 +45,11 @@ public class SendMessage extends BotApiMethod { super(); } - public long getChatId() { + public String getChatId() { return chatId; } - public SendMessage setChatId(long chatId) { + public SendMessage setChatId(String chatId) { this.chatId = chatId; return this; } @@ -168,7 +168,7 @@ public class SendMessage extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); - gen.writeStringField(CHATID_FIELD, Long.toHexString(chatId)); + gen.writeStringField(CHATID_FIELD, chatId); gen.writeStringField(TEXT_FIELD, text); if (parseMode != null) { diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index d0750dc4..5fae139c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -34,7 +34,7 @@ public abstract class TelegramLongPollingBot extends AbsSender implements ITeleg if (message.isCommand()) { if (!commandRegistry.executeCommand(message)) { SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(message.getChatId()); + sendMessage.setChatId(message.getChatId().toString()); sendMessage.setText("The command you provided is not registered for this bot"); try { sendMessage(sendMessage); From 2bff35b8b959dec0efb2d2517d926e6f5252edf4 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Fri, 20 May 2016 19:23:44 +0200 Subject: [PATCH 15/85] remove AbsSender Interface from BotCommand and add reference for sending messages --- .../telegrambots/api/commands/BotCommand.java | 24 +++++++++++++------ .../api/commands/HelpBotCommand.java | 6 ++--- .../bots/TelegramLongPollingBot.java | 8 +++++++ 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java index 63ad7ee0..68222543 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java @@ -8,7 +8,7 @@ import org.telegram.telegrambots.bots.AbsSender; * * @author tschulz */ -public abstract class BotCommand extends AbsSender { +public abstract class BotCommand { public final static String COMMAND_INIT_CHARACTER = "/"; public final static String COMMAND_PARAMETER_SEPARATOR = " "; @@ -16,7 +16,7 @@ public abstract class BotCommand extends AbsSender { private final String commandIdentifier; private final String description; - private final String botToken; + private AbsSender absSender; /** * construct a command @@ -24,7 +24,7 @@ public abstract class BotCommand extends AbsSender { * @param commandIdentifier the unique identifier of this command (e.g. the command string to enter into chat) * @param description the description of this command */ - public BotCommand(String commandIdentifier, String description, String botToken) { + public BotCommand(String commandIdentifier, String description) { if (commandIdentifier == null || commandIdentifier.isEmpty()) { throw new IllegalArgumentException("commandIdentifier for command cannot be null or empty"); @@ -40,7 +40,6 @@ public abstract class BotCommand extends AbsSender { this.commandIdentifier = commandIdentifier.toLowerCase(); this.description = description; - this.botToken = botToken; } /** @@ -61,9 +60,20 @@ public abstract class BotCommand extends AbsSender { return description; } - @Override - public final String getBotToken() { - return botToken; + /** + * Setter + * @param absSender set AbsSender + */ + public final void setAbsSender(AbsSender absSender) { + this.absSender = absSender; + } + + /** + * Getter + * @return the absSender + */ + protected final AbsSender getAbsSender() { + return absSender; } /** diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java index 79be1245..798ad588 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java @@ -16,7 +16,7 @@ public class HelpBotCommand extends BotCommand { private final ICommandRegistry commandRegistry; public HelpBotCommand(ICommandRegistry commandRegistry, String botToken) { - super("help", "Gives an overview over all Commands registered for this bot", botToken); + super("help", "Gives an overview over all Commands registered for this bot"); this.commandRegistry = commandRegistry; } @@ -25,12 +25,12 @@ public class HelpBotCommand extends BotCommand { for (BotCommand registeredBotCommand : commandRegistry.getRegisteredCommands()) { SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chat.getId()); + sendMessage.setChatId(chat.getId().toString()); sendMessage.enableHtml(true); sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredBotCommand.getCommandIdentifier() + "\n" + registeredBotCommand.getDescription()); try { - sendMessage(sendMessage); + getAbsSender().sendMessage(sendMessage); } catch (TelegramApiException e) { BotLogger.error("Failed to send HelpMessage", LOGTAG, e); } diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 5fae139c..241259a2 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -50,21 +50,29 @@ public abstract class TelegramLongPollingBot extends AbsSender implements ITeleg @Override public final boolean register(BotCommand botCommand) { + botCommand.setAbsSender(this); return commandRegistry.register(botCommand); } @Override public final Map registerAll(BotCommand... botCommands) { + for (BotCommand botCommand : botCommands) { + botCommand.setAbsSender(this); + } return commandRegistry.registerAll(botCommands); } @Override public final boolean deregister(BotCommand botCommand) { + botCommand.setAbsSender(null); return commandRegistry.deregister(botCommand); } @Override public final Map deregisterAll(BotCommand... botCommands) { + for (BotCommand botCommand : botCommands) { + botCommand.setAbsSender(null); + } return commandRegistry.deregisterAll(botCommands); } From 3dd0b87ca0c5a80f04887f22fd6cda3dbee77ffe Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Sat, 21 May 2016 14:56:08 +0200 Subject: [PATCH 16/85] move command bot functionality to own bot base class, to avoid api change for future releases --- .../bots/TelegramLongPollingBot.java | 78 +-------------- .../bots/TelegramLongPollingCommandBot.java | 95 +++++++++++++++++++ 2 files changed, 97 insertions(+), 76 deletions(-) create mode 100644 src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 241259a2..7afdf9c8 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -1,85 +1,11 @@ package org.telegram.telegrambots.bots; -import org.telegram.telegrambots.BotLogger; -import org.telegram.telegrambots.TelegramApiException; -import org.telegram.telegrambots.api.commands.BotCommand; -import org.telegram.telegrambots.api.commands.CommandRegistry; -import org.telegram.telegrambots.api.commands.ICommandRegistry; -import org.telegram.telegrambots.api.methods.send.SendMessage; -import org.telegram.telegrambots.api.objects.Message; -import org.telegram.telegrambots.api.objects.Update; - -import java.util.Collection; -import java.util.Map; - /** * @author Ruben Bermudez * @version 1.0 * @brief TODO * @date 14 of January of 2016 */ -public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistry { +public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot { - public static final String LOGTAG = "TelegramLongPollingBot"; - private final CommandRegistry commandRegistry; - - public TelegramLongPollingBot() { - this.commandRegistry = new CommandRegistry(getBotToken()); - } - - @Override - public final void onUpdateReceived(Update update) { - if (update.hasMessage()) { - Message message = update.getMessage(); - if (message.isCommand()) { - if (!commandRegistry.executeCommand(message)) { - SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(message.getChatId().toString()); - sendMessage.setText("The command you provided is not registered for this bot"); - try { - sendMessage(sendMessage); - } catch (TelegramApiException e) { - BotLogger.error("Cannot send message", LOGTAG, e); - } - } - return; - } - } - processNonCommandUpdate(update); - } - - @Override - public final boolean register(BotCommand botCommand) { - botCommand.setAbsSender(this); - return commandRegistry.register(botCommand); - } - - @Override - public final Map registerAll(BotCommand... botCommands) { - for (BotCommand botCommand : botCommands) { - botCommand.setAbsSender(this); - } - return commandRegistry.registerAll(botCommands); - } - - @Override - public final boolean deregister(BotCommand botCommand) { - botCommand.setAbsSender(null); - return commandRegistry.deregister(botCommand); - } - - @Override - public final Map deregisterAll(BotCommand... botCommands) { - for (BotCommand botCommand : botCommands) { - botCommand.setAbsSender(null); - } - return commandRegistry.deregisterAll(botCommands); - } - - @Override - public final Collection getRegisteredCommands() { - return commandRegistry.getRegisteredCommands(); - } - - public abstract void processNonCommandUpdate(Update update); -} \ No newline at end of file +} diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java new file mode 100644 index 00000000..f9a6ab8c --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -0,0 +1,95 @@ +package org.telegram.telegrambots.bots; + +import org.telegram.telegrambots.BotLogger; +import org.telegram.telegrambots.TelegramApiException; +import org.telegram.telegrambots.api.commands.BotCommand; +import org.telegram.telegrambots.api.commands.CommandRegistry; +import org.telegram.telegrambots.api.commands.ICommandRegistry; +import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.api.objects.Update; + +import java.util.Collection; +import java.util.Map; + +/** + * This class adds command functionality to the TelegramLongPollingBot + * + * @author tschulz + */ +public abstract class TelegramLongPollingCommandBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistry{ + + public static final String LOGTAG = "TelegramLongPollingCommandBot"; + private final CommandRegistry commandRegistry; + + /** + * construct creates CommandRegistry for this bot. + * Use ICommandRegistry's methods on this bot to register commands + */ + public TelegramLongPollingCommandBot() { + this.commandRegistry = new CommandRegistry(getBotToken()); + } + + @Override + public final void onUpdateReceived(Update update) { + if (update.hasMessage()) { + Message message = update.getMessage(); + if (message.isCommand()) { + if (!commandRegistry.executeCommand(message)) { + SendMessage sendMessage = new SendMessage(); + sendMessage.setChatId(message.getChatId().toString()); + sendMessage.setText("The command you provided is not registered for this bot"); + try { + sendMessage(sendMessage); + } catch (TelegramApiException e) { + BotLogger.error("Cannot send message", LOGTAG, e); + } + } + return; + } + } + processNonCommandUpdate(update); + } + + @Override + public final boolean register(BotCommand botCommand) { + botCommand.setAbsSender(this); + return commandRegistry.register(botCommand); + } + + @Override + public final Map registerAll(BotCommand... botCommands) { + for (BotCommand botCommand : botCommands) { + botCommand.setAbsSender(this); + } + return commandRegistry.registerAll(botCommands); + } + + @Override + public final boolean deregister(BotCommand botCommand) { + botCommand.setAbsSender(null); + return commandRegistry.deregister(botCommand); + } + + @Override + public final Map deregisterAll(BotCommand... botCommands) { + for (BotCommand botCommand : botCommands) { + botCommand.setAbsSender(null); + } + return commandRegistry.deregisterAll(botCommands); + } + + @Override + public final Collection getRegisteredCommands() { + return commandRegistry.getRegisteredCommands(); + } + + /** + * Process all updates, that are not commands. + * Attention: commands, that have valid syntax but are not registered on this bot, + * won't be forwarded to this method! + * + * @param update the update + */ + public abstract void processNonCommandUpdate(Update update); +} From e51d6eaa4b08bb8f8031402c6ead729a672a5217 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Sat, 21 May 2016 15:00:40 +0200 Subject: [PATCH 17/85] fix missing blank ;) --- .../telegrambots/bots/TelegramLongPollingCommandBot.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index f9a6ab8c..9f7fbc5f 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -17,7 +17,7 @@ import java.util.Map; * * @author tschulz */ -public abstract class TelegramLongPollingCommandBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistry{ +public abstract class TelegramLongPollingCommandBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistry { public static final String LOGTAG = "TelegramLongPollingCommandBot"; private final CommandRegistry commandRegistry; From f33b9fa10efc0317be460a02f7ccaacfe4399362 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Sun, 22 May 2016 14:10:57 +0200 Subject: [PATCH 18/85] remove AbsSender field for command and instead reach it in on each execute call -> so one command could be reached to multiple bot in parallel --- .../telegrambots/api/commands/BotCommand.java | 22 +++---------------- .../api/commands/CommandRegistry.java | 5 +++-- .../api/commands/HelpBotCommand.java | 5 +++-- .../bots/TelegramLongPollingCommandBot.java | 10 +-------- 4 files changed, 10 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java index 68222543..b22bfde6 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java @@ -16,7 +16,6 @@ public abstract class BotCommand { private final String commandIdentifier; private final String description; - private AbsSender absSender; /** * construct a command @@ -60,27 +59,12 @@ public abstract class BotCommand { return description; } - /** - * Setter - * @param absSender set AbsSender - */ - public final void setAbsSender(AbsSender absSender) { - this.absSender = absSender; - } - - /** - * Getter - * @return the absSender - */ - protected final AbsSender getAbsSender() { - return absSender; - } - /** * execute the command * - * @param arguments passed arguments + * @param absSender absSender to send messages over * @param chat the chat, to be able to send replies + * @param arguments passed arguments */ - public abstract void execute(String[] arguments, Chat chat); + public abstract void execute(AbsSender absSender, Chat chat, String[] arguments); } \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java index eb2a9209..8e176508 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.api.commands; import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.bots.AbsSender; import java.util.Arrays; import java.util.Collection; @@ -65,7 +66,7 @@ public final class CommandRegistry implements ICommandRegistry { * @param message input message * @return true if success or false otherwise */ - public final boolean executeCommand(Message message) { + public final boolean executeCommand(AbsSender absSender, Message message) { if (message.hasText()) { String text = message.getText(); if (!text.isEmpty() && text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { @@ -76,7 +77,7 @@ public final class CommandRegistry implements ICommandRegistry { if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); - commandRegistryMap.get(command).execute(parameters, message.getChat()); + commandRegistryMap.get(command).execute(absSender, message.getChat(), parameters); return true; } } diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java index 798ad588..a68fc2e1 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.BotLogger; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Chat; +import org.telegram.telegrambots.bots.AbsSender; /** * standard help command, which gets registered by default, to supply a list of all available commands @@ -21,7 +22,7 @@ public class HelpBotCommand extends BotCommand { } @Override - public void execute(String[] arguments, Chat chat) { + public void execute(AbsSender absSender, Chat chat, String[] arguments) { for (BotCommand registeredBotCommand : commandRegistry.getRegisteredCommands()) { SendMessage sendMessage = new SendMessage(); @@ -30,7 +31,7 @@ public class HelpBotCommand extends BotCommand { sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredBotCommand.getCommandIdentifier() + "\n" + registeredBotCommand.getDescription()); try { - getAbsSender().sendMessage(sendMessage); + absSender.sendMessage(sendMessage); } catch (TelegramApiException e) { BotLogger.error("Failed to send HelpMessage", LOGTAG, e); } diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index 9f7fbc5f..a8942fb9 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -35,7 +35,7 @@ public abstract class TelegramLongPollingCommandBot extends AbsSender implements if (update.hasMessage()) { Message message = update.getMessage(); if (message.isCommand()) { - if (!commandRegistry.executeCommand(message)) { + if (!commandRegistry.executeCommand(this, message)) { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(message.getChatId().toString()); sendMessage.setText("The command you provided is not registered for this bot"); @@ -53,29 +53,21 @@ public abstract class TelegramLongPollingCommandBot extends AbsSender implements @Override public final boolean register(BotCommand botCommand) { - botCommand.setAbsSender(this); return commandRegistry.register(botCommand); } @Override public final Map registerAll(BotCommand... botCommands) { - for (BotCommand botCommand : botCommands) { - botCommand.setAbsSender(this); - } return commandRegistry.registerAll(botCommands); } @Override public final boolean deregister(BotCommand botCommand) { - botCommand.setAbsSender(null); return commandRegistry.deregister(botCommand); } @Override public final Map deregisterAll(BotCommand... botCommands) { - for (BotCommand botCommand : botCommands) { - botCommand.setAbsSender(null); - } return commandRegistry.deregisterAll(botCommands); } From e60e50a9c5a87062922131aa18fbc742ef65c2e5 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Sun, 22 May 2016 14:33:35 +0200 Subject: [PATCH 19/85] teach git to ignore .DS_STORE files --- .gitignore | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index e3308905..b8b3cdb3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,28 +8,32 @@ release.properties dependency-reduced-pom.xml buildNumber.properties .mvn/timing.properties + ### Java template *.class -# Mobile Tools for Java (J2ME) +### Mobile Tools for Java (J2ME) .mtj.tmp/ -# Package Files # +### Package Files # *.jar *.war *.ear -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +### virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* -# logs files +### logs files *.log -# Certs +### Certs *.jks *.cer *.pem -# IDE files +### IDE files .idea/ *.iml + +#File System specific files +.DS_STORE \ No newline at end of file From ea339c08e62f23b5c1f4bf1c5d19c5fb16293f1a Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Sun, 22 May 2016 14:37:30 +0200 Subject: [PATCH 20/85] remove .DS_STORE files from tracking --- .DS_Store | Bin 6148 -> 0 bytes src/.DS_Store | Bin 6148 -> 0 bytes src/main/.DS_Store | Bin 6148 -> 0 bytes src/main/java/.DS_Store | Bin 6148 -> 0 bytes 4 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store delete mode 100644 src/.DS_Store delete mode 100644 src/main/.DS_Store delete mode 100644 src/main/java/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 23b437c2154a1e5ee4df5f7e507c1d9fc8ead69b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%}T>S5Z-O8rh18}Ab8oU&_nAF#apa;6bh9VQK^XubfF}rNi9+eIr|v?KZYRs z4nB%EXLi@3R4*Px%1oI3W@l#-=3Cg!FvfVL=a(3>8DkbGVkQs6H-hV^W0El*4hU+q zxZ|}W4`y#(XDpf=|B(UQyDW=Ymz{b2&->SwaZ)V4@=P{2H9ceHXXo&-=Vwo9t*Bp1 z+@u#*-0qQ@Nk8z6U3HVzhkX!5?UC(zbs6-V_To+yCaw&F?x)n_h7A3vUx|95A0OBB z`x??uT1|VY+6~Sjwd#gJUB=RrZJAtHd3>7o@?fxDS}TZBd23h@gL1i85F6{|;n04x ztd-Tx?ft{f@bc>V=JxLX;ptiL0mrgY7Bq~;mytyVF+dCu0~5@EIRve_39gY!BL;|p z-!Xvag8)Tz45k{@(E)>M0RVI0RsuHm5||?lItEjXumZw$Dxgl~rp4eo9sI(?IR;aW zI-POTd~ow+ZaNgMz7FpfDx7ggBaOrWG4Pdvte)C<|L^_W|9?%Q88JW%OcVn=w_Dq- zKuP9q9V-s+S^;_rih^;e#!(6w>MDjS5Zz5d_8DkbGVkQT}H-hV^W0El*4hU*9 zuNSwyR^-9_eJq+B|B(UQyDU3rE|V<$x_@4~CF7)6eB+s^?DWj6mCMiJW6$SL>&>WF zPu!#%SKQ9Ann^$Kj9qh+=BK?MMXjOjdIvJ-HSEQmC`?=#2AwadCx!r1VD3!Mc1<@~;iv_WYFM8{yNQ5_vHs1^V)3vMM~V=sX@!k}X?)d(vfT&Du+RBl=fuG7IUOq^pd z)u_`MH_Zn(U*@Jm;p*$~exbq{cQn#S3=jjO3{2^%jrafV&;9>s63vJKVql^e;Mr=u zT7il2s8fYK}{*-|a D?o?k2 diff --git a/src/main/.DS_Store b/src/main/.DS_Store deleted file mode 100644 index 9d2a42b384b31f1b70c5b2a6473c440e430d708c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%}T>S5ZAzTq%BekIr|v?KZYRs z4nB%EXLi@3R4*Px%1oI3W@l#-=3Cg!FvfVf>lYcb8DkbGVkQT}H-hV^W0El*4hU*9 zuOGL)R^-9_Z7iA`|B(UQyDU3rF6%M(^Zt45mW-1^;gx5mvePrOR&H({AA4c$wAzgN z)x=G@aoO#hsG0Nw&)5|=X@1y;QPdjQu6HDZe#2hcjl#s0VbJ-MTCd5_kNV}P8~Sm* zs^3?We$s5%%au;hgVc%}21hcMo@~kF!ph;(uvZ3yjpBM<6ieH~ycm>9g}m6@C=G}9 zqh+nGZS5Q!w}+Qk*EhF!_YY6cdKWkrjG`@^1GKc|UfEbuq2Fwv?%};EFR2VTp z4E&Y>JRbxoqGK@CsE!U8R0{x@1-BBgv6sLcVbC#{YJ?RKu2TVZDmN_#*XiIFCeAUK zYSihBo92U?FLTqOaP@U~zfj?fI~r*u28e;L3{2^%jrafl&;9?`B$^Qe#K1%`z_WYR zy)u+!?$)v5@U9i0XP_t;mueiPfT6Bph{daT1yl+61sZ^k!Biu7KS5Z-O8rh18}Ab8oU&_nAF#apa;6bh9VQK<8DkbGVkQs6H-hV^W0El*4hU+q zxZ|}W4`y#(XDpf=|B(UQyDW=Xmz{b2&->SwaZ)V4@=P{2H9ceHXXo&-=Vwo9t*Bp1 z+@u#*-0qQ@Nk8z6U3HVzhkX!5?UC(zbs6-V_To+yCaw&F?x)n_h7A3vUx|95A0OBB z`x??uT1|VY+6~Sjwd#gJUB=RrZJAtHd3>7o@?fxDS}TZBd23h@gL1i85F6{|;n04x ztd-Tx?ft{f@bc>V=JxLX;ptiL0mrgY7Bq~;mytyVF+dCu0~5@EIRve_39gY!BL;|p z-!Xvag8)Tz45k{@(E)>M0RVI0RsuHm5||?lItEjXumZw$Dxgl~rp4eo9sI(?IR;aW zI-POTd~ow+ZaNgMz7FpfDx7ggBaOrWG4Pdvte)C<|L^_W|9?%Q88JW%OcVn=w_Dq- zKuP9q9V-s+S^;_rih^;e#!(6w>MDj Date: Wed, 25 May 2016 01:28:08 +0200 Subject: [PATCH 21/85] Create .travis.yml --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..2d5b8253 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,2 @@ +language: java +script: mvn versions:display-dependency-updates clean compile assembly:single From cf78dcfcbe683eeaa677d5efa0ebf6b6f4623256 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Wed, 25 May 2016 01:33:56 +0200 Subject: [PATCH 22/85] Update .travis.yml --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 2d5b8253..06fdcc0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,2 +1,4 @@ language: java +jdk: + - oraclejdk8 script: mvn versions:display-dependency-updates clean compile assembly:single From b8a019436e5be8236975944861ab480278bbe9e6 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Wed, 25 May 2016 02:47:10 +0200 Subject: [PATCH 23/85] Update .travis.yml --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 06fdcc0a..bad9326c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,3 +2,7 @@ language: java jdk: - oraclejdk8 script: mvn versions:display-dependency-updates clean compile assembly:single +notifications: + webhooks: + secure: "jC7dK/x67ONWQoeLZg4HfW0mHhcjDerJjsLLkrbcpltiqAbw2p7XfY8Pk4zHoD72a+5o6WKu5WvYvZ4OdldnjP8Y6ZUbliQ5RG3olg3gFDoe0+sc3geeb4HRYVcdI20O0z4Bup/qO0ZihxPBc0D5IpHmFxlaqlZG0WeST4CicU8PNnBh6aX9/VMrwXhkMb2vfzmjmIhMbx/uK5+93bnk/vR5Uwu00/Yd2cTAAWMaqK1MRdtR0WLbxlUNsprEfCjYiH3n9XZnlKXs6cLC8EOU436Wx7aepiAszW0wWFMe/7nVqOqztrQiKNvL0qXYwlQf0BLechJdt458EopL9QCu687TNDFYvg1yERAmCRiaayYZcX3PbUSMr6H5Q+Odntjs3XKyzfgSqqlkgf/SAND5jny1/1uteVoplZmFXuZFIiK4H8Rl2ezy1/8pnbp+JD3YEfiA2NuRjlou1BZXyMhiqqVXbrJqk/tXF6yZSkDlYJfNsWzRCGfra4B6JjEvUP927chIFm1ii3dgNstXDo1evV46+OQQO4HKvMPdtU2FPvWpPlkTxnmpZRZjB+bjmybluJdWT3E+e1C3wm7YbRe3vporhpfNPlnod6M0G10y9CKzl9Fbcku6X1FtM+IoPO/aqZ8S4/CBZoYEuR/Nk6bcvsYouxtyIl6PSuF9E8YjpJE=" + email: false From 6daf18f007597d096ca1e7532ecb5ef6c836d8b7 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Wed, 25 May 2016 18:08:10 +0200 Subject: [PATCH 24/85] fix BotLogger import --- .../org/telegram/telegrambots/api/commands/HelpBotCommand.java | 2 +- .../telegrambots/bots/TelegramLongPollingCommandBot.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java index a68fc2e1..2c02af26 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java +++ b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java @@ -1,10 +1,10 @@ package org.telegram.telegrambots.api.commands; -import org.telegram.telegrambots.BotLogger; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Chat; import org.telegram.telegrambots.bots.AbsSender; +import org.telegram.telegrambots.logging.BotLogger; /** * standard help command, which gets registered by default, to supply a list of all available commands diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index a8942fb9..e48f95ed 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -1,6 +1,6 @@ package org.telegram.telegrambots.bots; -import org.telegram.telegrambots.BotLogger; + import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.commands.BotCommand; import org.telegram.telegrambots.api.commands.CommandRegistry; @@ -8,6 +8,7 @@ import org.telegram.telegrambots.api.commands.ICommandRegistry; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.logging.BotLogger; import java.util.Collection; import java.util.Map; From 94e4d4397b059cc984bf0e6db3cb44fc1a881d8f Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Wed, 25 May 2016 19:33:15 +0200 Subject: [PATCH 25/85] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5e9c2f73..c0f7e74a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Telegram Bot Java Library +[![Build Status](https://travis-ci.org/rubenlagus/TelegramBots.svg?branch=master)](https://travis-ci.org/rubenlagus/TelegramBots) [![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi) A simple to use library to create Telegram Bots in Java From 66566e3a652a664569b0b4760b41990e1943827d Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Thu, 26 May 2016 09:24:10 +0200 Subject: [PATCH 26/85] make command bot extend TelegramLongPollingBot --- .../telegrambots/bots/TelegramLongPollingCommandBot.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index e48f95ed..17c0b0a8 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -18,7 +18,7 @@ import java.util.Map; * * @author tschulz */ -public abstract class TelegramLongPollingCommandBot extends AbsSender implements ITelegramLongPollingBot, ICommandRegistry { +public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingBot implements ICommandRegistry { public static final String LOGTAG = "TelegramLongPollingCommandBot"; private final CommandRegistry commandRegistry; From ce9d198d5cdf7c49e8bb001150cd610c44423b08 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 27 May 2016 02:04:21 +0200 Subject: [PATCH 27/85] Merges #82 --- .../org/telegram/telegrambots/Constants.java | 1 + .../updatesreceivers/BotSession.java | 57 ++++++++++--------- 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/Constants.java b/src/main/java/org/telegram/telegrambots/Constants.java index 60371d0f..ac241cc3 100644 --- a/src/main/java/org/telegram/telegrambots/Constants.java +++ b/src/main/java/org/telegram/telegrambots/Constants.java @@ -8,6 +8,7 @@ package org.telegram.telegrambots; */ public class Constants { public static final String BASEURL = "https://api.telegram.org/bot"; + public static final int GETUPDATESTIMEOUT = 50; public static final String RESPONSEFIELDOK = "ok"; public static final String RESPONSEFIELDRESULT = "result"; public static final String ERRORDESCRIPTIONFIELD = "description"; diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java index 39b5f1ec..554c69e6 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java @@ -14,12 +14,12 @@ import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.telegram.telegrambots.logging.BotLogger; import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.methods.updates.GetUpdates; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.bots.ITelegramLongPollingBot; +import org.telegram.telegrambots.logging.BotLogger; import java.io.IOException; import java.io.InvalidObjectException; @@ -27,9 +27,6 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.TimeUnit; -import static org.telegram.telegrambots.Constants.ERRORCODEFIELD; -import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; - /** * @author Ruben Bermudez * @version 1.0 @@ -54,49 +51,55 @@ public class BotSession { public BotSession(String token, ITelegramLongPollingBot callback) { this.token = token; this.callback = callback; + httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) .setMaxConnTotal(100) .build(); + requestConfig = RequestConfig.copy(RequestConfig.custom().build()) .setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); - this.readerThread = new ReaderThread(); + + readerThread = new ReaderThread(); readerThread.setName(callback.getBotUsername() + " Telegram Connection"); - this.readerThread.start(); - this.handlerThread = new HandlerThread(); - handlerThread.setName(callback.getBotUsername() + " Executor"); - this.handlerThread.start(); + readerThread.start(); + + handlerThread = new HandlerThread(); + handlerThread.setName(callback.getBotUsername() + " Telegram Executor"); + handlerThread.start(); } - - public void close() - { - running = false; - if(httpclient != null) - { - try - { - httpclient.close(); - httpclient = null; + + public void close() { + running = false; + if (readerThread != null) { + readerThread.interrupt(); + } + if (handlerThread != null) { + handlerThread.interrupt(); + } + if (httpclient != null) { + try { + httpclient.close(); + httpclient = null; } catch (IOException e) { BotLogger.severe(LOGTAG, e); } - } - + } } private class ReaderThread extends Thread { - @Override + @Override public void run() { setPriority(Thread.MIN_PRIORITY); - while(running) { + while (running) { try { GetUpdates request = new GetUpdates(); request.setLimit(100); - request.setTimeout(50); + request.setTimeout(Constants.GETUPDATESTIMEOUT); request.setOffset(lastReceivedUpdate + 1); String url = Constants.BASEURL + token + "/" + GetUpdates.PATH; //http client @@ -111,7 +114,9 @@ public class BotSession { String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); JSONObject jsonObject = new JSONObject(responseContent); if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { - throw new TelegramApiException("Error getting updates", jsonObject.getString(ERRORDESCRIPTIONFIELD), jsonObject.getInt(ERRORCODEFIELD)); + throw new TelegramApiException("Error getting updates", + jsonObject.getString(Constants.ERRORDESCRIPTIONFIELD), + jsonObject.getInt(Constants.ERRORCODEFIELD)); } JSONArray jsonArray = jsonObject.getJSONArray(Constants.RESPONSEFIELDRESULT); if (jsonArray.length() != 0) { @@ -155,7 +160,7 @@ public class BotSession { @Override public void run() { setPriority(Thread.MIN_PRIORITY); - while(running) { + while (running) { try { Update update = receivedUpdates.pollLast(); if (update == null) { From 1100ad11e455ca0d930798da3ebf5d0632a35971 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 27 May 2016 03:19:17 +0200 Subject: [PATCH 28/85] Changes on #83 --- .gitignore | 1 + .../api/commands/HelpBotCommand.java | 40 ------------------- .../telegrambots/api/objects/Message.java | 7 ++-- .../bots/TelegramLongPollingCommandBot.java | 36 +++++++---------- .../{api => bots}/commands/BotCommand.java | 22 ++++++---- .../commands/CommandRegistry.java | 25 +++++++++--- .../commands/ICommandRegistry.java | 23 ++++++++--- 7 files changed, 71 insertions(+), 83 deletions(-) delete mode 100644 src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java rename src/main/java/org/telegram/telegrambots/{api => bots}/commands/BotCommand.java (78%) rename src/main/java/org/telegram/telegrambots/{api => bots}/commands/CommandRegistry.java (75%) rename src/main/java/org/telegram/telegrambots/{api => bots}/commands/ICommandRegistry.java (51%) diff --git a/.gitignore b/.gitignore index b8b3cdb3..f2fa92ab 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,7 @@ hs_err_pid* ### IDE files .idea/ +copyright/ *.iml #File System specific files diff --git a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java b/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java deleted file mode 100644 index 2c02af26..00000000 --- a/src/main/java/org/telegram/telegrambots/api/commands/HelpBotCommand.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.telegram.telegrambots.api.commands; - -import org.telegram.telegrambots.TelegramApiException; -import org.telegram.telegrambots.api.methods.send.SendMessage; -import org.telegram.telegrambots.api.objects.Chat; -import org.telegram.telegrambots.bots.AbsSender; -import org.telegram.telegrambots.logging.BotLogger; - -/** - * standard help command, which gets registered by default, to supply a list of all available commands - * - * @author tschulz - */ -public class HelpBotCommand extends BotCommand { - - private static final String LOGTAG = "HELPCOMMAND"; - private final ICommandRegistry commandRegistry; - - public HelpBotCommand(ICommandRegistry commandRegistry, String botToken) { - super("help", "Gives an overview over all Commands registered for this bot"); - this.commandRegistry = commandRegistry; - } - - @Override - public void execute(AbsSender absSender, Chat chat, String[] arguments) { - - for (BotCommand registeredBotCommand : commandRegistry.getRegisteredCommands()) { - SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chat.getId().toString()); - sendMessage.enableHtml(true); - sendMessage.setText("" + COMMAND_INIT_CHARACTER + registeredBotCommand.getCommandIdentifier() + "\n" + registeredBotCommand.getDescription()); - - try { - absSender.sendMessage(sendMessage); - } catch (TelegramApiException e) { - BotLogger.error("Failed to send HelpMessage", LOGTAG, e); - } - } - } -} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Message.java b/src/main/java/org/telegram/telegrambots/api/objects/Message.java index f32a8c15..f14c2894 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Message.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/Message.java @@ -382,10 +382,11 @@ public class Message implements IBotApiObject { } public boolean isCommand() { - if (entities != null) { + if (hasText() && entities != null) { for (MessageEntity entity : entities) { - if (entity != null && "bot_command".equals(entity.getType())) { - return text != null && !text.isEmpty(); + if (entity != null && entity.getOffset() == 0 && + EntityType.BOTCOMMAND.equals(entity.getType())) { + return true; } } } diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index 17c0b0a8..fba5b986 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -1,17 +1,15 @@ package org.telegram.telegrambots.bots; -import org.telegram.telegrambots.TelegramApiException; -import org.telegram.telegrambots.api.commands.BotCommand; -import org.telegram.telegrambots.api.commands.CommandRegistry; -import org.telegram.telegrambots.api.commands.ICommandRegistry; -import org.telegram.telegrambots.api.methods.send.SendMessage; +import org.telegram.telegrambots.bots.commands.BotCommand; +import org.telegram.telegrambots.bots.commands.CommandRegistry; +import org.telegram.telegrambots.bots.commands.ICommandRegistry; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.Update; -import org.telegram.telegrambots.logging.BotLogger; import java.util.Collection; import java.util.Map; +import java.util.function.BiConsumer; /** * This class adds command functionality to the TelegramLongPollingBot @@ -19,8 +17,6 @@ import java.util.Map; * @author tschulz */ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingBot implements ICommandRegistry { - - public static final String LOGTAG = "TelegramLongPollingCommandBot"; private final CommandRegistry commandRegistry; /** @@ -28,7 +24,8 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * Use ICommandRegistry's methods on this bot to register commands */ public TelegramLongPollingCommandBot() { - this.commandRegistry = new CommandRegistry(getBotToken()); + super(); + this.commandRegistry = new CommandRegistry(); } @Override @@ -36,17 +33,9 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB if (update.hasMessage()) { Message message = update.getMessage(); if (message.isCommand()) { - if (!commandRegistry.executeCommand(this, message)) { - SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(message.getChatId().toString()); - sendMessage.setText("The command you provided is not registered for this bot"); - try { - sendMessage(sendMessage); - } catch (TelegramApiException e) { - BotLogger.error("Cannot send message", LOGTAG, e); - } + if (commandRegistry.executeCommand(this, message)) { + return; } - return; } } processNonCommandUpdate(update); @@ -77,10 +66,15 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB return commandRegistry.getRegisteredCommands(); } + @Override + public void registerDefaultAction(BiConsumer defaultConsumer) { + commandRegistry.registerDefaultAction(defaultConsumer); + } + /** * Process all updates, that are not commands. - * Attention: commands, that have valid syntax but are not registered on this bot, - * won't be forwarded to this method! + * @warning Commands that have valid syntax but are not registered on this bot, + * won't be forwarded to this method if a default action is present. * * @param update the update */ diff --git a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java similarity index 78% rename from src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java rename to src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java index b22bfde6..f46e9a10 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/BotCommand.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java @@ -1,4 +1,4 @@ -package org.telegram.telegrambots.api.commands; +package org.telegram.telegrambots.bots.commands; import org.telegram.telegrambots.api.objects.Chat; import org.telegram.telegrambots.bots.AbsSender; @@ -9,18 +9,18 @@ import org.telegram.telegrambots.bots.AbsSender; * @author tschulz */ public abstract class BotCommand { - public final static String COMMAND_INIT_CHARACTER = "/"; - public final static String COMMAND_PARAMETER_SEPARATOR = " "; + public static final String COMMAND_PARAMETER_SEPARATOR = " "; private final static int COMMAND_MAX_LENGTH = 32; private final String commandIdentifier; private final String description; /** - * construct a command + * Construct a command * - * @param commandIdentifier the unique identifier of this command (e.g. the command string to enter into chat) + * @param commandIdentifier the unique identifier of this command (e.g. the command string to + * enter into chat) * @param description the description of this command */ public BotCommand(String commandIdentifier, String description) { @@ -42,7 +42,7 @@ public abstract class BotCommand { } /** - * get the identifier of this command + * Get the identifier of this command * * @return the identifier */ @@ -51,7 +51,7 @@ public abstract class BotCommand { } /** - * get the description of this command + * Get the description of this command * * @return the description as String */ @@ -59,8 +59,14 @@ public abstract class BotCommand { return description; } + @Override + public String toString() { + return "" + COMMAND_INIT_CHARACTER + getCommandIdentifier() + + "\n" + getDescription(); + } + /** - * execute the command + * Execute the command * * @param absSender absSender to send messages over * @param chat the chat, to be able to send replies diff --git a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java similarity index 75% rename from src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java rename to src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index 8e176508..6d2d3eb7 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -1,4 +1,4 @@ -package org.telegram.telegrambots.api.commands; +package org.telegram.telegrambots.bots.commands; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.bots.AbsSender; @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.function.BiConsumer; /** * @author tschulz @@ -14,9 +15,14 @@ import java.util.Map; public final class CommandRegistry implements ICommandRegistry { private final Map commandRegistryMap = new HashMap<>(); + private BiConsumer defaultConsumer; - public CommandRegistry(String botToken) { - register(new HelpBotCommand(this, botToken)); + public CommandRegistry() { + } + + @Override + public void registerDefaultAction(BiConsumer defaultConsumer) { + this.defaultConsumer = defaultConsumer; } @Override @@ -61,15 +67,19 @@ public final class CommandRegistry implements ICommandRegistry { } /** - * executes a command if present and replies the success + * Executes a command action if the command is registered. * + * @note If the command is not registered and there is a default consumer, + * that action will be performed + * + * @param absSender absSender * @param message input message - * @return true if success or false otherwise + * @return True if a command or default action is executed, false otherwise */ public final boolean executeCommand(AbsSender absSender, Message message) { if (message.hasText()) { String text = message.getText(); - if (!text.isEmpty() && text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { + if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { String commandMessage = text.substring(1); String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR); @@ -79,6 +89,9 @@ public final class CommandRegistry implements ICommandRegistry { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); commandRegistryMap.get(command).execute(absSender, message.getChat(), parameters); return true; + } else if (defaultConsumer != null) { + defaultConsumer.accept(absSender, message); + return true; } } } diff --git a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java similarity index 51% rename from src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java rename to src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java index 06db1d88..676e1f8f 100644 --- a/src/main/java/org/telegram/telegrambots/api/commands/ICommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java @@ -1,18 +1,31 @@ -package org.telegram.telegrambots.api.commands; +package org.telegram.telegrambots.bots.commands; + +import org.telegram.telegrambots.api.objects.Message; +import org.telegram.telegrambots.bots.AbsSender; import java.util.Collection; import java.util.Map; +import java.util.function.BiConsumer; /** * */ public interface ICommandRegistry { + /** + * Register a default action when there is no command register that match the message sent + * @param defaultConsumer Consumer to evaluate the message + * + * @note Use this method if you want your bot to execute a default action when the user + * sends a command that is not registered. + */ + void registerDefaultAction(BiConsumer defaultConsumer); + /** * register a command * * @param botCommand the command to register - * @return whether the command could be registered, was not already registered + * @return whether the command could be registered, was not already registered */ boolean register(BotCommand botCommand); @@ -20,7 +33,7 @@ public interface ICommandRegistry { * register multiple commands * * @param botCommands commands to register - * @return map with results of the command register per command + * @return map with results of the command register per command */ Map registerAll(BotCommand... botCommands); @@ -28,7 +41,7 @@ public interface ICommandRegistry { * deregister a command * * @param botCommand the command to deregister - * @return whether the command could be deregistered, was registered + * @return whether the command could be deregistered, was registered */ boolean deregister(BotCommand botCommand); @@ -36,7 +49,7 @@ public interface ICommandRegistry { * deregister multiple commands * * @param botCommands commands to deregister - * @return map with results of the command deregistered per command + * @return map with results of the command deregistered per command */ Map deregisterAll(BotCommand... botCommands); From b07bf5531b4a8ae9269669896e83bf5f16342368 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 27 May 2016 04:43:13 +0200 Subject: [PATCH 29/85] Clean up, update pom file --- .travis.yml | 2 +- pom.xml | 146 ++++++++---------- .../telegram/telegrambots/bots/AbsSender.java | 44 +++--- 3 files changed, 86 insertions(+), 106 deletions(-) diff --git a/.travis.yml b/.travis.yml index bad9326c..56e8ff9e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: java jdk: - oraclejdk8 -script: mvn versions:display-dependency-updates clean compile assembly:single +script: mvn clean compile package verify notifications: webhooks: secure: "jC7dK/x67ONWQoeLZg4HfW0mHhcjDerJjsLLkrbcpltiqAbw2p7XfY8Pk4zHoD72a+5o6WKu5WvYvZ4OdldnjP8Y6ZUbliQ5RG3olg3gFDoe0+sc3geeb4HRYVcdI20O0z4Bup/qO0ZihxPBc0D5IpHmFxlaqlZG0WeST4CicU8PNnBh6aX9/VMrwXhkMb2vfzmjmIhMbx/uK5+93bnk/vR5Uwu00/Yd2cTAAWMaqK1MRdtR0WLbxlUNsprEfCjYiH3n9XZnlKXs6cLC8EOU436Wx7aepiAszW0wWFMe/7nVqOqztrQiKNvL0qXYwlQf0BLechJdt458EopL9QCu687TNDFYvg1yERAmCRiaayYZcX3PbUSMr6H5Q+Odntjs3XKyzfgSqqlkgf/SAND5jny1/1uteVoplZmFXuZFIiK4H8Rl2ezy1/8pnbp+JD3YEfiA2NuRjlou1BZXyMhiqqVXbrJqk/tXF6yZSkDlYJfNsWzRCGfra4B6JjEvUP927chIFm1ii3dgNstXDo1evV46+OQQO4HKvMPdtU2FPvWpPlkTxnmpZRZjB+bjmybluJdWT3E+e1C3wm7YbRe3vporhpfNPlnod6M0G10y9CKzl9Fbcku6X1FtM+IoPO/aqZ8S4/CBZoYEuR/Nk6bcvsYouxtyIl6PSuF9E8YjpJE=" diff --git a/pom.xml b/pom.xml index 5a65bc3a..fa4f0398 100644 --- a/pom.xml +++ b/pom.xml @@ -26,6 +26,7 @@ 1.19.1 4.5.2 20160212 + 2.7.4 @@ -44,6 +45,7 @@ org.glassfish.jersey.containers jersey-container-grizzly2-http + ${jersey.version} org.glassfish.jersey.media @@ -83,91 +85,69 @@ ${project.artifactId}-${project.version} ${project.build.directory}/test-classes ${project.basedir}/src/main/java + + + maven-clean-plugin + 3.0.0 + + + clean-project + clean + + clean + + + + + + maven-assembly-plugin + 2.6 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.0 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + site + + javadoc-no-fork + + + + + - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - true - lib/ - org.telegram.Main - - - - - - maven-assembly-plugin - - - - org.telegram.Main - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.9 - - - copy-dependencies - package - - copy-dependencies - - - ${project.build.directory}/lib - false - false - true - - - - - - maven-clean-plugin - org.apache.maven.plugins maven-compiler-plugin diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 703bc816..ebefba8c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -104,7 +104,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter sendMessage can not be null"); } - return (Message) sendApiMethod(sendMessage); + return sendApiMethod(sendMessage); } public Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { @@ -112,7 +112,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter answerInlineQuery can not be null"); } - return (Boolean) sendApiMethod(answerInlineQuery); + return sendApiMethod(answerInlineQuery); } public Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { @@ -120,7 +120,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter sendChatAction can not be null"); } - return (Boolean) sendApiMethod(sendChatAction); + return sendApiMethod(sendChatAction); } public Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { @@ -128,7 +128,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter forwardMessage can not be null"); } - return (Message) sendApiMethod(forwardMessage); + return sendApiMethod(forwardMessage); } public Message sendLocation(SendLocation sendLocation) throws TelegramApiException { @@ -136,7 +136,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter sendLocation can not be null"); } - return (Message) sendApiMethod(sendLocation); + return sendApiMethod(sendLocation); } public Message sendVenue(SendVenue sendVenue) throws TelegramApiException { @@ -144,7 +144,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter sendVenue can not be null"); } - return (Message) sendApiMethod(sendVenue); + return sendApiMethod(sendVenue); } public Message sendContact(SendContact sendContact) throws TelegramApiException { @@ -152,84 +152,84 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter sendContact can not be null"); } - return (Message) sendApiMethod(sendContact); + return sendApiMethod(sendContact); } public Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { if (kickChatMember == null) { throw new TelegramApiException("Parameter kickChatMember can not be null"); } - return (Boolean) sendApiMethod(kickChatMember); + return sendApiMethod(kickChatMember); } public Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { if (unbanChatMember == null) { throw new TelegramApiException("Parameter unbanChatMember can not be null"); } - return (Boolean) sendApiMethod(unbanChatMember); + return sendApiMethod(unbanChatMember); } public Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { if (leaveChat == null) { throw new TelegramApiException("Parameter leaveChat can not be null"); } - return (Boolean) sendApiMethod(leaveChat); + return sendApiMethod(leaveChat); } public Chat getChat(GetChat getChat) throws TelegramApiException { if (getChat == null) { throw new TelegramApiException("Parameter getChat can not be null"); } - return (Chat) sendApiMethod(getChat); + return sendApiMethod(getChat); } public List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { if (getChatAdministrators == null) { throw new TelegramApiException("Parameter getChatAdministrators can not be null"); } - return (ArrayList) sendApiMethod(getChatAdministrators); + return sendApiMethod(getChatAdministrators); } public ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { if (getChatMember == null) { throw new TelegramApiException("Parameter getChatMember can not be null"); } - return (ChatMember) sendApiMethod(getChatMember); + return sendApiMethod(getChatMember); } public Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { if (getChatMemberCount == null) { throw new TelegramApiException("Parameter getChatMemberCount can not be null"); } - return (Integer) sendApiMethod(getChatMemberCount); + return sendApiMethod(getChatMemberCount); } public Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { if (editMessageText == null) { throw new TelegramApiException("Parameter editMessageText can not be null"); } - return (Message) sendApiMethod(editMessageText); + return sendApiMethod(editMessageText); } public Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { if (editMessageCaption == null) { throw new TelegramApiException("Parameter editMessageCaption can not be null"); } - return (Message) sendApiMethod(editMessageCaption); + return sendApiMethod(editMessageCaption); } public Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { if (editMessageReplyMarkup == null) { throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); } - return (Message) sendApiMethod(editMessageReplyMarkup); + return sendApiMethod(editMessageReplyMarkup); } public Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { if (answerCallbackQuery == null) { throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); } - return (Boolean) sendApiMethod(answerCallbackQuery); + return sendApiMethod(answerCallbackQuery); } public UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { @@ -237,7 +237,7 @@ public abstract class AbsSender { throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); } - return (UserProfilePhotos) sendApiMethod(getUserProfilePhotos); + return sendApiMethod(getUserProfilePhotos); } public File getFile(GetFile getFile) throws TelegramApiException{ @@ -247,13 +247,13 @@ public abstract class AbsSender { else if(getFile.getFileId() == null){ throw new TelegramApiException("Attribute file_id in parameter getFile can not be null"); } - return (File) sendApiMethod(getFile); + return sendApiMethod(getFile); } public User getMe() throws TelegramApiException { GetMe getMe = new GetMe(); - return (User) sendApiMethod(getMe); + return sendApiMethod(getMe); } // Send Requests Async @@ -928,7 +928,7 @@ public abstract class AbsSender { }); } - private Serializable sendApiMethod(BotApiMethod method) throws TelegramApiException { + private T sendApiMethod(BotApiMethod method) throws TelegramApiException { String responseContent; try { String url = getBaseUrl() + method.getPath(); From 28250901122bd75e8f2cdbda90c6e9d4c2cfd61c Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 27 May 2016 14:11:11 +0200 Subject: [PATCH 30/85] Fix webhooks (unstable) --- pom.xml | 2 +- .../telegrambots/TelegramBotsApi.java | 40 +++++++++++++------ .../updatesreceivers/Webhook.java | 15 +++++-- 3 files changed, 40 insertions(+), 17 deletions(-) diff --git a/pom.xml b/pom.xml index fa4f0398..db2329b4 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.1 + 2.3.3.2 Telegram Bots https://telegram.me/JavaBotsApi diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java index 824fc051..10618642 100644 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -21,6 +21,7 @@ import org.telegram.telegrambots.updatesreceivers.Webhook; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.text.MessageFormat; import static org.telegram.telegrambots.Constants.ERRORCODEFIELD; import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; @@ -32,11 +33,11 @@ import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; * @date 14 of January of 2016 */ public class TelegramBotsApi { + private static final String webhookUrlFormat = "{0}callback/"; private boolean useWebhook; ///< private Webhook webhook; ///< private String extrenalUrl; ///< private String pathToCertificate; ///< - private String publicCertificateName; ///< /** * @@ -52,6 +53,13 @@ public class TelegramBotsApi { * @param internalUrl */ public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiException { + if (externalUrl == null || externalUrl.isEmpty()) { + throw new TelegramApiException("Parameter externalUrl can not be null or empty"); + } + if (internalUrl == null || internalUrl.isEmpty()) { + throw new TelegramApiException("Parameter internalUrl can not be null or empty"); + } + this.useWebhook = true; this.extrenalUrl = fixExternalUrl(externalUrl); webhook = new Webhook(keyStore, keyStorePassword, internalUrl); @@ -64,14 +72,18 @@ public class TelegramBotsApi { * @param keyStorePassword * @param externalUrl * @param internalUrl - * @param pathToCertificate - * @param publicCertificateName + * @param pathToCertificate Full path until .pem public certificate keys */ - public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate, String publicCertificateName) throws TelegramApiException { + public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiException { + if (externalUrl == null || externalUrl.isEmpty()) { + throw new TelegramApiException("Parameter externalUrl can not be null or empty"); + } + if (internalUrl == null || internalUrl.isEmpty()) { + throw new TelegramApiException("Parameter internalUrl can not be null or empty"); + } this.useWebhook = true; this.extrenalUrl = fixExternalUrl(externalUrl); this.pathToCertificate = pathToCertificate; - this.publicCertificateName = publicCertificateName; webhook = new Webhook(keyStore, keyStorePassword, internalUrl); webhook.startServer(); } @@ -85,7 +97,7 @@ public class TelegramBotsApi { if (externalUrl != null && !externalUrl.endsWith("/")) { externalUrl = externalUrl + "/"; } - return externalUrl; + return MessageFormat.format(webhookUrlFormat, externalUrl); } /** @@ -96,7 +108,7 @@ public class TelegramBotsApi { * @param publicCertificateName * @throws TelegramApiException */ - private static void setWebhook(String webHookURL, String botToken, String publicCertificatePath, String publicCertificateName) throws TelegramApiException { + private static void setWebhook(String webHookURL, String botToken, String publicCertificatePath) throws TelegramApiException { try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) { String url = Constants.BASEURL + botToken + "/" + SetWebhook.PATH; @@ -104,7 +116,10 @@ public class TelegramBotsApi { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SetWebhook.URL_FIELD, webHookURL); if (publicCertificatePath != null) { - builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, new File(publicCertificatePath), ContentType.APPLICATION_OCTET_STREAM, publicCertificateName); + File certificate = new File(publicCertificatePath); + if (certificate.exists()) { + builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName()); + } } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -129,7 +144,7 @@ public class TelegramBotsApi { * @param bot the bot to register */ public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { - setWebhook(bot.getBotToken()); + setWebhook(bot.getBotToken(), null); return new BotSession(bot.getBotToken(), bot); } @@ -140,7 +155,7 @@ public class TelegramBotsApi { public void registerBot(TelegramWebhookBot bot) throws TelegramApiException { if (useWebhook) { webhook.registerWebhook(bot); - setWebhook(bot.getBotToken()); + setWebhook(bot.getBotToken(), bot.getBotPath()); } } @@ -148,10 +163,11 @@ public class TelegramBotsApi { * * @param botToken */ - private void setWebhook(String botToken) throws TelegramApiException { + private void setWebhook(String botToken, String urlPath) throws TelegramApiException { if (botToken == null) { throw new TelegramApiException("Parameter botToken can not be null"); } - setWebhook(extrenalUrl == null ? "" : extrenalUrl, botToken, pathToCertificate, publicCertificateName); + String completeExternalUrl = urlPath == null ? "" : extrenalUrl + urlPath; + setWebhook(completeExternalUrl, botToken, pathToCertificate); } } diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java index 63824e38..96245969 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/Webhook.java @@ -10,6 +10,7 @@ import org.glassfish.jersey.server.ResourceConfig; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.bots.ITelegramWebhookBot; +import java.io.File; import java.io.IOException; import java.net.URI; @@ -20,17 +21,16 @@ import java.net.URI; * @date 20 of June of 2015 */ public class Webhook { - private static final String LOGTAG = "WEBHOOK"; - private final String KEYSTORE_SERVER_FILE; private final String KEYSTORE_SERVER_PWD; private final RestApi restApi; private final String internalUrl; - public Webhook(String keyStore, String keyStorePassword, String internalUrl) { + public Webhook(String keyStore, String keyStorePassword, String internalUrl) throws TelegramApiException { this.KEYSTORE_SERVER_FILE = keyStore; this.KEYSTORE_SERVER_PWD = keyStorePassword; + validateServerKeystoreFile(keyStore); this.internalUrl = internalUrl; this.restApi = new RestApi(); } @@ -65,4 +65,11 @@ public class Webhook { private URI getBaseURI() { return URI.create(internalUrl); } - } + + private static void validateServerKeystoreFile(String keyStore) throws TelegramApiException { + File file = new File(keyStore); + if (!file.exists() || !file.canRead()) { + throw new TelegramApiException("Can't find or access server keystore file."); + } + } +} From b5eac76c685f8502faa0a1b152dfe10a12641c0b Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Fri, 27 May 2016 14:25:19 +0200 Subject: [PATCH 31/85] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 56e8ff9e..5992b3c4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: java jdk: - oraclejdk8 -script: mvn clean compile package verify +script: mvn clean compile package notifications: webhooks: secure: "jC7dK/x67ONWQoeLZg4HfW0mHhcjDerJjsLLkrbcpltiqAbw2p7XfY8Pk4zHoD72a+5o6WKu5WvYvZ4OdldnjP8Y6ZUbliQ5RG3olg3gFDoe0+sc3geeb4HRYVcdI20O0z4Bup/qO0ZihxPBc0D5IpHmFxlaqlZG0WeST4CicU8PNnBh6aX9/VMrwXhkMb2vfzmjmIhMbx/uK5+93bnk/vR5Uwu00/Yd2cTAAWMaqK1MRdtR0WLbxlUNsprEfCjYiH3n9XZnlKXs6cLC8EOU436Wx7aepiAszW0wWFMe/7nVqOqztrQiKNvL0qXYwlQf0BLechJdt458EopL9QCu687TNDFYvg1yERAmCRiaayYZcX3PbUSMr6H5Q+Odntjs3XKyzfgSqqlkgf/SAND5jny1/1uteVoplZmFXuZFIiK4H8Rl2ezy1/8pnbp+JD3YEfiA2NuRjlou1BZXyMhiqqVXbrJqk/tXF6yZSkDlYJfNsWzRCGfra4B6JjEvUP927chIFm1ii3dgNstXDo1evV46+OQQO4HKvMPdtU2FPvWpPlkTxnmpZRZjB+bjmybluJdWT3E+e1C3wm7YbRe3vporhpfNPlnod6M0G10y9CKzl9Fbcku6X1FtM+IoPO/aqZ8S4/CBZoYEuR/Nk6bcvsYouxtyIl6PSuF9E8YjpJE=" From 4270a529a0105590b37a78d00a6ddc37baa46c25 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 27 May 2016 15:06:09 +0200 Subject: [PATCH 32/85] Closes #84 --- .../objects/inlinequery/result/InlineQueryResultVoice.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java index d90f3acb..7bbc7549 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/InlineQueryResultVoice.java @@ -107,9 +107,9 @@ public class InlineQueryResultVoice implements InlineQueryResult { JSONObject jsonObject = new JSONObject(); jsonObject.put(TYPE_FIELD, type); jsonObject.put(ID_FIELD, this.id); - jsonObject.put(VOICE_DURATION_FIELD, voiceUrl); + jsonObject.put(VOICEURL_FIELD, voiceUrl); if (title != null) { - jsonObject.put(TITLE_FIELD, this.title); + jsonObject.put(TITLE_FIELD, title); } if (voiceDuration != null) { jsonObject.put(VOICE_DURATION_FIELD, voiceDuration); @@ -130,7 +130,7 @@ public class InlineQueryResultVoice implements InlineQueryResult { gen.writeStringField(ID_FIELD, id); gen.writeStringField(VOICEURL_FIELD, voiceUrl); if (title != null) { - gen.writeStringField(TITLE_FIELD, this.title); + gen.writeStringField(TITLE_FIELD, title); } if (voiceDuration != null) { gen.writeNumberField(VOICE_DURATION_FIELD, voiceDuration); From 402b842a351b22ea2c76017989d599830cf6a8f0 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Sun, 29 May 2016 03:59:39 +0200 Subject: [PATCH 33/85] Closes #85 --- .../result/chached/InlineQueryResultCachedAudio.java | 2 +- .../result/chached/InlineQueryResultCachedDocument.java | 2 +- .../inlinequery/result/chached/InlineQueryResultCachedGif.java | 2 +- .../result/chached/InlineQueryResultCachedMpeg4Gif.java | 2 +- .../result/chached/InlineQueryResultCachedPhoto.java | 2 +- .../result/chached/InlineQueryResultCachedSticker.java | 2 +- .../result/chached/InlineQueryResultCachedVideo.java | 2 +- .../result/chached/InlineQueryResultCachedVoice.java | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java index a53ca68c..08a504b3 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java @@ -87,7 +87,7 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { jsonObject.put(ID_FIELD, id); jsonObject.put(AUDIO_FILE_ID_FIELD, audioFileId); if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java index 21634824..e19cd3ee 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java @@ -128,7 +128,7 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { jsonObject.put(DESCRIPTION_FIELD, this.description); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java index c2ad9280..04790156 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java @@ -115,7 +115,7 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { jsonObject.put(CAPTION_FIELD, this.caption); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java index 00112f0b..df7dbbfc 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java @@ -115,7 +115,7 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { jsonObject.put(CAPTION_FIELD, this.caption); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java index a5a8306c..489d3a09 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java @@ -130,7 +130,7 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { jsonObject.put(CAPTION_FIELD, this.caption); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java index 76556a71..c52bf668 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java @@ -87,7 +87,7 @@ public class InlineQueryResultCachedSticker implements InlineQueryResult { jsonObject.put(ID_FIELD, this.id); jsonObject.put(STICKER_FILE_ID_FIELD, stickerFileId); if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java index d187fc5a..565f9943 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java @@ -130,7 +130,7 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { jsonObject.put(DESCRIPTION_FIELD, this.description); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); diff --git a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java index 810656b6..b770252c 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java @@ -102,7 +102,7 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { jsonObject.put(TITLE_FIELD, this.title); } if (replyMarkup != null) { - jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup); + jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson()); } if (inputMessageContent != null) { jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent); From c8aaa911876ddf829d8fff3e05a01be323ab8683 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Mon, 30 May 2016 20:25:36 +0200 Subject: [PATCH 34/85] Fix RestApi --- .../telegrambots/updatesreceivers/RestApi.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java index 4b0c4608..07748e4a 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java @@ -3,10 +3,16 @@ package org.telegram.telegrambots.updatesreceivers; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.bots.ITelegramWebhookBot; -import javax.ws.rs.*; +import java.util.concurrent.ConcurrentHashMap; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.concurrent.ConcurrentHashMap; /** * @author Ruben Bermudez @@ -15,7 +21,7 @@ import java.util.concurrent.ConcurrentHashMap; * @date 20 of June of 2015 */ @Path("callback") -class RestApi { +public class RestApi { private final ConcurrentHashMap callbacks = new ConcurrentHashMap<>(); From d1d8c74c984b3bfb7a0971229bf602f3636a11f0 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Tue, 31 May 2016 01:09:24 +0200 Subject: [PATCH 35/85] Update version to 2.3.3.2 --- README.md | 16 +++++++--------- eclipse configuration.md | 9 +++++---- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index c0f7e74a..d4fd43a1 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,11 @@ Feel free to fork this project, work on it and then make a pull request. Most of Please, **DO NOT PUSH ANY TOKEN OR API KEY**, I will never accept a pull request with that content. ## Webhooks vs GetUpdates -Both ways are supported (but I still didn't tested webhooks). - -I recommend using getUpdates methods. +Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.1) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.1) +Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.2) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.2) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. @@ -51,15 +49,15 @@ Once done, you just need to creat a `org.telegram.telegrambots.TelegramBotsApi`a ## Example bots Open them and send them */help* command to get some information about their capabilities: -https://telegram.me/weatherbot +https://telegram.me/weatherbot (**Use custom keyboards**) -https://telegram.me/directionsbot +https://telegram.me/directionsbot (**Basic messages**) -https://telegram.me/filesbot +https://telegram.me/filesbot (**Send files by file_id**) -https://telegram.me/TGlanguagesbot +https://telegram.me/TGlanguagesbot (**Send files uploding them**) -https://telegram.me/RaeBot +https://telegram.me/RaeBot (**Inline support**) You can see code for those bots at [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) project. diff --git a/eclipse configuration.md b/eclipse configuration.md index 8637ab1a..66375ab3 100644 --- a/eclipse configuration.md +++ b/eclipse configuration.md @@ -1,5 +1,8 @@ # How to use TelegramBots with Eclipse +If you **don't** need to modify the sources, you can just download the jar file from [here](https://github.com/rubenlagus/TelegramBots/releases) and import it as an external library. + +If you need to modify the sources, follow these steps: ### Step 1: Install Maven To get started, you need to install the Maven-Plugin for Eclipse. Click on Help > Eclipse Marketplace. After it finished loading, search for “Maven”. @@ -16,11 +19,9 @@ Now let’s setup the project-folder. Go to your Eclipse-Workspace and create a To import your project into the workspace you have to go to File > Import > (Folder) Maven > Existing Maven Projects > Next. Choose the folder, you have created in Step 3. In my case: **“TelegramBotApi”**. Click on finish and let Maven import the dependencies. ### Step 5: Setting the compliance level -In this last step you need to change the Compiler compliance level. To do this right-click on your Project (in my case **“TelegramBotApi”**) > Properties > Java Compiler. Uncheck the “Use compliance from…” if necessary and set it to 1.7 +In this last step you need to change the Compiler compliance level. To do this right-click on your Project (in my case **“TelegramBotApi”**) > Properties > Java Compiler. Uncheck the “Use compliance from…” if necessary and set it to 1.8 -*Now you are done. Everything should work fine. You need to set your Bot-Token in the BotConfig.java, afterwards you can run Main.java to check.* - -**For a better intstruction sheet, visit [Google Drive]** +*Now you are done. Everything should work fine.* [Google Drive]:https://goo.gl/5jd40w [here]:https://github.com/rubenlagus/TelegramBots/archive/master.zip From 986608d7adede40c548c0e8dc80436ee24a3a4ce Mon Sep 17 00:00:00 2001 From: tschulz Date: Tue, 31 May 2016 10:54:40 +0200 Subject: [PATCH 36/85] add java doc for CommandRegistry -> class purpose --- .../telegram/telegrambots/bots/commands/CommandRegistry.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index 6d2d3eb7..5231c4f5 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -10,6 +10,8 @@ import java.util.Map; import java.util.function.BiConsumer; /** + * This class manages all the commands for a bot. You can register and deregister commands on demand + * * @author tschulz */ public final class CommandRegistry implements ICommandRegistry { From eefeb1e19f3ab33e8565c71d1fda5e081c8af7b6 Mon Sep 17 00:00:00 2001 From: tschulz Date: Tue, 31 May 2016 10:54:58 +0200 Subject: [PATCH 37/85] remove empty constructor --- .../telegram/telegrambots/bots/commands/CommandRegistry.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index 5231c4f5..033e297a 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -19,9 +19,6 @@ public final class CommandRegistry implements ICommandRegistry { private final Map commandRegistryMap = new HashMap<>(); private BiConsumer defaultConsumer; - public CommandRegistry() { - } - @Override public void registerDefaultAction(BiConsumer defaultConsumer) { this.defaultConsumer = defaultConsumer; From d8abaec756a1ade9c0df166ff3ad003318437f05 Mon Sep 17 00:00:00 2001 From: tschulz Date: Tue, 31 May 2016 10:56:21 +0200 Subject: [PATCH 38/85] add javadoc (class purpose) for ICommandRegistry --- .../telegram/telegrambots/bots/commands/ICommandRegistry.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java index 676e1f8f..29559a0b 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java @@ -8,7 +8,9 @@ import java.util.Map; import java.util.function.BiConsumer; /** + * This Interface represents the gateway for registering and deregistering commands. * + * @author tschulz */ public interface ICommandRegistry { From cc9cda3226249d2061e0127ba05a2588f58f7ddf Mon Sep 17 00:00:00 2001 From: tschulz Date: Tue, 31 May 2016 11:13:28 +0200 Subject: [PATCH 39/85] add example for command bot to readme --- README.md | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d4fd43a1..7fb0a014 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ In order to use Long Polling mode, just create your own bot extending `org.teleg If you like to use Webhook, extend `org.telegram.telegrambots.bots.TelegramWebhookBot` -Once done, you just need to creat a `org.telegram.telegrambots.TelegramBotsApi`and register your bots: +Once done, you just need to create a `org.telegram.telegrambots.TelegramBotsApi`and register your bots: ```java @@ -44,7 +44,64 @@ Once done, you just need to creat a `org.telegram.telegrambots.TelegramBotsApi`a } ``` +## Command Bot +In order to make commands work for your bot by using the `org.telegram.telegrambots.bots.TelegramLongPollingCommandBot` you can +just make your Bot extend this class instead of the `org.telegram.telegrambots.bots.TelegramLongPollingBot`. + +Since this bot inherits from `org.telegram.telegrambots.bots.commands.ICommandRegistry` it is capable of register- and +deregistering commands to your bot. + +Here is an example: + +```java + + public class Main { + + private static final String LOGTAG = "MAIN"; + + public static void main(String[] args) { + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + try { + telegramBotsApi.registerBot(new MySuperSpecialBotHandler()); + } catch (TelegramApiException e) { + BotLogger.error(LOGTAG, e); + } + } + } +``` +```java + + public class MySuperSpecialBotHandler extends TelegramLongPollingCommandBot { + + private static final String LOGTAG = "MY_SUPER_SPECIAL_BOT_HANDLER"; + + public MySuperSpecialBotHandler() { + register(new BotCommand("mycommand", "This command just demonstrates the use of commands") { + @Override + public void execute(AbsSender absSender, Chat chat, String[] arguments) { + SendMessage sendMessage = new SendMessage(); + sendMessage.setText("Wow you finally used that command " + chat.getUserName()); + sendMessage.setChatId(chat.getId().toString()); + try { + absSender.sendMessage(sendMessage); + } catch (TelegramApiException e) { + BotLogger.error(LOGTAG, e); + } + } + }); + } + + @Override + public void processNonCommandUpdate(Update update) { + //All non command updated end here + } + + . + . + . + } +``` ## Example bots Open them and send them */help* command to get some information about their capabilities: From 00a8ccfac62d84929618ea6c4e75db5fa8c9b202 Mon Sep 17 00:00:00 2001 From: tschulz Date: Tue, 31 May 2016 11:14:56 +0200 Subject: [PATCH 40/85] fiy typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7fb0a014..be734913 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Here is an example: @Override public void processNonCommandUpdate(Update update) { - //All non command updated end here + //All non command updates are passed to this method } . From 0ff2e13f9691a92d4db86f4965c6235e5bf7c0b4 Mon Sep 17 00:00:00 2001 From: tschulz Date: Tue, 31 May 2016 11:14:56 +0200 Subject: [PATCH 41/85] fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7fb0a014..be734913 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Here is an example: @Override public void processNonCommandUpdate(Update update) { - //All non command updated end here + //All non command updates are passed to this method } . From e4b92fd0ad3eee00ad923627d2cc715c7862067c Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Tue, 31 May 2016 19:08:56 +0200 Subject: [PATCH 42/85] Update Telegram api docs --- .../telegrambots/api/objects/Chat.java | 6 ++++ .../telegrambots/api/objects/Message.java | 32 +++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Chat.java b/src/main/java/org/telegram/telegrambots/api/objects/Chat.java index 065aac32..18b77d8f 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Chat.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/Chat.java @@ -28,6 +28,12 @@ public class Chat implements IBotApiObject { private static final String CHANNELCHATTYPE = "channel"; private static final String SUPERGROUPCHATTYPE = "supergroup"; @JsonProperty(ID_FIELD) + /** + * Unique identifier for this chat. + * This number may be greater than 32 bits and some programming languages may + * have difficulty/silent defects in interpreting it. But it smaller than 52 bits, + * so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + */ private Long id; ///< Unique identifier for this chat, not exciding 1e13 by absolute value @JsonProperty(TYPE_FIELD) private String type; ///< Type of the chat, one of “private”, “group” or “channel” diff --git a/src/main/java/org/telegram/telegrambots/api/objects/Message.java b/src/main/java/org/telegram/telegrambots/api/objects/Message.java index f14c2894..7cc91759 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/Message.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/Message.java @@ -111,12 +111,40 @@ public class Message implements IBotApiObject { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters @JsonProperty(SUPERGROUPCREATED_FIELD) - private Boolean superGroupCreated; ///< Optional. Informs that the supergroup has been created + /** + * Optional. Service message: the supergroup has been created. + * This field can‘t be received in a message coming through updates, + * because bot can’t be a member of a supergroup when it is created. + * It can only be found in reply_to_message + * if someone replies to a very first message in a directly created supergroup. + */ + private Boolean superGroupCreated; @JsonProperty(CHANNELCHATCREATED_FIELD) - private Boolean channelChatCreated; ///< Optional. Informs that the channel has been created + /** + * Optional. Service message: the channel has been created. + * This field can‘t be received in a message coming through updates, + * because bot can’t be a member of a channel when it is created. + * It can only be found in reply_to_message if someone + * replies to a very first message in a channel. + */ + private Boolean channelChatCreated; @JsonProperty(MIGRATETOCHAT_FIELD) + /** + * Optional. The group has been migrated to a supergroup with the specified identifier. + * This number may be greater than 32 bits and some programming languages + * may have difficulty/silent defects in interpreting it. + * But it smaller than 52 bits, so a signed 64 bit integer or double-precision + * float type are safe for storing this identifier. + */ private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value @JsonProperty(MIGRATEFROMCHAT_FIELD) + /** + * Optional. The supergroup has been migrated from a group with the specified identifier. + * This number may be greater than 32 bits and some programming languages + * may have difficulty/silent defects in interpreting it. + * But it smaller than 52 bits, so a signed 64 bit integer or double-precision + * float type are safe for storing this identifier. + */ private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value @JsonProperty(EDITDATE_FIELD) private Integer editDate; ///< Optional. Date the message was last edited in Unix time From 01f321d917729f86b5953d7cbfbe83552cb0f3dd Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Tue, 31 May 2016 19:53:06 +0200 Subject: [PATCH 43/85] remove commandbot example from readme --- README.md | 57 ------------------------------------------------------- 1 file changed, 57 deletions(-) diff --git a/README.md b/README.md index be734913..e339dcb9 100644 --- a/README.md +++ b/README.md @@ -44,64 +44,7 @@ Once done, you just need to create a `org.telegram.telegrambots.TelegramBotsApi` } ``` -## Command Bot -In order to make commands work for your bot by using the `org.telegram.telegrambots.bots.TelegramLongPollingCommandBot` you can -just make your Bot extend this class instead of the `org.telegram.telegrambots.bots.TelegramLongPollingBot`. - -Since this bot inherits from `org.telegram.telegrambots.bots.commands.ICommandRegistry` it is capable of register- and -deregistering commands to your bot. - -Here is an example: - -```java - - public class Main { - - private static final String LOGTAG = "MAIN"; - - public static void main(String[] args) { - TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); - try { - telegramBotsApi.registerBot(new MySuperSpecialBotHandler()); - } catch (TelegramApiException e) { - BotLogger.error(LOGTAG, e); - } - } - } -``` -```java - - public class MySuperSpecialBotHandler extends TelegramLongPollingCommandBot { - - private static final String LOGTAG = "MY_SUPER_SPECIAL_BOT_HANDLER"; - - public MySuperSpecialBotHandler() { - register(new BotCommand("mycommand", "This command just demonstrates the use of commands") { - @Override - public void execute(AbsSender absSender, Chat chat, String[] arguments) { - SendMessage sendMessage = new SendMessage(); - sendMessage.setText("Wow you finally used that command " + chat.getUserName()); - sendMessage.setChatId(chat.getId().toString()); - try { - absSender.sendMessage(sendMessage); - } catch (TelegramApiException e) { - BotLogger.error(LOGTAG, e); - } - } - }); - } - - @Override - public void processNonCommandUpdate(Update update) { - //All non command updates are passed to this method - } - - . - . - . - } -``` ## Example bots Open them and send them */help* command to get some information about their capabilities: From 3a41c3fd5e11cd887d28ab2eeca7121587013137 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Tue, 31 May 2016 19:57:54 +0200 Subject: [PATCH 44/85] Add sender of the command to the execute method signature, to be able to do sth with it's data (e.g. userId) --- .../org/telegram/telegrambots/bots/commands/BotCommand.java | 4 +++- .../telegram/telegrambots/bots/commands/CommandRegistry.java | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java index f46e9a10..24c1cd3c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.bots.commands; import org.telegram.telegrambots.api.objects.Chat; +import org.telegram.telegrambots.api.objects.User; import org.telegram.telegrambots.bots.AbsSender; /** @@ -69,8 +70,9 @@ public abstract class BotCommand { * Execute the command * * @param absSender absSender to send messages over + * @param user the user who sent the command * @param chat the chat, to be able to send replies * @param arguments passed arguments */ - public abstract void execute(AbsSender absSender, Chat chat, String[] arguments); + public abstract void execute(AbsSender absSender, User user, Chat chat, String[] arguments); } \ No newline at end of file diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index 033e297a..816fa1cc 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -86,7 +86,7 @@ public final class CommandRegistry implements ICommandRegistry { if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); - commandRegistryMap.get(command).execute(absSender, message.getChat(), parameters); + commandRegistryMap.get(command).execute(absSender, message.getFrom(), message.getChat(), parameters); return true; } else if (defaultConsumer != null) { defaultConsumer.accept(absSender, message); From 7047811eaaa8dd94bb604c70f3847fd579cf29c0 Mon Sep 17 00:00:00 2001 From: Timo Schulz Date: Tue, 31 May 2016 20:01:50 +0200 Subject: [PATCH 45/85] change @author tag to full name + github username for reference --- .../telegrambots/bots/TelegramLongPollingCommandBot.java | 2 +- .../org/telegram/telegrambots/bots/commands/BotCommand.java | 2 +- .../telegram/telegrambots/bots/commands/CommandRegistry.java | 2 +- .../telegram/telegrambots/bots/commands/ICommandRegistry.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index fba5b986..f9f8091f 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -14,7 +14,7 @@ import java.util.function.BiConsumer; /** * This class adds command functionality to the TelegramLongPollingBot * - * @author tschulz + * @author Timo Schulz (Mit0x2) */ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingBot implements ICommandRegistry { private final CommandRegistry commandRegistry; diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java index 24c1cd3c..4b0935fa 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/BotCommand.java @@ -7,7 +7,7 @@ import org.telegram.telegrambots.bots.AbsSender; /** * Representation of a command, which can be executed * - * @author tschulz + * @author Timo Schulz (Mit0x2) */ public abstract class BotCommand { public final static String COMMAND_INIT_CHARACTER = "/"; diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index 816fa1cc..1cbafd7f 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -12,7 +12,7 @@ import java.util.function.BiConsumer; /** * This class manages all the commands for a bot. You can register and deregister commands on demand * - * @author tschulz + * @author Timo Schulz (Mit0x2) */ public final class CommandRegistry implements ICommandRegistry { diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java index 29559a0b..d6cd992c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java @@ -10,7 +10,7 @@ import java.util.function.BiConsumer; /** * This Interface represents the gateway for registering and deregistering commands. * - * @author tschulz + * @author Timo Schulz (Mit0x2) */ public interface ICommandRegistry { From 80ee84a3671e85edae937e15236db64a792a7484 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Tue, 31 May 2016 22:09:41 +0200 Subject: [PATCH 46/85] Added new webhook sample --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e339dcb9..51f8c9b7 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ https://telegram.me/TGlanguagesbot (**Send files uploding them**) https://telegram.me/RaeBot (**Inline support**) +https://telegram.me/SnowcrashBot (**Webhook support**) + You can see code for those bots at [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) project. ## Telegram Bot API From e39e20c7f933b24ac7c69d0602736c28cca3ed12 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Wed, 1 Jun 2016 00:32:14 +0200 Subject: [PATCH 47/85] Remove setter for unmodificable fields in replymarkup --- .../api/objects/replykeyboard/ForceReplyKeyboard.java | 6 ------ .../api/objects/replykeyboard/ReplyKeyboardHide.java | 8 +------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java index f086dc89..b03c2d98 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ForceReplyKeyboard.java @@ -19,7 +19,6 @@ import java.io.IOException; * @date 22 of June of 2015 */ public class ForceReplyKeyboard implements ReplyKeyboard { - private static final String FORCEREPLY_FIELD = "force_reply"; private static final String SELECTIVE_FIELD = "selective"; /** @@ -55,11 +54,6 @@ public class ForceReplyKeyboard implements ReplyKeyboard { return forceReply; } - public ForceReplyKeyboard setForceReply(Boolean forceReply) { - this.forceReply = forceReply; - return this; - } - public Boolean getSelective() { return selective; } diff --git a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java index 2b5f9529..b47e5fc4 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/replykeyboard/ReplyKeyboardHide.java @@ -19,7 +19,6 @@ import java.io.IOException; * @date 20 of June of 2015 */ public class ReplyKeyboardHide implements ReplyKeyboard { - private static final String HIDEKEYBOARD_FIELD = "hide_keyboard"; private static final String SELECTIVE_FIELD = "selective"; @JsonProperty(HIDEKEYBOARD_FIELD) @@ -34,7 +33,7 @@ public class ReplyKeyboardHide implements ReplyKeyboard { public ReplyKeyboardHide() { super(); - this.selective = true; + this.hideKeyboard = true; } public ReplyKeyboardHide(JSONObject jsonObject) { @@ -51,11 +50,6 @@ public class ReplyKeyboardHide implements ReplyKeyboard { return hideKeyboard; } - public ReplyKeyboardHide setHideKeyboard(Boolean hideKeyboard) { - this.hideKeyboard = hideKeyboard; - return this; - } - public Boolean getSelective() { return selective; } From 56ac18e2634b0f1451be5c8bb4034c9dd97d6f9c Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Wed, 1 Jun 2016 02:06:35 +0200 Subject: [PATCH 48/85] Fix ForwardMessage method --- .../api/methods/ForwardMessage.java | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java b/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java index 14da4fa7..c7254102 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/ForwardMessage.java @@ -19,12 +19,12 @@ import java.io.IOException; public class ForwardMessage extends BotApiMethod { public static final String PATH = "forwardmessage"; - public static final String CHATID_FIELD = "chat_id"; - public static final String FROMCHATID_FIELD = "from_chat_id"; - public static final String MESSAGEID_FIELD = "message_id"; - public static final String DISABLENOTIFICATION_FIELD = "disable_notification"; + private static final String CHATID_FIELD = "chat_id"; + private static final String FROMCHATID_FIELD = "from_chat_id"; + private static final String MESSAGEID_FIELD = "message_id"; + private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels) - private Integer fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id + private String fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id private Integer messageId; ///< Unique message identifier /** * Optional. Sends the message silently. @@ -47,11 +47,17 @@ public class ForwardMessage extends BotApiMethod { return this; } - public Integer getFromChatId() { + @Deprecated + public ForwardMessage setFromChatId(Integer fromChatId) { + this.fromChatId = fromChatId.toString(); + return this; + } + + public String getFromChatId() { return fromChatId; } - public ForwardMessage setFromChatId(Integer fromChatId) { + public ForwardMessage setFromChatId(String fromChatId) { this.fromChatId = fromChatId; return this; } @@ -82,7 +88,7 @@ public class ForwardMessage extends BotApiMethod { gen.writeStartObject(); gen.writeStringField(METHOD_FIELD, PATH); gen.writeStringField(CHATID_FIELD, chatId); - gen.writeNumberField(FROMCHATID_FIELD, fromChatId); + gen.writeStringField(FROMCHATID_FIELD, fromChatId); gen.writeNumberField(MESSAGEID_FIELD, messageId); if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); From 4b08b8ef7b28fa8807f6272105020a13e523b391 Mon Sep 17 00:00:00 2001 From: antonu17 Date: Thu, 2 Jun 2016 00:28:01 +0600 Subject: [PATCH 49/85] Set UTF-8 character set for reply_markup field in sendDocument(), sendPhoto(), sendVideo(), sendSticker(), sendAudio(), sendVoice() methods --- .../org/telegram/telegrambots/bots/AbsSender.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index ebefba8c..d2999b31 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -504,7 +504,7 @@ public abstract class AbsSender { builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId()); builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); if (sendDocument.getReplayMarkup() != null) { - builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString()); + builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); } if (sendDocument.getReplayToMessageId() != null) { builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString()); @@ -564,7 +564,7 @@ public abstract class AbsSender { builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()); builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); if (sendPhoto.getReplayMarkup() != null) { - builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString()); + builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); } if (sendPhoto.getReplayToMessageId() != null) { builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString()); @@ -624,7 +624,7 @@ public abstract class AbsSender { builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId()); builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); if (sendVideo.getReplayMarkup() != null) { - builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString()); + builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); } if (sendVideo.getReplayToMessageId() != null) { builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString()); @@ -703,7 +703,7 @@ public abstract class AbsSender { builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId()); builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); if (sendSticker.getReplayMarkup() != null) { - builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString()); + builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); } if (sendSticker.getReplayToMessageId() != null) { builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString()); @@ -765,7 +765,7 @@ public abstract class AbsSender { builder.addTextBody(SendAudio.CHATID_FIELD, sendAudio.getChatId()); builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); if (sendAudio.getReplayMarkup() != null) { - builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString()); + builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); } if (sendAudio.getReplayToMessageId() != null) { builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplayToMessageId().toString()); @@ -847,7 +847,7 @@ public abstract class AbsSender { builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId()); builder.addBinaryBody(SendVoice.AUDIO_FIELD, new java.io.File(sendVoice.getAudio()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); if (sendVoice.getReplayMarkup() != null) { - builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString()); + builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); } if (sendVoice.getReplayToMessageId() != null) { builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplayToMessageId().toString()); From ee12175eeaffd919e3d240c43b7df5d767d42f04 Mon Sep 17 00:00:00 2001 From: antonu17 Date: Fri, 3 Jun 2016 23:22:02 +0600 Subject: [PATCH 50/85] Change sendNew methods signature, now accepting File --- .../api/methods/send/SendAudio.java | 21 ++++++++++--------- .../api/methods/send/SendDocument.java | 17 ++++++++------- .../api/methods/send/SendPhoto.java | 15 ++++++------- .../api/methods/send/SendSticker.java | 17 ++++++++------- .../api/methods/send/SendVideo.java | 15 ++++++------- .../api/methods/send/SendVoice.java | 16 +++++++------- 6 files changed, 54 insertions(+), 47 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index 649906ca..6141adbd 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -2,6 +2,8 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; + /** * @author Ruben Bermudez * @version 1.0 @@ -36,8 +38,9 @@ public class SendAudio { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private String performer; ///< Optional. Performer of sent audio private String title; ///< Optional. Title of sent audio - private boolean isNewAudio; - private String audioName; + + private boolean isNewAudio; ///< True to upload a new audio, false to use a fileId + private File newAudioFile; ///< New audio file public SendAudio() { super(); @@ -80,13 +83,12 @@ public class SendAudio { /** * Use this method to set the audio to a new file * - * @param audio Path to the new file in your server - * @param audioName Name of the file itself + * @param file New audio file */ - public SendAudio setNewAudio(String audio, String audioName) { - this.audio = audio; + public SendAudio setNewAudio(File file) { + this.audio = file.getName(); this.isNewAudio = true; - this.audioName = audioName; + this.newAudioFile = file; return this; } @@ -144,8 +146,8 @@ public class SendAudio { return isNewAudio; } - public String getAudioName() { - return audioName; + public File getNewAudioFile() { + return newAudioFile; } @Override @@ -158,7 +160,6 @@ public class SendAudio { ", performer='" + performer + '\'' + ", title='" + title + '\'' + ", isNewAudio=" + isNewAudio + - ", audioName='" + audioName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index dacf2bb2..9f3ddbe7 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -2,6 +2,8 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; + /** * @author Ruben Bermudez * @version 1.0 @@ -28,8 +30,8 @@ public class SendDocument { private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private boolean isNewDocument; - private String documentName; + private boolean isNewDocument; ///< True to upload a new document, false to use a fileId + private File newDocumentFile; ///< New document file public SendDocument() { super(); @@ -54,10 +56,10 @@ public class SendDocument { return this; } - public SendDocument setNewDocument(String document, String documentName) { - this.document = document; + public SendDocument setNewDocument(File file) { + this.document = file.getName(); this.isNewDocument = true; - this.documentName = documentName; + this.newDocumentFile = file; return this; } @@ -65,8 +67,8 @@ public class SendDocument { return isNewDocument; } - public String getDocumentName() { - return documentName; + public File getNewDocumentFile() { + return newDocumentFile; } public Integer getReplayToMessageId() { @@ -118,7 +120,6 @@ public class SendDocument { ", replayToMessageId=" + replayToMessageId + ", replayMarkup=" + replayMarkup + ", isNewDocument=" + isNewDocument + - ", documentName='" + documentName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index fcb59daa..18cb4802 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -2,6 +2,8 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; + /** * @author Ruben Bermudez * @version 1.0 @@ -29,7 +31,7 @@ public class SendPhoto { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewPhoto; ///< True if the photo must be uploaded from a file, file if it is a fileId - private String photoName; ///< Name of the photo + private File newPhotoFile; // New photo file public SendPhoto() { @@ -86,8 +88,8 @@ public class SendPhoto { return isNewPhoto; } - public String getPhotoName() { - return photoName; + public File getNewPhotoFile() { + return newPhotoFile; } public Boolean getDisableNotification() { @@ -104,10 +106,10 @@ public class SendPhoto { return this; } - public SendPhoto setNewPhoto(String photo, String photoName) { - this.photo = photo; + public SendPhoto setNewPhoto(File file) { + this.photo = file.getName(); + this.newPhotoFile = file; this.isNewPhoto = true; - this.photoName = photoName; return this; } @@ -120,7 +122,6 @@ public class SendPhoto { ", replayToMessageId=" + replayToMessageId + ", replayMarkup=" + replayMarkup + ", isNewPhoto=" + isNewPhoto + - ", photoName='" + photoName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index b9c9cd9a..b67a0eaf 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -2,6 +2,8 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; + /** * @author Ruben Bermudez * @version 1.0 @@ -26,8 +28,8 @@ public class SendSticker { private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private boolean isNewSticker; - private String stickerName; + private boolean isNewSticker; ///< True to upload a new sticker, false to use a fileId + private File newStickerFile; ///< New sticker file public SendSticker() { super(); @@ -70,10 +72,10 @@ public class SendSticker { return this; } - public SendSticker setSticker(String sticker, String stickerName) { - this.sticker = sticker; + public SendSticker setSticker(File file) { + this.sticker = file.getName(); this.isNewSticker = true; - this.stickerName = stickerName; + this.newStickerFile = file; return this; } @@ -95,8 +97,8 @@ public class SendSticker { return isNewSticker; } - public String getStickerName() { - return stickerName; + public File getNewStickerFile() { + return newStickerFile; } @Override @@ -107,7 +109,6 @@ public class SendSticker { ", replayToMessageId=" + replayToMessageId + ", replayMarkup=" + replayMarkup + ", isNewSticker=" + isNewSticker + - ", stickerName='" + stickerName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index 135ad939..25fbc004 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -2,6 +2,8 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; + /** * @author Ruben Bermudez * @version 1.0 @@ -36,7 +38,7 @@ public class SendVideo { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewVideo; ///< True to upload a new video, false to use a fileId - private String videoName; ///< Name of the video + private File newVideoFile; ///< New video file public SendVideo() { super(); @@ -101,8 +103,8 @@ public class SendVideo { return isNewVideo; } - public String getVideoName() { - return videoName; + public File getNewVideoFile() { + return newVideoFile; } public Boolean getDisableNotification() { @@ -137,10 +139,10 @@ public class SendVideo { return this; } - public SendVideo setNewVideo(String video, String videoName) { - this.video = video; + public SendVideo setNewVideo(File file) { + this.video = file.getName(); this.isNewVideo = true; - this.videoName = videoName; + this.newVideoFile = file; return this; } @@ -154,7 +156,6 @@ public class SendVideo { ", replayToMessageId=" + replayToMessageId + ", replayMarkup=" + replayMarkup + ", isNewVideo=" + isNewVideo + - ", videoName='" + videoName + '\'' + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index fb01b1ea..d6057548 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -2,6 +2,8 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; +import java.io.File; + /** * @author Ruben Bermudez * @version 1.0 @@ -31,7 +33,7 @@ public class SendVoice { private Integer duration; ///< Optional. Duration of sent audio in seconds private boolean isNewVoice; ///< True to upload a new voice note, false to use a fileId - private String voiceName; ///< Name of the voice note + private File newVoiceFile; ///< New voice note file public SendVoice() { super(); @@ -81,10 +83,10 @@ public class SendVoice { return this; } - public SendVoice setNewAudio(String audio, String audioName) { - this.audio = audio; - this.isNewVoice = false; - this.voiceName = audioName; + public SendVoice setNewAudio(File file) { + this.audio = file.getName(); + this.isNewVoice = true; + this.newVoiceFile = file; return this; } @@ -119,7 +121,7 @@ public class SendVoice { return isNewVoice; } - public String getVoiceName() { - return voiceName; + public File getNewVoiceFile() { + return newVoiceFile; } } From 7b6a3769764891ace193d683a5225baf4c56ef83 Mon Sep 17 00:00:00 2001 From: antonu17 Date: Fri, 3 Jun 2016 23:22:13 +0600 Subject: [PATCH 51/85] Change MultipartEntityBuilder.addBinaryBody() function --- .../org/telegram/telegrambots/bots/AbsSender.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index ebefba8c..0425a167 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -502,7 +502,7 @@ public abstract class AbsSender { if (sendDocument.isNewDocument()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId()); - builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentFile()); if (sendDocument.getReplayMarkup() != null) { builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString()); } @@ -562,7 +562,7 @@ public abstract class AbsSender { if (sendPhoto.isNewPhoto()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()); - builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoFile()); if (sendPhoto.getReplayMarkup() != null) { builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString()); } @@ -622,7 +622,7 @@ public abstract class AbsSender { if (sendVideo.isNewVideo()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId()); - builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); + builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoFile()); if (sendVideo.getReplayMarkup() != null) { builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString()); } @@ -701,7 +701,7 @@ public abstract class AbsSender { if (sendSticker.isNewSticker()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId()); - builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); + builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerFile()); if (sendSticker.getReplayMarkup() != null) { builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString()); } @@ -763,7 +763,7 @@ public abstract class AbsSender { if (sendAudio.isNewAudio()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendAudio.CHATID_FIELD, sendAudio.getChatId()); - builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); + builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioFile()); if (sendAudio.getReplayMarkup() != null) { builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString()); } @@ -831,6 +831,7 @@ public abstract class AbsSender { /** * Sends a voice note using Send Voice method (https://core.telegram.org/bots/api#sendvoice) + * For this to work, your audio must be in an .ogg file encoded with OPUS * @param sendVoice Information to send * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio @@ -845,7 +846,7 @@ public abstract class AbsSender { if (sendVoice.isNewVoice()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId()); - builder.addBinaryBody(SendVoice.AUDIO_FIELD, new java.io.File(sendVoice.getAudio()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); + builder.addBinaryBody(SendVoice.AUDIO_FIELD, sendVoice.getNewVoiceFile()); if (sendVoice.getReplayMarkup() != null) { builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString()); } From 65d82076c2911906861adc421006d4986e41bf95 Mon Sep 17 00:00:00 2001 From: antonu17 Date: Sat, 4 Jun 2016 10:15:55 +0600 Subject: [PATCH 52/85] Deprecate old methods, overload setNew... methods with InputStream arguments --- .../api/methods/send/SendAudio.java | 31 +++++++++++++++++++ .../api/methods/send/SendDocument.java | 25 +++++++++++++++ .../api/methods/send/SendPhoto.java | 26 +++++++++++++++- .../api/methods/send/SendSticker.java | 27 +++++++++++++++- .../api/methods/send/SendVideo.java | 25 +++++++++++++++ .../api/methods/send/SendVoice.java | 25 +++++++++++++++ 6 files changed, 157 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index 6141adbd..6f101844 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; +import java.io.InputStream; /** * @author Ruben Bermudez @@ -40,7 +41,9 @@ public class SendAudio { private String title; ///< Optional. Title of sent audio private boolean isNewAudio; ///< True to upload a new audio, false to use a fileId + private String audioName; private File newAudioFile; ///< New audio file + private InputStream newAudioStream; ///< New audio stream public SendAudio() { super(); @@ -80,6 +83,20 @@ public class SendAudio { return this; } + /** + * Use this method to set the audio to a new file + * + * @param audio Path to the new file in your server + * @param audioName Name of the file itself + */ + @Deprecated + public SendAudio setNewAudio(String audio, String audioName) { + this.audio = audio; + this.isNewAudio = true; + this.audioName = audioName; + return this; + } + /** * Use this method to set the audio to a new file * @@ -92,6 +109,12 @@ public class SendAudio { return this; } + public SendAudio setNewAudio(InputStream inputStream) { + this.isNewAudio = true; + this.newAudioStream = inputStream; + return this; + } + public Integer getReplayToMessageId() { return replayToMessageId; } @@ -146,10 +169,18 @@ public class SendAudio { return isNewAudio; } + public String getAudioName() { + return audioName; + } + public File getNewAudioFile() { return newAudioFile; } + public InputStream getNewAudioStream() { + return newAudioStream; + } + @Override public String toString() { return "SendAudio{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index 9f3ddbe7..6a1c8dd2 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; +import java.io.InputStream; /** * @author Ruben Bermudez @@ -31,7 +32,9 @@ public class SendDocument { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewDocument; ///< True to upload a new document, false to use a fileId + private String documentName; private File newDocumentFile; ///< New document file + private InputStream newDocumentStream; ///< New document stream public SendDocument() { super(); @@ -56,6 +59,14 @@ public class SendDocument { return this; } + @Deprecated + public SendDocument setNewDocument(String document, String documentName) { + this.document = document; + this.isNewDocument = true; + this.documentName = documentName; + return this; + } + public SendDocument setNewDocument(File file) { this.document = file.getName(); this.isNewDocument = true; @@ -63,14 +74,28 @@ public class SendDocument { return this; } + public SendDocument setNewDocument(InputStream inputStream) { + this.isNewDocument = true; + this.newDocumentStream = inputStream; + return this; + } + public boolean isNewDocument() { return isNewDocument; } + public String getDocumentName() { + return documentName; + } + public File getNewDocumentFile() { return newDocumentFile; } + public InputStream getNewDocumentStream() { + return newDocumentStream; + } + public Integer getReplayToMessageId() { return replayToMessageId; } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index 18cb4802..57694a11 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; +import java.io.InputStream; /** * @author Ruben Bermudez @@ -31,8 +32,9 @@ public class SendPhoto { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewPhoto; ///< True if the photo must be uploaded from a file, file if it is a fileId + private String photoName; ///< Name of the photo private File newPhotoFile; // New photo file - + private InputStream newPhotoStream; // New photo stream public SendPhoto() { super(); @@ -88,10 +90,18 @@ public class SendPhoto { return isNewPhoto; } + public String getPhotoName() { + return photoName; + } + public File getNewPhotoFile() { return newPhotoFile; } + public InputStream getNewPhotoStream() { + return newPhotoStream; + } + public Boolean getDisableNotification() { return disableNotification; } @@ -106,6 +116,14 @@ public class SendPhoto { return this; } + @Deprecated + public SendPhoto setNewPhoto(String photo, String photoName) { + this.photo = photo; + this.isNewPhoto = true; + this.photoName = photoName; + return this; + } + public SendPhoto setNewPhoto(File file) { this.photo = file.getName(); this.newPhotoFile = file; @@ -113,6 +131,12 @@ public class SendPhoto { return this; } + public SendPhoto setNewPhoto(InputStream inputStream) { + this.newPhotoStream = inputStream; + this.isNewPhoto = true; + return this; + } + @Override public String toString() { return "SendPhoto{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index b67a0eaf..4f663297 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; +import java.io.InputStream; /** * @author Ruben Bermudez @@ -29,7 +30,9 @@ public class SendSticker { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewSticker; ///< True to upload a new sticker, false to use a fileId + private String stickerName; private File newStickerFile; ///< New sticker file + private InputStream newStickerStream; ///< New sticker stream public SendSticker() { super(); @@ -72,13 +75,27 @@ public class SendSticker { return this; } - public SendSticker setSticker(File file) { + @Deprecated + public SendSticker setSticker(String sticker, String stickerName) { + this.sticker = sticker; + this.isNewSticker = true; + this.stickerName = stickerName; + return this; + } + + public SendSticker setNewSticker(File file) { this.sticker = file.getName(); this.isNewSticker = true; this.newStickerFile = file; return this; } + public SendSticker setNewSticker(InputStream inputStream) { + this.isNewSticker = true; + this.newStickerStream = inputStream; + return this; + } + public Boolean getDisableNotification() { return disableNotification; } @@ -97,10 +114,18 @@ public class SendSticker { return isNewSticker; } + public String getStickerName() { + return stickerName; + } + public File getNewStickerFile() { return newStickerFile; } + public InputStream getNewStickerStream() { + return newStickerStream; + } + @Override public String toString() { return "SendSticker{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index 25fbc004..956588b6 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; +import java.io.InputStream; /** * @author Ruben Bermudez @@ -38,7 +39,9 @@ public class SendVideo { private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewVideo; ///< True to upload a new video, false to use a fileId + private String videoName; ///< Name of the video private File newVideoFile; ///< New video file + private InputStream newVideoStream; ///< New video stream public SendVideo() { super(); @@ -103,10 +106,18 @@ public class SendVideo { return isNewVideo; } + public String getVideoName() { + return videoName; + } + public File getNewVideoFile() { return newVideoFile; } + public InputStream getNewVideoStream() { + return newVideoStream; + } + public Boolean getDisableNotification() { return disableNotification; } @@ -139,6 +150,14 @@ public class SendVideo { return this; } + @Deprecated + public SendVideo setNewVideo(String video, String videoName) { + this.video = video; + this.isNewVideo = true; + this.videoName = videoName; + return this; + } + public SendVideo setNewVideo(File file) { this.video = file.getName(); this.isNewVideo = true; @@ -146,6 +165,12 @@ public class SendVideo { return this; } + public SendVideo setNewVideo(InputStream inputStream) { + this.isNewVideo = true; + this.newVideoStream = inputStream; + return this; + } + @Override public String toString() { return "SendVideo{" + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index d6057548..27f20367 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.api.methods.send; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; +import java.io.InputStream; /** * @author Ruben Bermudez @@ -33,7 +34,9 @@ public class SendVoice { private Integer duration; ///< Optional. Duration of sent audio in seconds private boolean isNewVoice; ///< True to upload a new voice note, false to use a fileId + private String voiceName; ///< Name of the voice note private File newVoiceFile; ///< New voice note file + private InputStream newVoiceStream; ///< New voice note stream public SendVoice() { super(); @@ -83,6 +86,14 @@ public class SendVoice { return this; } + @Deprecated + public SendVoice setNewAudio(String audio, String audioName) { + this.audio = audio; + this.isNewVoice = false; + this.voiceName = audioName; + return this; + } + public SendVoice setNewAudio(File file) { this.audio = file.getName(); this.isNewVoice = true; @@ -90,6 +101,12 @@ public class SendVoice { return this; } + public SendVoice setNewAudio(InputStream inputStream) { + this.isNewVoice = true; + this.newVoiceStream = inputStream; + return this; + } + public Integer getReplayToMessageId() { return replayToMessageId; } @@ -121,7 +138,15 @@ public class SendVoice { return isNewVoice; } + public String getVoiceName() { + return voiceName; + } + public File getNewVoiceFile() { return newVoiceFile; } + + public InputStream getNewVoiceStream() { + return newVoiceStream; + } } From 510808714440b3a4bc29db2fc7f1ad0556e65acd Mon Sep 17 00:00:00 2001 From: antonu17 Date: Sat, 4 Jun 2016 10:17:00 +0600 Subject: [PATCH 53/85] Change send methods, add using InputStream --- .../telegram/telegrambots/bots/AbsSender.java | 48 ++++++++++++++++--- 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 0425a167..300d3539 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -502,7 +502,13 @@ public abstract class AbsSender { if (sendDocument.isNewDocument()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId()); - builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentFile()); + if (sendDocument.getNewDocumentFile() != null) { + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentFile()); + } else if (sendDocument.getNewDocumentStream() != null) { + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentStream()); + } else { + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); + } if (sendDocument.getReplayMarkup() != null) { builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString()); } @@ -562,7 +568,13 @@ public abstract class AbsSender { if (sendPhoto.isNewPhoto()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()); - builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoFile()); + if (sendPhoto.getNewPhotoFile() != null) { + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoFile()); + } else if (sendPhoto.getNewPhotoStream() != null) { + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoStream()); + } else { + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); + } if (sendPhoto.getReplayMarkup() != null) { builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString()); } @@ -622,7 +634,13 @@ public abstract class AbsSender { if (sendVideo.isNewVideo()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId()); - builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoFile()); + if (sendVideo.getNewVideoFile() != null) { + builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoFile()); + } else if (sendVideo.getNewVideoStream() != null) { + builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoStream()); + } else { + builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); + } if (sendVideo.getReplayMarkup() != null) { builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString()); } @@ -701,7 +719,13 @@ public abstract class AbsSender { if (sendSticker.isNewSticker()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId()); - builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerFile()); + if (sendSticker.getNewStickerFile() != null) { + builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerFile()); + } else if (sendSticker.getNewStickerStream() != null) { + builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerStream()); + } else { + builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); + } if (sendSticker.getReplayMarkup() != null) { builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString()); } @@ -763,7 +787,13 @@ public abstract class AbsSender { if (sendAudio.isNewAudio()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendAudio.CHATID_FIELD, sendAudio.getChatId()); - builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioFile()); + if (sendAudio.getNewAudioFile() != null) { + builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioFile()); + } else if (sendAudio.getNewAudioStream() != null) { + builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioStream()); + } else { + builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); + } if (sendAudio.getReplayMarkup() != null) { builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString()); } @@ -846,7 +876,13 @@ public abstract class AbsSender { if (sendVoice.isNewVoice()) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId()); - builder.addBinaryBody(SendVoice.AUDIO_FIELD, sendVoice.getNewVoiceFile()); + if (sendVoice.getNewVoiceFile() != null) { + builder.addBinaryBody(SendVoice.AUDIO_FIELD, sendVoice.getNewVoiceFile()); + } else if (sendVoice.getNewVoiceStream() != null) { + builder.addBinaryBody(SendVoice.AUDIO_FIELD, sendVoice.getNewVoiceStream()); + } else { + builder.addBinaryBody(SendVoice.AUDIO_FIELD, new java.io.File(sendVoice.getAudio()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); + } if (sendVoice.getReplayMarkup() != null) { builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString()); } From 1c1b302b52d3a32e9923cd7f5f1bb7aa5b47f827 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 9 Jun 2016 22:31:14 +0200 Subject: [PATCH 54/85] Extract constant text plain content type --- .../telegram/telegrambots/bots/AbsSender.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index d2999b31..c54d19e7 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -74,6 +74,8 @@ import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; */ @SuppressWarnings("unused") public abstract class AbsSender { + private static final ContentType TEXT_PLAIN_CONTENT_TYPE = ContentType.create("text/plain", StandardCharsets.UTF_8); + private final ExecutorService exe = Executors.newSingleThreadExecutor(); private volatile CloseableHttpClient httpclient; private volatile RequestConfig requestConfig; @@ -504,13 +506,13 @@ public abstract class AbsSender { builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId()); builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); if (sendDocument.getReplayMarkup() != null) { - builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } if (sendDocument.getReplayToMessageId() != null) { builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString()); } if (sendDocument.getCaption() != null) { - builder.addTextBody(SendDocument.CAPTION_FIELD, sendDocument.getCaption(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendDocument.CAPTION_FIELD, sendDocument.getCaption(), TEXT_PLAIN_CONTENT_TYPE); } if (sendDocument.getDisableNotification() != null) { builder.addTextBody(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString()); @@ -564,13 +566,13 @@ public abstract class AbsSender { builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId()); builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); if (sendPhoto.getReplayMarkup() != null) { - builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } if (sendPhoto.getReplayToMessageId() != null) { builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString()); } if (sendPhoto.getCaption() != null) { - builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption(), TEXT_PLAIN_CONTENT_TYPE); } if (sendPhoto.getDisableNotification() != null) { builder.addTextBody(SendPhoto.DISABLENOTIFICATION_FIELD, sendPhoto.getDisableNotification().toString()); @@ -624,13 +626,13 @@ public abstract class AbsSender { builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId()); builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); if (sendVideo.getReplayMarkup() != null) { - builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } if (sendVideo.getReplayToMessageId() != null) { builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString()); } if (sendVideo.getCaption() != null) { - builder.addTextBody(SendVideo.CAPTION_FIELD, sendVideo.getCaption(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendVideo.CAPTION_FIELD, sendVideo.getCaption(), TEXT_PLAIN_CONTENT_TYPE); } if (sendVideo.getDuration() != null) { builder.addTextBody(SendVideo.DURATION_FIELD, sendVideo.getDuration().toString()); @@ -703,7 +705,7 @@ public abstract class AbsSender { builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId()); builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); if (sendSticker.getReplayMarkup() != null) { - builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } if (sendSticker.getReplayToMessageId() != null) { builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString()); @@ -765,7 +767,7 @@ public abstract class AbsSender { builder.addTextBody(SendAudio.CHATID_FIELD, sendAudio.getChatId()); builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); if (sendAudio.getReplayMarkup() != null) { - builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } if (sendAudio.getReplayToMessageId() != null) { builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplayToMessageId().toString()); @@ -847,7 +849,7 @@ public abstract class AbsSender { builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId()); builder.addBinaryBody(SendVoice.AUDIO_FIELD, new java.io.File(sendVoice.getAudio()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); if (sendVoice.getReplayMarkup() != null) { - builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString(), ContentType.create("text/plain", StandardCharsets.UTF_8)); + builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } if (sendVoice.getReplayToMessageId() != null) { builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplayToMessageId().toString()); From ef66e35827dbefe4b2e5611a559ef861c0063ec1 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 9 Jun 2016 22:52:08 +0200 Subject: [PATCH 55/85] Document deprecated methods --- .../api/methods/send/SendAudio.java | 2 + .../api/methods/send/SendDocument.java | 24 ++++++ .../api/methods/send/SendPhoto.java | 8 ++ .../api/methods/send/SendSticker.java | 8 ++ .../api/methods/send/SendVideo.java | 8 ++ .../api/methods/send/SendVoice.java | 77 +++++++++++++++---- .../telegram/telegrambots/bots/AbsSender.java | 10 +-- 7 files changed, 115 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index 6f101844..141fdf02 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -88,6 +88,8 @@ public class SendAudio { * * @param audio Path to the new file in your server * @param audioName Name of the file itself + * + * @deprecated use {@link #setNewAudio(File)} or {@link #setNewAudio(InputStream)} instead. */ @Deprecated public SendAudio setNewAudio(String audio, String audioName) { diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index 6a1c8dd2..3a2da623 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -53,12 +53,26 @@ public class SendDocument { return document; } + /** + * Use this method to set the document to an document existing in Telegram system + * + * @param document File_id of the document to send + * @note The file_id must have already been received or sent by your bot + */ public SendDocument setDocument(String document) { this.document = document; this.isNewDocument = false; return this; } + /** + * Use this method to set the document to a new file + * + * @param document Path to the new file in your server + * @param documentName Name of the file itself + * + * @deprecated use {@link #setNewDocument(File)} or {@link #setNewDocument(InputStream)} instead. + */ @Deprecated public SendDocument setNewDocument(String document, String documentName) { this.document = document; @@ -67,6 +81,11 @@ public class SendDocument { return this; } + /** + * Use this method to set the document to a new file + * + * @param file New document file + */ public SendDocument setNewDocument(File file) { this.document = file.getName(); this.isNewDocument = true; @@ -74,6 +93,11 @@ public class SendDocument { return this; } + /** + * Use this method to set the document to a new file + * + * @param inputStream New document file + */ public SendDocument setNewDocument(InputStream inputStream) { this.isNewDocument = true; this.newDocumentStream = inputStream; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index 57694a11..5ed0d039 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -116,6 +116,14 @@ public class SendPhoto { return this; } + /** + * Use this method to set the photo to a new file + * + * @param photo Path to the new file in your server + * @param photoName Name of the file itself + * + * @deprecated use {@link #setNewPhoto(File)} or {@link #setNewPhoto(InputStream)} instead. + */ @Deprecated public SendPhoto setNewPhoto(String photo, String photoName) { this.photo = photo; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index 4f663297..0999ad76 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -75,6 +75,14 @@ public class SendSticker { return this; } + /** + * Use this method to set the sticker to a new file + * + * @param sticker Path to the new file in your server + * @param stickerName Name of the file itself + * + * @deprecated use {@link #setNewSticker(File)} or {@link #setNewSticker(InputStream)} instead. + */ @Deprecated public SendSticker setSticker(String sticker, String stickerName) { this.sticker = sticker; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index 956588b6..d4338594 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -150,6 +150,14 @@ public class SendVideo { return this; } + /** + * Use this method to set the video to a new file + * + * @param video Path to the new file in your server + * @param videoName Name of the file itself + * + * @deprecated use {@link #setNewVideo(File)} or {@link #setNewVideo(InputStream)} instead. + */ @Deprecated public SendVideo setNewVideo(String video, String videoName) { this.video = video; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index 27f20367..3ceeb59a 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -17,13 +17,14 @@ public class SendVoice { public static final String PATH = "sendvoice"; public static final String CHATID_FIELD = "chat_id"; - public static final String AUDIO_FIELD = "audio"; + public static final String VOICE_FIELD = "voice"; public static final String DISABLENOTIFICATION_FIELD = "disable_notification"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String DURATION_FIELD = "duration"; + private String chatId; ///< Unique identifier for the chat sent message to (Or username for channels) - private String audio; ///< Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data. + private String voice; ///< Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data. /** * Optional. Sends the message silently. iOS users will not receive a notification, Android * users will receive a notification with no sound. Other apps coming soon @@ -46,7 +47,7 @@ public class SendVoice { public String toString() { return "SendVoice{" + "chatId='" + chatId + '\'' + - ", audio='" + audio + '\'' + + ", voice='" + voice + '\'' + ", replayToMessageId=" + replayToMessageId + ", replayMarkup=" + replayMarkup + ", duration=" + duration + @@ -76,32 +77,74 @@ public class SendVoice { return this; } - public String getAudio() { - return audio; - } - - public SendVoice setAudio(String audio) { - this.audio = audio; - this.isNewVoice = false; - return this; + public String getVoice() { + return voice; } + /** + * @deprecated Use {@link #getVoice()} instead + */ @Deprecated - public SendVoice setNewAudio(String audio, String audioName) { - this.audio = audio; + public String getAudio() { + return voice; + } + + public SendVoice setVoice(String voice) { + this.voice = voice; this.isNewVoice = false; - this.voiceName = audioName; return this; } - public SendVoice setNewAudio(File file) { - this.audio = file.getName(); + /** + * @deprecated Use {@link #setVoice(String)} instead + */ + @Deprecated + public SendVoice setAudio(String voice) { + this.voice = voice; + this.isNewVoice = false; + return this; + } + + /** + * Use this method to set the voice to a new file + * + * @param voice Path to the new file in your server + * @param voiceName Name of the file itself + * + * @deprecated use {@link #setNewVoice(File)} or {@link #setNewVoice(InputStream)} instead. + */ + @Deprecated + public SendVoice setNewVoice(String voice, String voiceName) { + this.voice = voice; + this.isNewVoice = false; + this.voiceName = voiceName; + return this; + } + + /** + * Use this method to set the voice to a new file + * + * @param voice Path to the new file in your server + * @param voiceName Name of the file itself + * + * @deprecated use {@link #setNewVoice(File)} or {@link #setNewVoice(InputStream)} instead. + */ + @Deprecated + public SendVoice setNewAudio(String voice, String voiceName) { + this.voice = voice; + this.isNewVoice = false; + this.voiceName = voiceName; + return this; + } + + public SendVoice setNewVoice(File file) { + this.voice = file.getName(); this.isNewVoice = true; this.newVoiceFile = file; return this; } - public SendVoice setNewAudio(InputStream inputStream) { + public SendVoice setNewVoice(InputStream inputStream) { this.isNewVoice = true; this.newVoiceStream = inputStream; return this; diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 2b6109f0..4196fa9d 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -81,7 +81,7 @@ public abstract class AbsSender { private volatile RequestConfig requestConfig; private static final int SOCKET_TIMEOUT = 75 * 1000; - public AbsSender() { + AbsSender() { httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) @@ -879,11 +879,11 @@ public abstract class AbsSender { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId()); if (sendVoice.getNewVoiceFile() != null) { - builder.addBinaryBody(SendVoice.AUDIO_FIELD, sendVoice.getNewVoiceFile()); + builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceFile()); } else if (sendVoice.getNewVoiceStream() != null) { - builder.addBinaryBody(SendVoice.AUDIO_FIELD, sendVoice.getNewVoiceStream()); + builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceStream()); } else { - builder.addBinaryBody(SendVoice.AUDIO_FIELD, new java.io.File(sendVoice.getAudio()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); + builder.addBinaryBody(SendVoice.VOICE_FIELD, new java.io.File(sendVoice.getVoice()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); } if (sendVoice.getReplayMarkup() != null) { builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); @@ -902,7 +902,7 @@ public abstract class AbsSender { } else { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendVoice.CHATID_FIELD, sendVoice.getChatId())); - nameValuePairs.add(new BasicNameValuePair(SendVoice.AUDIO_FIELD, sendVoice.getAudio())); + nameValuePairs.add(new BasicNameValuePair(SendVoice.VOICE_FIELD, sendVoice.getVoice())); if (sendVoice.getReplayMarkup() != null) { nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString())); } From 4fc3cc34cf83d40fd5ef8a756f676629e274eb05 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 9 Jun 2016 23:04:08 +0200 Subject: [PATCH 56/85] Update version v2.3.3.3 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 51f8c9b7..1e25b41f 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.2) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.2) +Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.3) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.3) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/pom.xml b/pom.xml index db2329b4..b73f825a 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.2 + 2.3.3.3 Telegram Bots https://telegram.me/JavaBotsApi From 04a2b6978bbc20c19414d0278968879e3cac1574 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Fri, 10 Jun 2016 12:17:31 +0200 Subject: [PATCH 57/85] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1e25b41f..bad22fc2 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # Telegram Bot Java Library [![Build Status](https://travis-ci.org/rubenlagus/TelegramBots.svg?branch=master)](https://travis-ci.org/rubenlagus/TelegramBots) +[![Jitpack](https://jitpack.io/v/rubenlagus/TelegramBots.svg)](https://jitpack.io/#rubenlagus/TelegramBots) [![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi) A simple to use library to create Telegram Bots in Java From 588011460497a0ebc0de229dbc925afc7f55ad53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Petersen?= Date: Mon, 20 Jun 2016 20:16:17 +0200 Subject: [PATCH 58/85] Add eclipse files to .gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index f2fa92ab..d69eab65 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,9 @@ hs_err_pid* .idea/ copyright/ *.iml +.classpath +.project +.settings/ #File System specific files .DS_STORE \ No newline at end of file From 68cda72ece0ee8117e1e106bca2bbf47e0865516 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Petersen?= Date: Mon, 20 Jun 2016 20:50:03 +0200 Subject: [PATCH 59/85] Fix replay/reply typo and deprecate old methods. Fixes #97 --- .../api/methods/send/SendAudio.java | 56 ++++++++--- .../api/methods/send/SendContact.java | 72 ++++++++++---- .../api/methods/send/SendDocument.java | 56 ++++++++--- .../api/methods/send/SendLocation.java | 72 ++++++++++---- .../api/methods/send/SendMessage.java | 72 ++++++++++---- .../api/methods/send/SendPhoto.java | 56 ++++++++--- .../api/methods/send/SendSticker.java | 56 ++++++++--- .../api/methods/send/SendVenue.java | 72 ++++++++++---- .../api/methods/send/SendVideo.java | 56 ++++++++--- .../api/methods/send/SendVoice.java | 56 ++++++++--- .../telegram/telegrambots/bots/AbsSender.java | 98 +++++++++---------- 11 files changed, 521 insertions(+), 201 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index 141fdf02..a450b5d0 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -30,13 +30,13 @@ public class SendAudio { private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender private String chatId; ///< Unique identifier for the chat to send the message to (or Username fro channels) private String audio; ///< Audio file to send. file_id as String to resend an audio that is already on the Telegram servers - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message /** * Optional. Sends the message silently. iOS users will not receive a notification, Android * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private String performer; ///< Optional. Performer of sent audio private String title; ///< Optional. Title of sent audio @@ -117,22 +117,54 @@ public class SendAudio { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendAudio setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendAudio setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendAudio setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendAudio setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendAudio setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendAudio setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public String getPerformer() { @@ -188,8 +220,8 @@ public class SendAudio { return "SendAudio{" + "chatId='" + chatId + '\'' + ", audio='" + audio + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", performer='" + performer + '\'' + ", title='" + title + '\'' + ", isNewAudio=" + isNewAudio + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java index 3fd86098..a8c94889 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java @@ -38,8 +38,8 @@ public class SendContact extends BotApiMethod { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public String getChatId() { return chatId; @@ -50,22 +50,54 @@ public class SendContact extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendContact setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendContact setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendContact setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendContact setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendContact setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendContact setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableNotification() { @@ -134,11 +166,11 @@ public class SendContact extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -157,11 +189,11 @@ public class SendContact extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -180,8 +212,8 @@ public class SendContact extends BotApiMethod { ", phoneNumber=" + phoneNumber + ", firstName=" + firstName + ", lastName=" + lastName + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index 3a2da623..9ab38fee 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -28,8 +28,8 @@ public class SendDocument { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewDocument; ///< True to upload a new document, false to use a fileId private String documentName; @@ -120,15 +120,31 @@ public class SendDocument { return newDocumentStream; } - public Integer getReplayToMessageId() { - return replayToMessageId; + public Integer getReplyToMessageId() { + return replyToMessageId; } - public SendDocument setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; + public SendDocument setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; return this; } + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated + public Integer getReplayToMessageId() { + return getReplyToMessageId(); + } + + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendDocument setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); + } + public Boolean getDisableNotification() { return disableNotification; } @@ -152,22 +168,38 @@ public class SendDocument { return this; } - public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; } - public SendDocument setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; + public SendDocument setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; return this; } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated + public ReplyKeyboard getReplayMarkup() { + return getReplyMarkup(); + } + + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendDocument setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); + } + @Override public String toString() { return "SendDocument{" + "chatId='" + chatId + '\'' + ", document='" + document + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewDocument=" + isNewDocument + '}'; } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java index a9d2ee45..31f2701b 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendLocation.java @@ -35,8 +35,8 @@ public class SendLocation extends BotApiMethod { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public String getChatId() { return chatId; @@ -65,22 +65,54 @@ public class SendLocation extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendLocation setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendLocation setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendLocation setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendLocation setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendLocation setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendLocation setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableNotification() { @@ -119,11 +151,11 @@ public class SendLocation extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -139,11 +171,11 @@ public class SendLocation extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -161,8 +193,8 @@ public class SendLocation extends BotApiMethod { "chatId='" + chatId + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java index 722b8f2a..b0f885bd 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendMessage.java @@ -38,8 +38,8 @@ public class SendMessage extends BotApiMethod { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public SendMessage() { super(); @@ -63,22 +63,54 @@ public class SendMessage extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendMessage setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendMessage setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendMessage setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendMessage setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendMessage setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendMessage setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableWebPagePreview() { @@ -141,11 +173,11 @@ public class SendMessage extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -180,11 +212,11 @@ public class SendMessage extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -203,8 +235,8 @@ public class SendMessage extends BotApiMethod { ", text='" + text + '\'' + ", parseMode='" + parseMode + '\'' + ", disableWebPagePreview=" + disableWebPagePreview + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index 5ed0d039..ecb89cf7 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -28,8 +28,8 @@ public class SendPhoto { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewPhoto; ///< True if the photo must be uploaded from a file, file if it is a fileId private String photoName; ///< Name of the photo @@ -68,22 +68,54 @@ public class SendPhoto { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendPhoto setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendPhoto setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendPhoto setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendPhoto setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendPhoto setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendPhoto setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public boolean isNewPhoto() { @@ -151,8 +183,8 @@ public class SendPhoto { "chatId='" + chatId + '\'' + ", photo='" + photo + '\'' + ", caption='" + caption + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewPhoto=" + isNewPhoto + '}'; } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index 0999ad76..8a091729 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -26,8 +26,8 @@ public class SendSticker { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewSticker; ///< True to upload a new sticker, false to use a fileId private String stickerName; @@ -57,22 +57,54 @@ public class SendSticker { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendSticker setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendSticker setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendSticker setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendSticker setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendSticker setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendSticker setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } /** @@ -139,8 +171,8 @@ public class SendSticker { return "SendSticker{" + "chatId='" + chatId + '\'' + ", sticker='" + sticker + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewSticker=" + isNewSticker + '}'; } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java index a2512132..46ead134 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java @@ -42,8 +42,8 @@ public class SendVenue extends BotApiMethod { private Boolean disableNotification; private String address; ///< Address of the venue private String foursquareId; ///< Optional. Foursquare identifier of the venue - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard public String getChatId() { return chatId; @@ -72,22 +72,54 @@ public class SendVenue extends BotApiMethod { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendVenue setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendVenue setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendVenue setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendVenue setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendVenue setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendVenue setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Boolean getDisableNotification() { @@ -158,11 +190,11 @@ public class SendVenue extends BotApiMethod { if (disableNotification != null) { jsonObject.put(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - jsonObject.put(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + jsonObject.put(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - jsonObject.put(REPLYMARKUP_FIELD, replayMarkup.toJson()); + if (replyMarkup != null) { + jsonObject.put(REPLYMARKUP_FIELD, replyMarkup.toJson()); } return jsonObject; @@ -183,11 +215,11 @@ public class SendVenue extends BotApiMethod { if (disableNotification != null) { gen.writeBooleanField(DISABLENOTIFICATION_FIELD, disableNotification); } - if (replayToMessageId != null) { - gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replayToMessageId); + if (replyToMessageId != null) { + gen.writeNumberField(REPLYTOMESSAGEID_FIELD, replyToMessageId); } - if (replayMarkup != null) { - gen.writeObjectField(REPLYMARKUP_FIELD, replayMarkup); + if (replyMarkup != null) { + gen.writeObjectField(REPLYMARKUP_FIELD, replyMarkup); } gen.writeEndObject(); @@ -208,8 +240,8 @@ public class SendVenue extends BotApiMethod { ", title=" + title + ", address=" + address + ", foursquareId=" + foursquareId + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + '}'; } } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index d4338594..393edf38 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -35,8 +35,8 @@ public class SendVideo { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private boolean isNewVideo; ///< True to upload a new video, false to use a fileId private String videoName; ///< Name of the video @@ -84,22 +84,54 @@ public class SendVideo { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendVideo setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendVideo setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendVideo setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendVideo setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendVideo setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendVideo setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public boolean isNewVideo() { @@ -186,8 +218,8 @@ public class SendVideo { ", video='" + video + '\'' + ", duration=" + duration + ", caption='" + caption + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", isNewVideo=" + isNewVideo + '}'; } diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index 3ceeb59a..0c7fce91 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -30,8 +30,8 @@ public class SendVoice { * users will receive a notification with no sound. Other apps coming soon */ private Boolean disableNotification; - private Integer replayToMessageId; ///< Optional. If the message is a reply, ID of the original message - private ReplyKeyboard replayMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private Integer duration; ///< Optional. Duration of sent audio in seconds private boolean isNewVoice; ///< True to upload a new voice note, false to use a fileId @@ -48,8 +48,8 @@ public class SendVoice { return "SendVoice{" + "chatId='" + chatId + '\'' + ", voice='" + voice + '\'' + - ", replayToMessageId=" + replayToMessageId + - ", replayMarkup=" + replayMarkup + + ", replyToMessageId=" + replyToMessageId + + ", replyMarkup=" + replyMarkup + ", duration=" + duration + '}'; } @@ -150,22 +150,54 @@ public class SendVoice { return this; } + public Integer getReplyToMessageId() { + return replyToMessageId; + } + + public SendVoice setReplyToMessageId(Integer replyToMessageId) { + this.replyToMessageId = replyToMessageId; + return this; + } + + public ReplyKeyboard getReplyMarkup() { + return replyMarkup; + } + + public SendVoice setReplyMarkup(ReplyKeyboard replyMarkup) { + this.replyMarkup = replyMarkup; + return this; + } + + /** + * @deprecated Use {@link #getReplyToMessageId()} instead. + */ + @Deprecated public Integer getReplayToMessageId() { - return replayToMessageId; + return getReplyToMessageId(); } - public SendVoice setReplayToMessageId(Integer replayToMessageId) { - this.replayToMessageId = replayToMessageId; - return this; + /** + * @deprecated Use {@link #setReplyToMessageId(Integer)} instead. + */ + @Deprecated + public SendVoice setReplayToMessageId(Integer replyToMessageId) { + return setReplyToMessageId(replyToMessageId); } + /** + * @deprecated Use {@link #getReplyMarkup()} instead. + */ + @Deprecated public ReplyKeyboard getReplayMarkup() { - return replayMarkup; + return getReplyMarkup(); } - public SendVoice setReplayMarkup(ReplyKeyboard replayMarkup) { - this.replayMarkup = replayMarkup; - return this; + /** + * @deprecated Use {@link #setReplyMarkup(ReplyKeyboard)} instead. + */ + @Deprecated + public SendVoice setReplayMarkup(ReplyKeyboard replyMarkup) { + return setReplyMarkup(replyMarkup); } public Integer getDuration() { diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 4196fa9d..035ef98c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -511,11 +511,11 @@ public abstract class AbsSender { } else { builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); } - if (sendDocument.getReplayMarkup() != null) { - builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + if (sendDocument.getReplyMarkup() != null) { + builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } - if (sendDocument.getReplayToMessageId() != null) { - builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString()); + if (sendDocument.getReplyToMessageId() != null) { + builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString()); } if (sendDocument.getCaption() != null) { builder.addTextBody(SendDocument.CAPTION_FIELD, sendDocument.getCaption(), TEXT_PLAIN_CONTENT_TYPE); @@ -529,16 +529,16 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendDocument.CHATID_FIELD, sendDocument.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendDocument.DOCUMENT_FIELD, sendDocument.getDocument())); - if (sendDocument.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString())); + if (sendDocument.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplyMarkup().toJson().toString())); } - if (sendDocument.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplayToMessageId().toString())); + if (sendDocument.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString())); } if (sendDocument.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.CAPTION_FIELD, sendDocument.getCaption())); } - if (sendDocument.getReplayToMessageId() != null) { + if (sendDocument.getReplyToMessageId() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString())); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8)); @@ -577,11 +577,11 @@ public abstract class AbsSender { } else { builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); } - if (sendPhoto.getReplayMarkup() != null) { - builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + if (sendPhoto.getReplyMarkup() != null) { + builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } - if (sendPhoto.getReplayToMessageId() != null) { - builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString()); + if (sendPhoto.getReplyToMessageId() != null) { + builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString()); } if (sendPhoto.getCaption() != null) { builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption(), TEXT_PLAIN_CONTENT_TYPE); @@ -595,11 +595,11 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendPhoto.CHATID_FIELD, sendPhoto.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendPhoto.PHOTO_FIELD, sendPhoto.getPhoto())); - if (sendPhoto.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString())); + if (sendPhoto.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplyMarkup().toJson().toString())); } - if (sendPhoto.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplayToMessageId().toString())); + if (sendPhoto.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString())); } if (sendPhoto.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption())); @@ -643,11 +643,11 @@ public abstract class AbsSender { } else { builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); } - if (sendVideo.getReplayMarkup() != null) { - builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + if (sendVideo.getReplyMarkup() != null) { + builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } - if (sendVideo.getReplayToMessageId() != null) { - builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString()); + if (sendVideo.getReplyToMessageId() != null) { + builder.addTextBody(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplyToMessageId().toString()); } if (sendVideo.getCaption() != null) { builder.addTextBody(SendVideo.CAPTION_FIELD, sendVideo.getCaption(), TEXT_PLAIN_CONTENT_TYPE); @@ -670,11 +670,11 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendVideo.CHATID_FIELD, sendVideo.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendVideo.VIDEO_FIELD, sendVideo.getVideo())); - if (sendVideo.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString())); + if (sendVideo.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplyMarkup().toJson().toString())); } - if (sendVideo.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplayToMessageId().toString())); + if (sendVideo.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVideo.REPLYTOMESSAGEID_FIELD, sendVideo.getReplyToMessageId().toString())); } if (sendVideo.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendVideo.CAPTION_FIELD, sendVideo.getCaption())); @@ -728,11 +728,11 @@ public abstract class AbsSender { } else { builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); } - if (sendSticker.getReplayMarkup() != null) { - builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + if (sendSticker.getReplyMarkup() != null) { + builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } - if (sendSticker.getReplayToMessageId() != null) { - builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString()); + if (sendSticker.getReplyToMessageId() != null) { + builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString()); } if (sendSticker.getDisableNotification() != null) { builder.addTextBody(SendSticker.DISABLENOTIFICATION_FIELD, sendSticker.getDisableNotification().toString()); @@ -743,11 +743,11 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendSticker.CHATID_FIELD, sendSticker.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendSticker.STICKER_FIELD, sendSticker.getSticker())); - if (sendSticker.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString())); + if (sendSticker.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplyMarkup().toJson().toString())); } - if (sendSticker.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplayToMessageId().toString())); + if (sendSticker.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString())); } if (sendSticker.getDisableNotification() != null) { nameValuePairs.add(new BasicNameValuePair(SendSticker.DISABLENOTIFICATION_FIELD, sendSticker.getDisableNotification().toString())); @@ -796,11 +796,11 @@ public abstract class AbsSender { } else { builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); } - if (sendAudio.getReplayMarkup() != null) { - builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + if (sendAudio.getReplyMarkup() != null) { + builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } - if (sendAudio.getReplayToMessageId() != null) { - builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplayToMessageId().toString()); + if (sendAudio.getReplyToMessageId() != null) { + builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString()); } if (sendAudio.getPerformer() != null) { builder.addTextBody(SendAudio.PERFOMER_FIELD, sendAudio.getPerformer()); @@ -820,11 +820,11 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendAudio.CHATID_FIELD, sendAudio.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendAudio.AUDIO_FIELD, sendAudio.getAudio())); - if (sendAudio.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplayMarkup().toJson().toString())); + if (sendAudio.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYMARKUP_FIELD, sendAudio.getReplyMarkup().toJson().toString())); } - if (sendAudio.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplayToMessageId().toString())); + if (sendAudio.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString())); } if (sendAudio.getPerformer() != null) { nameValuePairs.add(new BasicNameValuePair(SendAudio.PERFOMER_FIELD, sendAudio.getPerformer())); @@ -885,11 +885,11 @@ public abstract class AbsSender { } else { builder.addBinaryBody(SendVoice.VOICE_FIELD, new java.io.File(sendVoice.getVoice()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); } - if (sendVoice.getReplayMarkup() != null) { - builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); + if (sendVoice.getReplyMarkup() != null) { + builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplyMarkup().toJson().toString(), TEXT_PLAIN_CONTENT_TYPE); } - if (sendVoice.getReplayToMessageId() != null) { - builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplayToMessageId().toString()); + if (sendVoice.getReplyToMessageId() != null) { + builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString()); } if (sendVoice.getDisableNotification() != null) { builder.addTextBody(SendVoice.DISABLENOTIFICATION_FIELD, sendVoice.getDisableNotification().toString()); @@ -903,11 +903,11 @@ public abstract class AbsSender { List nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(SendVoice.CHATID_FIELD, sendVoice.getChatId())); nameValuePairs.add(new BasicNameValuePair(SendVoice.VOICE_FIELD, sendVoice.getVoice())); - if (sendVoice.getReplayMarkup() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplayMarkup().toJson().toString())); + if (sendVoice.getReplyMarkup() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYMARKUP_FIELD, sendVoice.getReplyMarkup().toJson().toString())); } - if (sendVoice.getReplayToMessageId() != null) { - nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplayToMessageId().toString())); + if (sendVoice.getReplyToMessageId() != null) { + nameValuePairs.add(new BasicNameValuePair(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString())); } if (sendVoice.getDisableNotification() != null) { nameValuePairs.add(new BasicNameValuePair(SendVoice.DISABLENOTIFICATION_FIELD, sendVoice.getDisableNotification().toString())); From c314b5a875b570a3126582c5fe5f1a5e6b99b4c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Petersen?= Date: Mon, 20 Jun 2016 20:52:14 +0200 Subject: [PATCH 60/85] Add new line at end of .gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d69eab65..737c7ac7 100644 --- a/.gitignore +++ b/.gitignore @@ -40,4 +40,4 @@ copyright/ .settings/ #File System specific files -.DS_STORE \ No newline at end of file +.DS_STORE From 046d9185742a9c7ed919c12b91f53cfb99f8ce23 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Mon, 20 Jun 2016 21:33:14 +0200 Subject: [PATCH 61/85] Use enum for Actions types --- .../telegrambots/api/methods/ActionType.java | 57 +++++++++++++++++++ .../api/methods/send/SendChatAction.java | 25 ++++++-- 2 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 src/main/java/org/telegram/telegrambots/api/methods/ActionType.java diff --git a/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java b/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java new file mode 100644 index 00000000..fb107abe --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/methods/ActionType.java @@ -0,0 +1,57 @@ +package org.telegram.telegrambots.api.methods; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Types of actions for SendChatAction method. + * @date 20 of June of 2016 + */ +public enum ActionType { + TYPING("typing"), + RECORDVIDEO("record_video"), + RECORDAUDIO("record_audio"), + UPLOADPHOTO("upload_photo"), + UPLOADVIDEO("upload_video"), + UPLOADAUDIO("upload_audio"), + UPLOADDOCUMENT("upload_document"), + FINDLOCATION("find_location"); + + private String text; + + ActionType(String text) { + this.text = text; + } + + /** + * @deprecated Added for backward compatibility, will be dropped in next mayor release + * @param text text of the action + * @return ActionType + */ + @Deprecated + public static ActionType GetActionType(String text) throws IllegalArgumentException { + switch (text) { + case "typing": + return TYPING; + case "record_video": + return RECORDVIDEO; + case "record_audio": + return RECORDAUDIO; + case "upload_photo": + return UPLOADPHOTO; + case "upload_video": + return UPLOADVIDEO; + case "upload_audio": + return UPLOADAUDIO; + case "upload_document": + return UPLOADDOCUMENT; + case "find_location": + return FINDLOCATION; + } + throw new IllegalArgumentException(text + " doesn't match any know ActionType"); + } + + @Override + public String toString() { + return text; + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java index 8e1e55bf..7ae28d9e 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendChatAction.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import org.json.JSONObject; import org.telegram.telegrambots.Constants; +import org.telegram.telegrambots.api.methods.ActionType; import org.telegram.telegrambots.api.methods.BotApiMethod; import java.io.IOException; @@ -31,7 +32,7 @@ public class SendChatAction extends BotApiMethod { * videos 'record_audio' or 'upload_audio' for audio files 'upload_document' for general files, * 'find_location' for location data. */ - private String action; + private ActionType action; public String getChatId() { return chatId; @@ -42,12 +43,28 @@ public class SendChatAction extends BotApiMethod { return this; } + /** + * @deprecated + * @return Action type text + */ + @Deprecated public String getAction() { - return action; + return action.toString(); } - public SendChatAction setAction(String action) { + public void setAction(ActionType action) { this.action = action; + } + + /** + * @deprecated Use {@link #setAction(ActionType)} instead + * @param action Text of the action to create + * @return Reference to this same instance + * @throws IllegalArgumentException if action is not valid + */ + @Deprecated + public SendChatAction setAction(String action) throws IllegalArgumentException { + this.action = ActionType.GetActionType(action); return this; } @@ -76,7 +93,7 @@ public class SendChatAction extends BotApiMethod { public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(CHATID_FIELD, chatId); - gen.writeStringField(ACTION_FIELD, action); + gen.writeStringField(ACTION_FIELD, action.toString()); gen.writeEndObject(); } From d39f874ceb149e04f3c3ab5ea21f6e4a27e07d55 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Sun, 26 Jun 2016 19:44:17 +0200 Subject: [PATCH 62/85] Update version 2.3.3.4 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bad22fc2..de45d0c7 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.3) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.3) +Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.4) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.4) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/pom.xml b/pom.xml index b73f825a..f932c507 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.3 + 2.3.3.4 Telegram Bots https://telegram.me/JavaBotsApi From 1a77291d5bb2269cddc63dc32561d64874232f36 Mon Sep 17 00:00:00 2001 From: d2a-raudenaerde Date: Wed, 29 Jun 2016 17:59:35 +0200 Subject: [PATCH 63/85] Shading http components --- pom.xml | 336 ++++++++++++++++++++++++++++++-------------------------- 1 file changed, 182 insertions(+), 154 deletions(-) diff --git a/pom.xml b/pom.xml index f932c507..1e52c814 100644 --- a/pom.xml +++ b/pom.xml @@ -1,163 +1,191 @@ - 4.0.0 - jar - org.telegram - telegrambots - 2.3.3.4 + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + jar + org.telegram + telegrambots + 2.3.3.4 - Telegram Bots - https://telegram.me/JavaBotsApi - Easy to use library to create Telegram Bots + Telegram Bots + https://telegram.me/JavaBotsApi + Easy to use library to create Telegram Bots - - - GNU General Public License (GPL) - http://www.gnu.org/licenses/gpl.html - - + + + GNU General Public License (GPL) + http://www.gnu.org/licenses/gpl.html + + - - UTF-8 - UTF-8 - 2.23 - 1.19.1 - 4.5.2 - 20160212 - 2.7.4 - + + UTF-8 + UTF-8 + 2.23 + 1.19.1 + 4.5.2 + 20160212 + 2.7.4 + - - - - org.glassfish.jersey - jersey-bom - ${jersey.version} - pom - import - - - + + + + org.glassfish.jersey + jersey-bom + ${jersey.version} + pom + import + + + - - - org.glassfish.jersey.containers - jersey-container-grizzly2-http - ${jersey.version} - - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey.version} - - - com.sun.jersey - jersey-bundle - ${jerseybundle.version} - - - com.sun.jersey - jersey-grizzly2-servlet - ${jerseybundle.version} - - - org.json - json - ${json.version} - - - org.apache.httpcomponents - httpclient - ${httpcompontents.version} - - - org.apache.httpcomponents - httpmime - ${httpcompontents.version} - - + + + org.glassfish.jersey.containers + jersey-container-grizzly2-http + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + + + com.sun.jersey + jersey-bundle + ${jerseybundle.version} + + + com.sun.jersey + jersey-grizzly2-servlet + ${jerseybundle.version} + + + org.json + json + ${json.version} + + + org.apache.httpcomponents + httpclient + ${httpcompontents.version} + + + org.apache.httpcomponents + httpmime + ${httpcompontents.version} + + - - ${project.basedir}/target - ${project.build.directory}/classes - ${project.artifactId}-${project.version} - ${project.build.directory}/test-classes - ${project.basedir}/src/main/java - - - maven-clean-plugin - 3.0.0 - - - clean-project - clean - - clean - - - - - - maven-assembly-plugin - 2.6 - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.0 - - - attach-sources - verify - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - attach-javadocs - site - - javadoc-no-fork - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - - + + ${project.basedir}/target + ${project.build.directory}/classes + ${project.artifactId}-${project.version} + ${project.build.directory}/test-classes + ${project.basedir}/src/main/java + + + maven-clean-plugin + 3.0.0 + + + clean-project + clean + + clean + + + + + + maven-assembly-plugin + 2.6 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.0 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + site + + javadoc-no-fork + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.3 + + + package + + shade + + + false + true + + + org.apache.httpcomponents:* + + + + + org.apache.http + embedded.org.apache.http + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + UTF-8 + + + + + \ No newline at end of file From ee13d9204418d31e8fe736dccd3e5adfe0c87931 Mon Sep 17 00:00:00 2001 From: valery1707 Date: Sun, 10 Jul 2016 23:44:21 +0600 Subject: [PATCH 64/85] Fix typo in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index de45d0c7..9d5eda66 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradly, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.4) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.4) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.4) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.4) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. From e75a28f518750ac8dc3f0f57b262ab4e39c86930 Mon Sep 17 00:00:00 2001 From: Sheigutn Date: Wed, 13 Jul 2016 10:04:44 +0200 Subject: [PATCH 65/85] Fixed a few copy-paste mistakes in toString() methods & fixed functionality of GetChatMember and GetChatMemberCount --- src/main/java/org/telegram/telegrambots/TelegramBotsApi.java | 1 - .../telegram/telegrambots/api/methods/AnswerCallbackQuery.java | 2 +- .../api/methods/groupadministration/GetChatMember.java | 2 +- .../api/methods/groupadministration/GetChatMemberCount.java | 2 +- .../api/methods/groupadministration/KickChatMember.java | 2 +- .../api/methods/groupadministration/UnbanChatMember.java | 2 +- .../org/telegram/telegrambots/api/methods/send/SendContact.java | 2 +- .../org/telegram/telegrambots/api/methods/send/SendVenue.java | 2 +- .../org/telegram/telegrambots/api/objects/CallbackQuery.java | 2 +- .../org/telegram/telegrambots/api/objects/MessageEntity.java | 2 +- 10 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java index 10618642..c5b9e370 100644 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -105,7 +105,6 @@ public class TelegramBotsApi { * @param webHookURL * @param botToken * @param publicCertificatePath - * @param publicCertificateName * @throws TelegramApiException */ private static void setWebhook(String webHookURL, String botToken, String publicCertificatePath) throws TelegramApiException { diff --git a/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java b/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java index 9f7d61b6..ed930884 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/AnswerCallbackQuery.java @@ -109,7 +109,7 @@ public class AnswerCallbackQuery extends BotApiMethod { @Override public String toString() { - return "AnswerInlineQuery{" + + return "AnswerCallbackQuery{" + "callbackQueryId='" + callbackQueryId + '\'' + ", text=" + text + ", showAlert=" + showAlert + '\'' + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java index 73648daf..a14a270f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMember.java @@ -19,7 +19,7 @@ import java.io.IOException; * @date 20 of May of 2016 */ public class GetChatMember extends BotApiMethod { - public static final String PATH = "getChatAdministrators"; + public static final String PATH = "getChatMember"; private static final String CHATID_FIELD = "chat_id"; private static final String USERID_FIELD = "user_id"; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java index 3b350902..d75eb49f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/GetChatMemberCount.java @@ -17,7 +17,7 @@ import java.io.IOException; * @date 20 of May of 2016 */ public class GetChatMemberCount extends BotApiMethod { - public static final String PATH = "getChatAdministrators"; + public static final String PATH = "getChatMembersCount"; private static final String CHATID_FIELD = "chat_id"; private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java index 2ce1f911..c1d53356 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java @@ -90,7 +90,7 @@ public class KickChatMember extends BotApiMethod { @Override public String toString() { - return "SendMessage{" + + return "KickChatMember{" + "chatId='" + chatId + '\'' + ", userId='" + userId + '}'; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java index 6c75940c..16381b69 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/groupadministration/UnbanChatMember.java @@ -86,7 +86,7 @@ public class UnbanChatMember extends BotApiMethod { @Override public String toString() { - return "SendMessage{" + + return "UnbanChatMember{" + "chatId='" + chatId + '\'' + ", userId='" + userId + '}'; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java index a8c94889..cef6aa93 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendContact.java @@ -207,7 +207,7 @@ public class SendContact extends BotApiMethod { @Override public String toString() { - return "SendLocation{" + + return "SendContact{" + "chatId='" + chatId + '\'' + ", phoneNumber=" + phoneNumber + ", firstName=" + firstName + diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java index 46ead134..5e57207c 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVenue.java @@ -233,7 +233,7 @@ public class SendVenue extends BotApiMethod { @Override public String toString() { - return "SendLocation{" + + return "SendVenue{" + "chatId='" + chatId + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java b/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java index af25cc10..6487d28d 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/CallbackQuery.java @@ -107,7 +107,7 @@ public class CallbackQuery implements IBotApiObject { @Override public String toString() { - return "Contact{" + + return "CallbackQuery{" + "id='" + id + '\'' + ", from='" + from + '\'' + ", message='" + message + '\'' + diff --git a/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java b/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java index fc8fefa9..52ae50f5 100644 --- a/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java +++ b/src/main/java/org/telegram/telegrambots/api/objects/MessageEntity.java @@ -119,7 +119,7 @@ public class MessageEntity implements IBotApiObject { @Override public String toString() { - return "PhotoSize{" + + return "MessageEntity{" + "type='" + type + '\'' + ", offset=" + offset + ", length=" + length + From d4dc470706d064f67cad89f2e305bf31a02f802a Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Wed, 13 Jul 2016 20:23:38 +0200 Subject: [PATCH 66/85] reformat --- pom.xml | 364 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 182 insertions(+), 182 deletions(-) diff --git a/pom.xml b/pom.xml index 1e52c814..e05ed769 100644 --- a/pom.xml +++ b/pom.xml @@ -1,191 +1,191 @@ - 4.0.0 - jar - org.telegram - telegrambots - 2.3.3.4 + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + jar + org.telegram + telegrambots + 2.3.3.4 - Telegram Bots - https://telegram.me/JavaBotsApi - Easy to use library to create Telegram Bots + Telegram Bots + https://telegram.me/JavaBotsApi + Easy to use library to create Telegram Bots - - - GNU General Public License (GPL) - http://www.gnu.org/licenses/gpl.html - - + + + GNU General Public License (GPL) + http://www.gnu.org/licenses/gpl.html + + - - UTF-8 - UTF-8 - 2.23 - 1.19.1 - 4.5.2 - 20160212 - 2.7.4 - + + UTF-8 + UTF-8 + 2.23 + 1.19.1 + 4.5.2 + 20160212 + 2.7.4 + - - - - org.glassfish.jersey - jersey-bom - ${jersey.version} - pom - import - - - + + + + org.glassfish.jersey + jersey-bom + ${jersey.version} + pom + import + + + - - - org.glassfish.jersey.containers - jersey-container-grizzly2-http - ${jersey.version} - - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey.version} - - - com.sun.jersey - jersey-bundle - ${jerseybundle.version} - - - com.sun.jersey - jersey-grizzly2-servlet - ${jerseybundle.version} - - - org.json - json - ${json.version} - - - org.apache.httpcomponents - httpclient - ${httpcompontents.version} - - - org.apache.httpcomponents - httpmime - ${httpcompontents.version} - - + + + org.glassfish.jersey.containers + jersey-container-grizzly2-http + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + + + com.sun.jersey + jersey-bundle + ${jerseybundle.version} + + + com.sun.jersey + jersey-grizzly2-servlet + ${jerseybundle.version} + + + org.json + json + ${json.version} + + + org.apache.httpcomponents + httpclient + ${httpcompontents.version} + + + org.apache.httpcomponents + httpmime + ${httpcompontents.version} + + - - ${project.basedir}/target - ${project.build.directory}/classes - ${project.artifactId}-${project.version} - ${project.build.directory}/test-classes - ${project.basedir}/src/main/java - - - maven-clean-plugin - 3.0.0 - - - clean-project - clean - - clean - - - - - - maven-assembly-plugin - 2.6 - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.0 - - - attach-sources - verify - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - attach-javadocs - site - - javadoc-no-fork - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4.3 - - - package - - shade - - - false - true - - - org.apache.httpcomponents:* - - - - - org.apache.http - embedded.org.apache.http - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - UTF-8 - - - - - + + ${project.basedir}/target + ${project.build.directory}/classes + ${project.artifactId}-${project.version} + ${project.build.directory}/test-classes + ${project.basedir}/src/main/java + + + maven-clean-plugin + 3.0.0 + + + clean-project + clean + + clean + + + + + + maven-assembly-plugin + 2.6 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.0 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + site + + javadoc-no-fork + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.3 + + + package + + shade + + + false + true + + + org.apache.httpcomponents:* + + + + + org.apache.http + embedded.org.apache.http + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + UTF-8 + + + + + \ No newline at end of file From 759d829252a2027fbc0647139dbe40aea0c8f001 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Wed, 13 Jul 2016 20:28:36 +0200 Subject: [PATCH 67/85] Merge filter in commandbot --- .../bots/TelegramLongPollingCommandBot.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index f9f8091f..4cb0c0a6 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -32,7 +32,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB public final void onUpdateReceived(Update update) { if (update.hasMessage()) { Message message = update.getMessage(); - if (message.isCommand()) { + if (message.isCommand() && !filter(message)) { if (commandRegistry.executeCommand(this, message)) { return; } @@ -41,6 +41,23 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB processNonCommandUpdate(update); } + /** + * function message filter. + * Override this function in your bot implementation to filter messages with commands + * + * For example, if you want to prevent commands execution incoming from group chat: + * # + * # return !message.getChat().isGroupChat(); + * # + * + * @param message Received message + * @return true if the message must be ignored by the command bot and treated as a non command message, + * false otherwise + */ + protected boolean filter(Message message) { + return true; + } + @Override public final boolean register(BotCommand botCommand) { return commandRegistry.register(botCommand); From a24c147a17409df101212487e523c208687939d8 Mon Sep 17 00:00:00 2001 From: dartwata Date: Thu, 14 Jul 2016 12:49:06 +0800 Subject: [PATCH 68/85] get registered command by commandIdentifier --- .../telegrambots/bots/TelegramLongPollingCommandBot.java | 5 +++++ .../telegrambots/bots/commands/CommandRegistry.java | 5 +++++ .../telegrambots/bots/commands/ICommandRegistry.java | 6 ++++++ 3 files changed, 16 insertions(+) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index f9f8091f..db39d8c4 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -71,6 +71,11 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB commandRegistry.registerDefaultAction(defaultConsumer); } + @Override + public final BotCommand getRegisteredCommand(String commandIdentifier) { + return commandRegistry.getRegisteredCommand(commandIdentifier); + } + /** * Process all updates, that are not commands. * @warning Commands that have valid syntax but are not registered on this bot, diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index 1cbafd7f..bdc75e6d 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -65,6 +65,11 @@ public final class CommandRegistry implements ICommandRegistry { return commandRegistryMap.values(); } + @Override + public final BotCommand getRegisteredCommand(String commandIdentifier) { + return commandRegistryMap.get(commandIdentifier); + } + /** * Executes a command action if the command is registered. * diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java index d6cd992c..56ae4c6c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/ICommandRegistry.java @@ -62,4 +62,10 @@ public interface ICommandRegistry { */ Collection getRegisteredCommands(); + /** + * get registered command + * + * @return registered command if exists or null if not + */ + BotCommand getRegisteredCommand(String commandIdentifier); } \ No newline at end of file From 18b31aad376c2f05f13947b8dfde950fc132e98e Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 21 Jul 2016 21:28:13 +0200 Subject: [PATCH 69/85] Add support for proxys Marked as final methods not intended to be override Close #102 --- .../telegrambots/TelegramBotsApi.java | 2 +- .../telegram/telegrambots/bots/AbsSender.java | 114 ++++++++++-------- .../telegrambots/bots/BotOptions.java | 35 ++++++ .../bots/TelegramLongPollingBot.java | 6 + .../bots/TelegramLongPollingCommandBot.java | 10 +- .../telegrambots/bots/TelegramWebhookBot.java | 7 ++ .../updatesreceivers/BotSession.java | 23 +++- 7 files changed, 141 insertions(+), 56 deletions(-) create mode 100644 src/main/java/org/telegram/telegrambots/bots/BotOptions.java diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java index c5b9e370..4b280b69 100644 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -144,7 +144,7 @@ public class TelegramBotsApi { */ public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { setWebhook(bot.getBotToken(), null); - return new BotSession(bot.getBotToken(), bot); + return new BotSession(bot.getBotToken(), bot, bot.getOptions()); } /** diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 035ef98c..2c1cd61b 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.bots; import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; @@ -77,18 +78,25 @@ public abstract class AbsSender { private static final ContentType TEXT_PLAIN_CONTENT_TYPE = ContentType.create("text/plain", StandardCharsets.UTF_8); private final ExecutorService exe = Executors.newSingleThreadExecutor(); + private final BotOptions options; private volatile CloseableHttpClient httpclient; private volatile RequestConfig requestConfig; private static final int SOCKET_TIMEOUT = 75 * 1000; - AbsSender() { + AbsSender(BotOptions options) { + this.options = options; httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) .setMaxConnTotal(100) .build(); - requestConfig = RequestConfig.copy(RequestConfig.custom().build()) - .setSocketTimeout(SOCKET_TIMEOUT) + + RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()); + if (options.hasProxy()) { + configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + } + + requestConfig = configBuilder.setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); } @@ -99,9 +107,13 @@ public abstract class AbsSender { */ public abstract String getBotToken(); + public final BotOptions getOptions() { + return options; + } + // Send Requests - public Message sendMessage(SendMessage sendMessage) throws TelegramApiException { + public final Message sendMessage(SendMessage sendMessage) throws TelegramApiException { if (sendMessage == null) { throw new TelegramApiException("Parameter sendMessage can not be null"); } @@ -109,7 +121,7 @@ public abstract class AbsSender { return sendApiMethod(sendMessage); } - public Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { + public final Boolean answerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException { if (answerInlineQuery == null) { throw new TelegramApiException("Parameter answerInlineQuery can not be null"); } @@ -117,7 +129,7 @@ public abstract class AbsSender { return sendApiMethod(answerInlineQuery); } - public Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { + public final Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException { if (sendChatAction == null) { throw new TelegramApiException("Parameter sendChatAction can not be null"); } @@ -125,7 +137,7 @@ public abstract class AbsSender { return sendApiMethod(sendChatAction); } - public Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { + public final Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException { if (forwardMessage == null) { throw new TelegramApiException("Parameter forwardMessage can not be null"); } @@ -133,7 +145,7 @@ public abstract class AbsSender { return sendApiMethod(forwardMessage); } - public Message sendLocation(SendLocation sendLocation) throws TelegramApiException { + public final Message sendLocation(SendLocation sendLocation) throws TelegramApiException { if (sendLocation == null) { throw new TelegramApiException("Parameter sendLocation can not be null"); } @@ -141,7 +153,7 @@ public abstract class AbsSender { return sendApiMethod(sendLocation); } - public Message sendVenue(SendVenue sendVenue) throws TelegramApiException { + public final Message sendVenue(SendVenue sendVenue) throws TelegramApiException { if (sendVenue == null) { throw new TelegramApiException("Parameter sendVenue can not be null"); } @@ -149,7 +161,7 @@ public abstract class AbsSender { return sendApiMethod(sendVenue); } - public Message sendContact(SendContact sendContact) throws TelegramApiException { + public final Message sendContact(SendContact sendContact) throws TelegramApiException { if (sendContact == null) { throw new TelegramApiException("Parameter sendContact can not be null"); } @@ -157,84 +169,84 @@ public abstract class AbsSender { return sendApiMethod(sendContact); } - public Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { + public final Boolean kickMember(KickChatMember kickChatMember) throws TelegramApiException { if (kickChatMember == null) { throw new TelegramApiException("Parameter kickChatMember can not be null"); } return sendApiMethod(kickChatMember); } - public Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { + public final Boolean unbanMember(UnbanChatMember unbanChatMember) throws TelegramApiException { if (unbanChatMember == null) { throw new TelegramApiException("Parameter unbanChatMember can not be null"); } return sendApiMethod(unbanChatMember); } - public Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { + public final Boolean leaveChat(LeaveChat leaveChat) throws TelegramApiException { if (leaveChat == null) { throw new TelegramApiException("Parameter leaveChat can not be null"); } return sendApiMethod(leaveChat); } - public Chat getChat(GetChat getChat) throws TelegramApiException { + public final Chat getChat(GetChat getChat) throws TelegramApiException { if (getChat == null) { throw new TelegramApiException("Parameter getChat can not be null"); } return sendApiMethod(getChat); } - public List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { + public final List getChatAdministrators(GetChatAdministrators getChatAdministrators) throws TelegramApiException { if (getChatAdministrators == null) { throw new TelegramApiException("Parameter getChatAdministrators can not be null"); } return sendApiMethod(getChatAdministrators); } - public ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { + public final ChatMember getChatMember(GetChatMember getChatMember) throws TelegramApiException { if (getChatMember == null) { throw new TelegramApiException("Parameter getChatMember can not be null"); } return sendApiMethod(getChatMember); } - public Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { + public final Integer getChatMemberCount(GetChatMemberCount getChatMemberCount) throws TelegramApiException { if (getChatMemberCount == null) { throw new TelegramApiException("Parameter getChatMemberCount can not be null"); } return sendApiMethod(getChatMemberCount); } - public Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { + public final Message editMessageText(EditMessageText editMessageText) throws TelegramApiException { if (editMessageText == null) { throw new TelegramApiException("Parameter editMessageText can not be null"); } return sendApiMethod(editMessageText); } - public Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { + public final Message editMessageCaption(EditMessageCaption editMessageCaption) throws TelegramApiException { if (editMessageCaption == null) { throw new TelegramApiException("Parameter editMessageCaption can not be null"); } return sendApiMethod(editMessageCaption); } - public Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { + public final Message editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup) throws TelegramApiException { if (editMessageReplyMarkup == null) { throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); } return sendApiMethod(editMessageReplyMarkup); } - public Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { + public final Boolean answerCallbackQuery(AnswerCallbackQuery answerCallbackQuery) throws TelegramApiException { if (answerCallbackQuery == null) { throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); } return sendApiMethod(answerCallbackQuery); } - public UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { + public final UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException { if (getUserProfilePhotos == null) { throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); } @@ -242,7 +254,7 @@ public abstract class AbsSender { return sendApiMethod(getUserProfilePhotos); } - public File getFile(GetFile getFile) throws TelegramApiException{ + public final File getFile(GetFile getFile) throws TelegramApiException{ if(getFile == null){ throw new TelegramApiException("Parameter getFile can not be null"); } @@ -252,7 +264,7 @@ public abstract class AbsSender { return sendApiMethod(getFile); } - public User getMe() throws TelegramApiException { + public final User getMe() throws TelegramApiException { GetMe getMe = new GetMe(); return sendApiMethod(getMe); @@ -260,7 +272,7 @@ public abstract class AbsSender { // Send Requests Async - public void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { + public final void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { if (sendMessage == null) { throw new TelegramApiException("Parameter sendMessage can not be null"); } @@ -272,7 +284,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendMessage, sentCallback); } - public void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback sentCallback) throws TelegramApiException { + public final void answerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback sentCallback) throws TelegramApiException { if (answerInlineQuery == null) { throw new TelegramApiException("Parameter answerInlineQuery can not be null"); } @@ -284,7 +296,7 @@ public abstract class AbsSender { sendApiMethodAsync(answerInlineQuery, sentCallback); } - public void sendChatActionAsync(SendChatAction sendChatAction, SentCallback sentCallback) throws TelegramApiException { + public final void sendChatActionAsync(SendChatAction sendChatAction, SentCallback sentCallback) throws TelegramApiException { if (sendChatAction == null) { throw new TelegramApiException("Parameter sendChatAction can not be null"); } @@ -296,7 +308,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendChatAction, sentCallback); } - public void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback sentCallback) throws TelegramApiException { + public final void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback sentCallback) throws TelegramApiException { if (forwardMessage == null) { throw new TelegramApiException("Parameter forwardMessage can not be null"); } @@ -308,7 +320,7 @@ public abstract class AbsSender { sendApiMethodAsync(forwardMessage, sentCallback); } - public void sendLocationAsync(SendLocation sendLocation, SentCallback sentCallback) throws TelegramApiException { + public final void sendLocationAsync(SendLocation sendLocation, SentCallback sentCallback) throws TelegramApiException { if (sendLocation == null) { throw new TelegramApiException("Parameter sendLocation can not be null"); } @@ -320,7 +332,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendLocation, sentCallback); } - public void sendVenueAsync(SendVenue sendVenue, SentCallback sentCallback) throws TelegramApiException { + public final void sendVenueAsync(SendVenue sendVenue, SentCallback sentCallback) throws TelegramApiException { if (sendVenue == null) { throw new TelegramApiException("Parameter sendVenue can not be null"); } @@ -332,7 +344,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendVenue, sentCallback); } - public void sendContactAsync(SendContact sendContact, SentCallback sentCallback) throws TelegramApiException { + public final void sendContactAsync(SendContact sendContact, SentCallback sentCallback) throws TelegramApiException { if (sendContact == null) { throw new TelegramApiException("Parameter sendContact can not be null"); } @@ -343,7 +355,7 @@ public abstract class AbsSender { sendApiMethodAsync(sendContact, sentCallback); } - public void kickMemberAsync(KickChatMember kickChatMember, SentCallback sentCallback) throws TelegramApiException { + public final void kickMemberAsync(KickChatMember kickChatMember, SentCallback sentCallback) throws TelegramApiException { if (kickChatMember == null) { throw new TelegramApiException("Parameter kickChatMember can not be null"); } @@ -354,7 +366,7 @@ public abstract class AbsSender { sendApiMethodAsync(kickChatMember, sentCallback); } - public void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback sentCallback) throws TelegramApiException { + public final void unbanMemberAsync(UnbanChatMember unbanChatMember, SentCallback sentCallback) throws TelegramApiException { if (unbanChatMember == null) { throw new TelegramApiException("Parameter unbanChatMember can not be null"); } @@ -365,7 +377,7 @@ public abstract class AbsSender { sendApiMethodAsync(unbanChatMember, sentCallback); } - public void leaveChatAsync(LeaveChat leaveChat, SentCallback sentCallback) throws TelegramApiException { + public final void leaveChatAsync(LeaveChat leaveChat, SentCallback sentCallback) throws TelegramApiException { if (leaveChat == null) { throw new TelegramApiException("Parameter leaveChat can not be null"); } @@ -375,7 +387,7 @@ public abstract class AbsSender { sendApiMethodAsync(leaveChat, sentCallback); } - public void getChatAsync(GetChat getChat, SentCallback sentCallback) throws TelegramApiException { + public final void getChatAsync(GetChat getChat, SentCallback sentCallback) throws TelegramApiException { if (getChat == null) { throw new TelegramApiException("Parameter getChat can not be null"); } @@ -385,7 +397,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChat, sentCallback); } - public void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback> sentCallback) throws TelegramApiException { + public final void getChatAdministratorsAsync(GetChatAdministrators getChatAdministrators, SentCallback> sentCallback) throws TelegramApiException { if (getChatAdministrators == null) { throw new TelegramApiException("Parameter getChatAdministrators can not be null"); } @@ -395,7 +407,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChatAdministrators, sentCallback); } - public void getChatMemberAsync(GetChatMember getChatMember, SentCallback sentCallback) throws TelegramApiException { + public final void getChatMemberAsync(GetChatMember getChatMember, SentCallback sentCallback) throws TelegramApiException { if (getChatMember == null) { throw new TelegramApiException("Parameter getChatMember can not be null"); } @@ -405,7 +417,7 @@ public abstract class AbsSender { sendApiMethodAsync(getChatMember, sentCallback); } - public void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback sentCallback) throws TelegramApiException { + public final void getChatMemberCountAsync(GetChatMemberCount getChatMemberCount, SentCallback sentCallback) throws TelegramApiException { if (getChatMemberCount == null) { throw new TelegramApiException("Parameter getChatMemberCount can not be null"); } @@ -417,7 +429,7 @@ public abstract class AbsSender { } - public void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { + public final void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { if (editMessageText == null) { throw new TelegramApiException("Parameter editMessageText can not be null"); } @@ -428,7 +440,7 @@ public abstract class AbsSender { sendApiMethodAsync(editMessageText, sentCallback); } - public void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback sentCallback) throws TelegramApiException { + public final void editMessageCaptionAsync(EditMessageCaption editMessageCaption, SentCallback sentCallback) throws TelegramApiException { if (editMessageCaption == null) { throw new TelegramApiException("Parameter editMessageCaption can not be null"); } @@ -439,7 +451,7 @@ public abstract class AbsSender { sendApiMethodAsync(editMessageCaption, sentCallback); } - public void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback sentCallback) throws TelegramApiException { + public final void editMessageReplyMarkup(EditMessageReplyMarkup editMessageReplyMarkup, SentCallback sentCallback) throws TelegramApiException { if (editMessageReplyMarkup == null) { throw new TelegramApiException("Parameter editMessageReplyMarkup can not be null"); } @@ -450,7 +462,7 @@ public abstract class AbsSender { sendApiMethodAsync(editMessageReplyMarkup, sentCallback); } - public void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback sentCallback) throws TelegramApiException { + public final void answerCallbackQueryAsync(AnswerCallbackQuery answerCallbackQuery, SentCallback sentCallback) throws TelegramApiException { if (answerCallbackQuery == null) { throw new TelegramApiException("Parameter answerCallbackQuery can not be null"); } @@ -461,7 +473,7 @@ public abstract class AbsSender { sendApiMethodAsync(answerCallbackQuery, sentCallback); } - public void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback sentCallback) throws TelegramApiException { + public final void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback sentCallback) throws TelegramApiException { if (getUserProfilePhotos == null) { throw new TelegramApiException("Parameter getUserProfilePhotos can not be null"); } @@ -473,7 +485,7 @@ public abstract class AbsSender { sendApiMethodAsync(getUserProfilePhotos, sentCallback); } - public void getFileAsync(GetFile getFile, SentCallback sentCallback) throws TelegramApiException { + public final void getFileAsync(GetFile getFile, SentCallback sentCallback) throws TelegramApiException { if (getFile == null) { throw new TelegramApiException("Parameter getFile can not be null"); } else if (getFile.getFileId() == null) { @@ -483,7 +495,7 @@ public abstract class AbsSender { sendApiMethodAsync(getFile, sentCallback); } - public void getMeAsync(SentCallback sentCallback) throws TelegramApiException { + public final void getMeAsync(SentCallback sentCallback) throws TelegramApiException { if (sentCallback == null) { throw new TelegramApiException("Parameter sentCallback can not be null"); } @@ -494,7 +506,7 @@ public abstract class AbsSender { // Specific Send Requests - public Message sendDocument(SendDocument sendDocument) throws TelegramApiException { + public final Message sendDocument(SendDocument sendDocument) throws TelegramApiException { String responseContent; try { @@ -561,7 +573,7 @@ public abstract class AbsSender { return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); } - public Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException { + public final Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException { String responseContent; try { String url = getBaseUrl() + SendPhoto.PATH; @@ -627,7 +639,7 @@ public abstract class AbsSender { return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); } - public Message sendVideo(SendVideo sendVideo) throws TelegramApiException { + public final Message sendVideo(SendVideo sendVideo) throws TelegramApiException { String responseContent; try { String url = getBaseUrl() + SendVideo.PATH; @@ -711,7 +723,7 @@ public abstract class AbsSender { return new Message(jsonObject.getJSONObject(Constants.RESPONSEFIELDRESULT)); } - public Message sendSticker(SendSticker sendSticker) throws TelegramApiException { + public final Message sendSticker(SendSticker sendSticker) throws TelegramApiException { String responseContent; try { @@ -778,7 +790,7 @@ public abstract class AbsSender { * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio */ - public Message sendAudio(SendAudio sendAudio) throws TelegramApiException { + public final Message sendAudio(SendAudio sendAudio) throws TelegramApiException { String responseContent; @@ -868,7 +880,7 @@ public abstract class AbsSender { * @return If success, the sent Message is returned * @throws TelegramApiException If there is any error sending the audio */ - public Message sendVoice(SendVoice sendVoice) throws TelegramApiException { + public final Message sendVoice(SendVoice sendVoice) throws TelegramApiException { String responseContent; try { diff --git a/src/main/java/org/telegram/telegrambots/bots/BotOptions.java b/src/main/java/org/telegram/telegrambots/bots/BotOptions.java new file mode 100644 index 00000000..081481a9 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/bots/BotOptions.java @@ -0,0 +1,35 @@ +package org.telegram.telegrambots.bots; + +/** + * @author Ruben Bermudez + * @version 1.0 + * @brief Configurations for the Bot + * @date 21 of July of 2016 + */ +public class BotOptions { + private String proxyHost; + private int proxyPort; + + public BotOptions() { + } + + public String getProxyHost() { + return proxyHost; + } + + public int getProxyPort() { + return proxyPort; + } + + public void setProxyHost(String proxyHost) { + this.proxyHost = proxyHost; + } + + public void setProxyPort(int proxyPort) { + this.proxyPort = proxyPort; + } + + public boolean hasProxy() { + return proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0; + } +} diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 7afdf9c8..40915803 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -7,5 +7,11 @@ package org.telegram.telegrambots.bots; * @date 14 of January of 2016 */ public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot { + public TelegramLongPollingBot() { + this(new BotOptions()); + } + public TelegramLongPollingBot(BotOptions options) { + super(options); + } } diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index 8ff78678..e6d2b25f 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -24,7 +24,15 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * Use ICommandRegistry's methods on this bot to register commands */ public TelegramLongPollingCommandBot() { - super(); + this(new BotOptions()); + } + + /** + * construct creates CommandRegistry for this bot. + * Use ICommandRegistry's methods on this bot to register commands + */ + public TelegramLongPollingCommandBot(BotOptions options) { + super(options); this.commandRegistry = new CommandRegistry(); } diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java index ddf56bca..b3f41afb 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java @@ -7,4 +7,11 @@ package org.telegram.telegrambots.bots; * @date 14 of January of 2016 */ public abstract class TelegramWebhookBot extends AbsSender implements ITelegramWebhookBot { + public TelegramWebhookBot() { + this(new BotOptions()); + } + + public TelegramWebhookBot(BotOptions options) { + super(options); + } } diff --git a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java b/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java index 554c69e6..b13c5b2f 100644 --- a/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java +++ b/src/main/java/org/telegram/telegrambots/updatesreceivers/BotSession.java @@ -1,6 +1,7 @@ package org.telegram.telegrambots.updatesreceivers; import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -18,6 +19,7 @@ import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.TelegramApiException; import org.telegram.telegrambots.api.methods.updates.GetUpdates; import org.telegram.telegrambots.api.objects.Update; +import org.telegram.telegrambots.bots.BotOptions; import org.telegram.telegrambots.bots.ITelegramLongPollingBot; import org.telegram.telegrambots.logging.BotLogger; @@ -47,8 +49,19 @@ public class BotSession { private volatile CloseableHttpClient httpclient; private volatile RequestConfig requestConfig; - + /** + * Constructor present just to keep backward compatibility will be removed in next mayor release. + * + * @deprecated @deprecated use {@link #BotSession(String, ITelegramLongPollingBot, BotOptions)} + * @param token Token of the bot + * @param callback Callback for incomming updates + */ + @Deprecated public BotSession(String token, ITelegramLongPollingBot callback) { + this(token, callback, new BotOptions()); + } + + public BotSession(String token, ITelegramLongPollingBot callback, BotOptions options) { this.token = token; this.callback = callback; @@ -58,8 +71,12 @@ public class BotSession { .setMaxConnTotal(100) .build(); - requestConfig = RequestConfig.copy(RequestConfig.custom().build()) - .setSocketTimeout(SOCKET_TIMEOUT) + RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()); + if (options.hasProxy()) { + configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + } + + requestConfig = configBuilder.setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); From 45b63d9ea21c32521a2a9867ec7cf06b2914ae00 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 21 Jul 2016 22:21:22 +0200 Subject: [PATCH 70/85] Update to version 2.3.3.5 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 09533615..ffb57048 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.4) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.4) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.5) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.5) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/pom.xml b/pom.xml index e05ed769..ee620853 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.4 + 2.3.3.5 Telegram Bots https://telegram.me/JavaBotsApi From d5361d28dda7d7d7de292dd833ab19e09946804f Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 21 Jul 2016 23:07:27 +0200 Subject: [PATCH 71/85] Remove http shading (for now) --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index ee620853..f26f8acd 100644 --- a/pom.xml +++ b/pom.xml @@ -145,6 +145,7 @@ + From 46597db92bb13c853a40b835bfb1fad4f1bee925 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 21 Jul 2016 23:25:52 +0200 Subject: [PATCH 72/85] Update to version 2.3.3.6 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ffb57048..d058aefe 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.5) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.5) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.6) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.6) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/pom.xml b/pom.xml index f26f8acd..e41e3a4f 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.5 + 2.3.3.6 Telegram Bots https://telegram.me/JavaBotsApi From c9f77855c7e728e41fafa78c1aeaddf41d948ac3 Mon Sep 17 00:00:00 2001 From: Clevero Date: Sun, 7 Aug 2016 05:29:03 +0200 Subject: [PATCH 73/85] Update HOWTO (#124) * Create HOW_TO.md * Rename HOW_TO.md to HOWTO.md * small changes correct linking, spelling and add TelegramLongPollingCommandBot --- HOWTO.md | 275 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 HOWTO.md diff --git a/HOWTO.md b/HOWTO.md new file mode 100644 index 00000000..bbd64b2f --- /dev/null +++ b/HOWTO.md @@ -0,0 +1,275 @@ +So, you just wanna program a own Telegram bot with @rubenlagus library TelegramBots? Then I'm going to show you how to start ;) + +##### Table of Contents +[Preperations](#preperations) +[Let's code!](#lets_code) +[FAQ](#faq) +       1. [How to get picture?](#question_how_to_get_picture) +       2. [How to send photos?](#question_how_to_send_photos) +       3. [How to use custom keyboards?](#question_how_to_use_custom_keyboards) +       4. [How can I compile my project?](#question_how_to_compile) + + + + +## Preperations +First you need to download the latest .jar from the Release site [here](https://github.com/rubenlagus/TelegramBots/releases). You can choose between Jar dependencies and wthout. If you don't know what to choose, we recommend to download the full jar with all dependencies ;) + +Next, you need to integrate it into your project. + +Create a new project for your bot, in the example below we are showing you how to do it in eclipse. But of course, you are free to code in whatever IDE you want ;) + +If you don't know how to include a external .jar into your Eclipse project, maybe [this](https://www.youtube.com/watch?v=VWnfHkBgO1I) video is helpfull for you + +More information on how to use it with Gradly or Maven, can you find here [here](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.4) + + + +## Let's code! +Create a new class that is extending one of the following + +```TelegramLongPollingBot``` -> bot is asking the Telegram servers continuously if new updates are available + +```TelegramWebhookBot``` -> our bot is "called" from the Telegram servers when updates are available + +```TelegramLongPollingCommandBot``` -> simply like TelegramLongPollingBot, but based around the idea of Commands + + +Due to the fact that the TelegramLongPollingBot is a little bit less complicated than the others, are we going to work with him in the following. + + +Extend ```TelegramLongPollingBot``` with one of your own classes. If we want that the bot can work normally, we must implement the following methods: ```getBotUsername():String```, ```getBotToken():String``` und ```onUpdateReceived(update: Update)``` + +The first two methods are really easy to implement. Jus create a new class that contains all our informations for the bot (username, token and maybe in the future some database information) + +At the end it could look like this: + +```java +public class BotConfig { + + public static final String BOT_USERNAME = "echoBot"; + + public static final String BOT_TOKEN = "{you secret bot token you got from the BotFather}"; + +} +``` + +After it, return these static variables like this one: +```java +@Override + public String getBotToken() { + return BotConfig.BOT_TOKEN; + } + +``` + +The last method could look like this: + +```java +@Override + public void onUpdateReceived(Update update) { + + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + + //check if the message has text. it could also contain for example a location ( message.hasLocation() ) + if(message.hasText()){ + + //create a object that contains the information to send back the message + SendMessage sendMessageRequest = new SendMessage(); + sendMessageRequest.setChatId(message.getChatId().toString()); //who should get the message? the sender from which we got the message... + sendMessageRequest.setText("you said: " + message.getText()); + try { + sendMessage(sendMessageRequest); //at the end, so some magic and send the message ;) + } catch (TelegramApiException e) { + //do some error handling + } + } + } + + } +``` +The princip is rather easy, we have an ```update```, we see that it contains a text -> we create a Send*** object, fill it up with all necessary infos (user/chatId, text) and fire it up + +If you want to send also other types of media (such as photos or audio), then check out our FAQ at the end if this HOWTO. Also please check out the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It contains usefull informations on how to use the lib from @rubenlagus. + +If you have questions that are not handled here or in the example repo, than feel free to open a new Issue :P +In any case, you can reach us in our chat at [our group chat](https://telegram.me/JavaBotsApi) ;) + +But to be in context: our bot is not ready, yet. It lacks of a used way to the tell lib that we have a super cool new UpdateHandler written, you remember? 😏 + + +```java +public static void main(String[] args) { + + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + try { + telegramBotsApi.registerBot(new MyProjectHandler()); + } catch (TelegramApiException e) { + BotLogger.error(LOGTAG, e); + } + } +``` + + +## FAQ + + Question: + How to get a picture? + Answer: A ```onUpdateReceived()``` Method that just downloads every Photo that users send to the bot could look like this: + +```java + @Override + public void onUpdateReceived(Update update) { + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + + //check if we got some photos + if(message.getPhoto() != null){ + + + /* + * Just save our received photos in a list. At this point, we do not really have the photos. We have just their id. + * And with their id's we can download them from telegram servers + */ + + for(int i = 0; i < photos.size(); i++){ + + GetFile getFileRequest = new GetFile(); + + getFileRequest.setFileId(photos.get(0).getFileId()); + try { + + //we send a request with our fileId to get our filePath. + File file = getFile(getFileRequest); + + /* + * After that, we can now start to save them on our local machine. + * Please have a look on the API specification, on how to download the files with their filepaths you just got in the code above + * https://core.telegram.org/bots/api#file + * + * Just replace with File.getFilePath(); + */ + + // In this example, we just print here the filePaths + System.out.println(file.getFilePath()); + } catch (TelegramApiException e) { + //TODO: so some error handling + } + + } + + } + + } + + + } + +``` + Question: + How to send photos? + Answer: + + +```java + @Override + public void onUpdateReceived(Update update) { + + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + + //check if the message has text. it could also contain for example a location ( message.hasLocation() ) + if(message.hasText()){ + + if(message.getText().equals("/wiki")){ + + SendPhoto sendPhotoRequest = new SendPhoto(); + sendPhotoRequest.setChatId(message.getChatId().toString()); + + + //path: String, photoName: String + sendPhotoRequest.setNewPhoto("/home/marcel/Downloads/potd_wikipedia.jpg", "Good Friday.jpg"); // + try { + sendPhoto(sendPhotoRequest); + } catch (TelegramApiException e) { + /* + * Do some error handling + * e.printStackTrace(); + */ + } + + } + + } + } + + } +``` + + This method uploads the photo every time the user send the bot /wiki. Telegram stores the files we upload on their server. And if next time someone wants to retrieve THE SAME photo we uploaded some time ago, you should use instead of SendPhoto.setNewPhoto() the SendPhoto.setPhoto() method. This method has just one parameter, file_id. + + Question: + How to use custom keyboards? + Answer: +```java + //first, create a normal SendMessage object. Our CutsomKeyboard is attached to this object. But don't forget to assign a text. Otherwise the user get's no message +SendMessage sendMessageRequest = this.selectLanguage(); + + +sendMessageRequest.setChatId(message.getChatId().toString()); +sendMessageRequest.setText("Change language"); + +//ready top takeoff! +sendMessage(sendMessageRequest); +``` + +The selectLanguage() method could look like this (you also could put the code of the extra methode in your main() ) + +```java +public static List selectLanguage(Message message){ + + /* changed from "List>" to "List" + * Now we have just a one dimension array. Like a stack or something like that + */ + List rows = new ArrayList(); + rows.add(ReplyKeyboardFabricator.getHeader(message)); + + //Instead of a list that collects our strings, or "buttons" for each row, now we have a own Object for that + KeyboardRow row = new KeyboardRow(); + row.add(LocalisationService.getInstance().getString("change_language", DatabaseManager.getInstance().getUserLanguage(EchoHandler.getUserId(message)))); + rows.add(row); + + row = new KeyboardRow(); + row.add("🇦🇹 Deutsch (Östereich)"); + rows.add(row); + + //I just reused the object above. Of cource you could also create a new Keyboardrow for each real row + row = new KeyboardRow(); + row.add("🇩🇪 Deutsch (Deutschland)"); + rows.add(row); + + row = new KeyboardRow(); + row.add("🇧🇷 Português"); + rows.add(row); + + row = new KeyboardRow(); + row.add("🇺🇸 English (United States)"); + rows.add(row); + + return rows; + + } +``` + +For more example on this, please have a look at [this](https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java) bot in the example repo + + + Question: How can I compile my project? + Answer: This is just one way, how you can compile it (here with maven). The example below below is compiling the TelegramBotsExample repo. + [![asciicast](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj.png)](https://asciinema.org/a/4np9i2u9onuitkg287ism23kj) + + From b1b13efbbbfcb801ec3e0e02454e1b5d6a46dfe4 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Sun, 7 Aug 2016 05:46:41 +0200 Subject: [PATCH 74/85] Minor howto fixes --- HOWTO.md | 284 ++++++++++++++++++++++++------------------------------- 1 file changed, 125 insertions(+), 159 deletions(-) diff --git a/HOWTO.md b/HOWTO.md index bbd64b2f..50857c4b 100644 --- a/HOWTO.md +++ b/HOWTO.md @@ -1,4 +1,4 @@ -So, you just wanna program a own Telegram bot with @rubenlagus library TelegramBots? Then I'm going to show you how to start ;) +So, you just wanna program your own Telegram bot with @rubenlagus library TelegramBots? Then I'm going to show you how to start ;) ##### Table of Contents [Preperations](#preperations) @@ -13,103 +13,93 @@ So, you just wanna program a own Telegram bot with @rubenlagus library TelegramB ## Preperations -First you need to download the latest .jar from the Release site [here](https://github.com/rubenlagus/TelegramBots/releases). You can choose between Jar dependencies and wthout. If you don't know what to choose, we recommend to download the full jar with all dependencies ;) +First you need to download the latest .jar from the Release site [here](https://github.com/rubenlagus/TelegramBots/releases). You can choose between Jar with or without dependencies. If you don't know which one to choose, we recommend to download the full jar with all dependencies ;) Next, you need to integrate it into your project. Create a new project for your bot, in the example below we are showing you how to do it in eclipse. But of course, you are free to code in whatever IDE you want ;) -If you don't know how to include a external .jar into your Eclipse project, maybe [this](https://www.youtube.com/watch?v=VWnfHkBgO1I) video is helpfull for you +If you don't know how to include a external .jar into your Eclipse project, maybe [this](https://www.youtube.com/watch?v=VWnfHkBgO1I) video is helpful for you -More information on how to use it with Gradly or Maven, can you find here [here](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.4) +More information on how to use it with Gradle or Maven, can be found here [here](https://jitpack.io/#rubenlagus/TelegramBots) ## Let's code! -Create a new class that is extending one of the following +Create a new class that extends one of the following -```TelegramLongPollingBot``` -> bot is asking the Telegram servers continuously if new updates are available +```TelegramLongPollingBot``` -> bot is asking Telegram servers continuously if new updates are available -```TelegramWebhookBot``` -> our bot is "called" from the Telegram servers when updates are available +```TelegramWebhookBot``` -> our bot is "called" from Telegram servers when updates are available ```TelegramLongPollingCommandBot``` -> simply like TelegramLongPollingBot, but based around the idea of Commands +Due to the fact that the TelegramLongPollingBot is a little bit less complicated than the others, we are going to work with him in this example. -Due to the fact that the TelegramLongPollingBot is a little bit less complicated than the others, are we going to work with him in the following. +Extend ```TelegramLongPollingBot``` with one of your own classes. If we want that the bot can work normally, we must implement the following methods: ```getBotUsername():String```, ```getBotToken():String``` and ```onUpdateReceived(update: Update)``` - -Extend ```TelegramLongPollingBot``` with one of your own classes. If we want that the bot can work normally, we must implement the following methods: ```getBotUsername():String```, ```getBotToken():String``` und ```onUpdateReceived(update: Update)``` - -The first two methods are really easy to implement. Jus create a new class that contains all our informations for the bot (username, token and maybe in the future some database information) +The first two methods are really easy to implement. Just create a new class that contains all the information for the bot (username, token and maybe in the future some database information) At the end it could look like this: ```java public class BotConfig { - - public static final String BOT_USERNAME = "echoBot"; - - public static final String BOT_TOKEN = "{you secret bot token you got from the BotFather}"; - + public static final String BOT_USERNAME = "echoBot"; + public static final String BOT_TOKEN = "{you secret bot token that you got from BotFather}"; } ``` After it, return these static variables like this one: ```java @Override - public String getBotToken() { - return BotConfig.BOT_TOKEN; - } - +public String getBotToken() { + return BotConfig.BOT_TOKEN; +} ``` The last method could look like this: ```java @Override - public void onUpdateReceived(Update update) { - - //check if the update has a message - if(update.hasMessage()){ - Message message = update.getMessage(); - - //check if the message has text. it could also contain for example a location ( message.hasLocation() ) - if(message.hasText()){ - - //create a object that contains the information to send back the message - SendMessage sendMessageRequest = new SendMessage(); - sendMessageRequest.setChatId(message.getChatId().toString()); //who should get the message? the sender from which we got the message... - sendMessageRequest.setText("you said: " + message.getText()); - try { - sendMessage(sendMessageRequest); //at the end, so some magic and send the message ;) - } catch (TelegramApiException e) { - //do some error handling - } - } - } +public void onUpdateReceived(Update update) { + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + //check if the message has text. it could also contain for example a location ( message.hasLocation() ) + if(message.hasText()){ + //create an object that contains the information to send back the message + SendMessage sendMessageRequest = new SendMessage(); + sendMessageRequest.setChatId(message.getChatId().toString()); //who should get from the message the sender that sent it. + sendMessageRequest.setText("you said: " + message.getText()); + try { + sendMessage(sendMessageRequest); //at the end, so some magic and send the message ;) + } catch (TelegramApiException e) { + //do some error handling + } } + } +} ``` -The princip is rather easy, we have an ```update```, we see that it contains a text -> we create a Send*** object, fill it up with all necessary infos (user/chatId, text) and fire it up +The principle is rather easy, we have an ```update```, we see that it contains a text -> we create a Send*** object, fill it up with all necessary infos (user/chatId, text) and fire it up -If you want to send also other types of media (such as photos or audio), then check out our FAQ at the end if this HOWTO. Also please check out the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It contains usefull informations on how to use the lib from @rubenlagus. +If you want to send also other types of media (such as photos or audio), then check out our FAQ at the end if this HOWTO. Also please check out the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It contains useful information on how to use the lib from @rubenlagus. If you have questions that are not handled here or in the example repo, than feel free to open a new Issue :P -In any case, you can reach us in our chat at [our group chat](https://telegram.me/JavaBotsApi) ;) +In any case, you can reach us at [our Telegram group chat](https://telegram.me/JavaBotsApi) ;) -But to be in context: our bot is not ready, yet. It lacks of a used way to the tell lib that we have a super cool new UpdateHandler written, you remember? 😏 +But to be in context: our bot is not ready, yet. It lacks a way to tell the library that we have a super cool new UpdateHandler written, you remember? 😏 ```java public static void main(String[] args) { - - TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); - try { - telegramBotsApi.registerBot(new MyProjectHandler()); - } catch (TelegramApiException e) { - BotLogger.error(LOGTAG, e); - } + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + try { + telegramBotsApi.registerBot(new MyProjectHandler()); + } catch (TelegramApiException e) { + BotLogger.error(LOGTAG, e); } +} ``` @@ -120,54 +110,42 @@ public static void main(String[] args) { Answer: A ```onUpdateReceived()``` Method that just downloads every Photo that users send to the bot could look like this: ```java - @Override - public void onUpdateReceived(Update update) { - //check if the update has a message - if(update.hasMessage()){ - Message message = update.getMessage(); +@Override +public void onUpdateReceived(Update update) { + //check if the update has a message + if (update.hasMessage()) { + Message message = update.getMessage(); + //check if we got some photos + if (message.getPhoto() != null) { + /* + * Just save our received photos in a list. At this point, we do not really have the photos. We have just their id. + * And with their id's we can download them from Telegram servers + */ + for (int i = 0; i < photos.size(); i++) { + GetFile getFileRequest = new GetFile(); + getFileRequest.setFileId(photos.get(0).getFileId()); + try { - //check if we got some photos - if(message.getPhoto() != null){ + //we send a request with our fileId to get our filePath. + File file = getFile(getFileRequest); + /* + * After that, we can now start to save them on our local machine. + * Please have a look on the API specification, on how to download the files with their filepaths you just got in the code above + * https://core.telegram.org/bots/api#file + * + * Just replace with File.getFilePath(); + */ - /* - * Just save our received photos in a list. At this point, we do not really have the photos. We have just their id. - * And with their id's we can download them from telegram servers - */ - - for(int i = 0; i < photos.size(); i++){ - - GetFile getFileRequest = new GetFile(); - - getFileRequest.setFileId(photos.get(0).getFileId()); - try { - - //we send a request with our fileId to get our filePath. - File file = getFile(getFileRequest); - - /* - * After that, we can now start to save them on our local machine. - * Please have a look on the API specification, on how to download the files with their filepaths you just got in the code above - * https://core.telegram.org/bots/api#file - * - * Just replace with File.getFilePath(); - */ - - // In this example, we just print here the filePaths - System.out.println(file.getFilePath()); - } catch (TelegramApiException e) { - //TODO: so some error handling - } - - } - - } - - } - - - } - + // In this example, we just print here the filePaths + System.out.println(file.getFilePath()); + } catch (TelegramApiException e) { + //TODO: so some error handling + } + } + } + } +} ``` Question: How to send photos? @@ -175,39 +153,30 @@ public static void main(String[] args) { ```java - @Override - public void onUpdateReceived(Update update) { - - //check if the update has a message - if(update.hasMessage()){ - Message message = update.getMessage(); - - //check if the message has text. it could also contain for example a location ( message.hasLocation() ) - if(message.hasText()){ - - if(message.getText().equals("/wiki")){ - - SendPhoto sendPhotoRequest = new SendPhoto(); - sendPhotoRequest.setChatId(message.getChatId().toString()); - - - //path: String, photoName: String - sendPhotoRequest.setNewPhoto("/home/marcel/Downloads/potd_wikipedia.jpg", "Good Friday.jpg"); // - try { - sendPhoto(sendPhotoRequest); - } catch (TelegramApiException e) { - /* - * Do some error handling - * e.printStackTrace(); - */ - } - - } - - } - } - - } +@Override +public void onUpdateReceived(Update update) { + //check if the update has a message + if(update.hasMessage()){ + Message message = update.getMessage(); + //check if the message has text. it could also contain for example a location ( message.hasLocation() ) + if(message.hasText()){ + if(message.getText().equals("/wiki")){ + SendPhoto sendPhotoRequest = new SendPhoto(); + sendPhotoRequest.setChatId(message.getChatId().toString()); + //path: String, photoName: String + sendPhotoRequest.setNewPhoto("/home/marcel/Downloads/potd_wikipedia.jpg", "Good Friday.jpg"); // + try { + sendPhoto(sendPhotoRequest); + } catch (TelegramApiException e) { + /* + * Do some error handling + * e.printStackTrace(); + */ + } + } + } + } +} ``` This method uploads the photo every time the user send the bot /wiki. Telegram stores the files we upload on their server. And if next time someone wants to retrieve THE SAME photo we uploaded some time ago, you should use instead of SendPhoto.setNewPhoto() the SendPhoto.setPhoto() method. This method has just one parameter, file_id. @@ -216,10 +185,9 @@ public static void main(String[] args) { How to use custom keyboards? Answer: ```java - //first, create a normal SendMessage object. Our CutsomKeyboard is attached to this object. But don't forget to assign a text. Otherwise the user get's no message +//first, create a normal SendMessage object. Our CutsomKeyboard is attached to this object. But don't forget to assign a text. Otherwise the user get's no message SendMessage sendMessageRequest = this.selectLanguage(); - sendMessageRequest.setChatId(message.getChatId().toString()); sendMessageRequest.setText("Change language"); @@ -227,42 +195,40 @@ sendMessageRequest.setText("Change language"); sendMessage(sendMessageRequest); ``` -The selectLanguage() method could look like this (you also could put the code of the extra methode in your main() ) +The selectLanguage() method could look like this (you also could put the code of the extra method in your main() ) ```java public static List selectLanguage(Message message){ + /* changed from "List>" to "List" + * Now we have just a one dimension array. Like a stack or something like that + */ + List rows = new ArrayList(); + rows.add(ReplyKeyboardFabricator.getHeader(message)); - /* changed from "List>" to "List" - * Now we have just a one dimension array. Like a stack or something like that - */ - List rows = new ArrayList(); - rows.add(ReplyKeyboardFabricator.getHeader(message)); + //Instead of a list that collects our strings, or "buttons" for each row, now we have a own Object for that + KeyboardRow row = new KeyboardRow(); + row.add(LocalisationService.getInstance().getString("change_language", DatabaseManager.getInstance().getUserLanguage(EchoHandler.getUserId(message)))); + rows.add(row); - //Instead of a list that collects our strings, or "buttons" for each row, now we have a own Object for that - KeyboardRow row = new KeyboardRow(); - row.add(LocalisationService.getInstance().getString("change_language", DatabaseManager.getInstance().getUserLanguage(EchoHandler.getUserId(message)))); - rows.add(row); + row = new KeyboardRow(); + row.add("🇦🇹 Deutsch (Östereich)"); + rows.add(row); - row = new KeyboardRow(); - row.add("🇦🇹 Deutsch (Östereich)"); - rows.add(row); + //I just reused the object above. Of cource you could also create a new Keyboardrow for each real row + row = new KeyboardRow(); + row.add("🇩🇪 Deutsch (Deutschland)"); + rows.add(row); - //I just reused the object above. Of cource you could also create a new Keyboardrow for each real row - row = new KeyboardRow(); - row.add("🇩🇪 Deutsch (Deutschland)"); - rows.add(row); + row = new KeyboardRow(); + row.add("🇧🇷 Português"); + rows.add(row); - row = new KeyboardRow(); - row.add("🇧🇷 Português"); - rows.add(row); + row = new KeyboardRow(); + row.add("🇺🇸 English (United States)"); + rows.add(row); - row = new KeyboardRow(); - row.add("🇺🇸 English (United States)"); - rows.add(row); - - return rows; - - } + return rows; +} ``` For more example on this, please have a look at [this](https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java) bot in the example repo From b566ad9621b1df4c575a1fe2ae0ecde63e5c58cb Mon Sep 17 00:00:00 2001 From: Rumen Nikiforov Date: Sun, 7 Aug 2016 06:47:23 +0300 Subject: [PATCH 75/85] Fixing sending Files through InputStream causing exceptions. (#131) - Added proper methods to send Audio/Document/Photo/Sticker/Video/Voice through InputStream as it Telegram API requires file name to be specified. - Dropping not working methods that was using InputStream without name --- .../telegrambots/api/methods/send/SendAudio.java | 6 +++++- .../telegrambots/api/methods/send/SendDocument.java | 11 +++++------ .../telegrambots/api/methods/send/SendPhoto.java | 6 +++++- .../telegrambots/api/methods/send/SendSticker.java | 6 +++++- .../telegrambots/api/methods/send/SendVideo.java | 6 +++++- .../telegrambots/api/methods/send/SendVoice.java | 6 +++++- .../org/telegram/telegrambots/bots/AbsSender.java | 12 ++++++------ 7 files changed, 36 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java index a450b5d0..e3e1afe8 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendAudio.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; import java.io.InputStream; +import java.util.Objects; /** * @author Ruben Bermudez @@ -111,7 +112,10 @@ public class SendAudio { return this; } - public SendAudio setNewAudio(InputStream inputStream) { + public SendAudio setNewAudio(String audioName, InputStream inputStream) { + Objects.requireNonNull(audioName, "audioName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.audioName = audioName; this.isNewAudio = true; this.newAudioStream = inputStream; return this; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java index 9ab38fee..493e566f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendDocument.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; import java.io.InputStream; +import java.util.Objects; /** * @author Ruben Bermudez @@ -93,12 +94,10 @@ public class SendDocument { return this; } - /** - * Use this method to set the document to a new file - * - * @param inputStream New document file - */ - public SendDocument setNewDocument(InputStream inputStream) { + public SendDocument setNewDocument(String documentName, InputStream inputStream) { + Objects.requireNonNull(documentName, "documentName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.documentName = documentName; this.isNewDocument = true; this.newDocumentStream = inputStream; return this; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java index ecb89cf7..d4839fa7 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendPhoto.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; import java.io.InputStream; +import java.util.Objects; /** * @author Ruben Bermudez @@ -171,7 +172,10 @@ public class SendPhoto { return this; } - public SendPhoto setNewPhoto(InputStream inputStream) { + public SendPhoto setNewPhoto(String photoName, InputStream inputStream) { + Objects.requireNonNull(photoName, "photoName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.photoName = photoName; this.newPhotoStream = inputStream; this.isNewPhoto = true; return this; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java index 8a091729..2a06c9fb 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendSticker.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; import java.io.InputStream; +import java.util.Objects; /** * @author Ruben Bermudez @@ -130,7 +131,10 @@ public class SendSticker { return this; } - public SendSticker setNewSticker(InputStream inputStream) { + public SendSticker setNewSticker(String stickerName, InputStream inputStream) { + Objects.requireNonNull(stickerName, "stickerName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.stickerName = stickerName; this.isNewSticker = true; this.newStickerStream = inputStream; return this; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java index 393edf38..f354f503 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVideo.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; import java.io.InputStream; +import java.util.Objects; /** * @author Ruben Bermudez @@ -205,7 +206,10 @@ public class SendVideo { return this; } - public SendVideo setNewVideo(InputStream inputStream) { + public SendVideo setNewVideo(String videoName, InputStream inputStream) { + Objects.requireNonNull(videoName, "videoName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.videoName = videoName; this.isNewVideo = true; this.newVideoStream = inputStream; return this; diff --git a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java index 0c7fce91..3c8a865f 100644 --- a/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java +++ b/src/main/java/org/telegram/telegrambots/api/methods/send/SendVoice.java @@ -4,6 +4,7 @@ import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import java.io.File; import java.io.InputStream; +import java.util.Objects; /** * @author Ruben Bermudez @@ -144,7 +145,10 @@ public class SendVoice { return this; } - public SendVoice setNewVoice(InputStream inputStream) { + public SendVoice setNewVoice(String voiceName, InputStream inputStream) { + Objects.requireNonNull(voiceName, "voiceName cannot be null!"); + Objects.requireNonNull(inputStream, "inputStream cannot be null!"); + this.voiceName = voiceName; this.isNewVoice = true; this.newVoiceStream = inputStream; return this; diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index 2c1cd61b..a270898c 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -519,7 +519,7 @@ public abstract class AbsSender { if (sendDocument.getNewDocumentFile() != null) { builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentFile()); } else if (sendDocument.getNewDocumentStream() != null) { - builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentStream()); + builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, sendDocument.getNewDocumentStream(), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); } else { builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName()); } @@ -585,7 +585,7 @@ public abstract class AbsSender { if (sendPhoto.getNewPhotoFile() != null) { builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoFile()); } else if (sendPhoto.getNewPhotoStream() != null) { - builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoStream()); + builder.addBinaryBody(SendPhoto.PHOTO_FIELD, sendPhoto.getNewPhotoStream(), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); } else { builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName()); } @@ -651,7 +651,7 @@ public abstract class AbsSender { if (sendVideo.getNewVideoFile() != null) { builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoFile()); } else if (sendVideo.getNewVideoStream() != null) { - builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoStream()); + builder.addBinaryBody(SendVideo.VIDEO_FIELD, sendVideo.getNewVideoStream(), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); } else { builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName()); } @@ -736,7 +736,7 @@ public abstract class AbsSender { if (sendSticker.getNewStickerFile() != null) { builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerFile()); } else if (sendSticker.getNewStickerStream() != null) { - builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerStream()); + builder.addBinaryBody(SendSticker.STICKER_FIELD, sendSticker.getNewStickerStream(), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); } else { builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName()); } @@ -804,7 +804,7 @@ public abstract class AbsSender { if (sendAudio.getNewAudioFile() != null) { builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioFile()); } else if (sendAudio.getNewAudioStream() != null) { - builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioStream()); + builder.addBinaryBody(SendAudio.AUDIO_FIELD, sendAudio.getNewAudioStream(), ContentType.APPLICATION_OCTET_STREAM, sendAudio.getAudioName()); } else { builder.addBinaryBody(SendAudio.AUDIO_FIELD, new java.io.File(sendAudio.getAudio()), ContentType.create("audio/mpeg"), sendAudio.getAudioName()); } @@ -893,7 +893,7 @@ public abstract class AbsSender { if (sendVoice.getNewVoiceFile() != null) { builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceFile()); } else if (sendVoice.getNewVoiceStream() != null) { - builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceStream()); + builder.addBinaryBody(SendVoice.VOICE_FIELD, sendVoice.getNewVoiceStream(), ContentType.APPLICATION_OCTET_STREAM, sendVoice.getVoiceName()); } else { builder.addBinaryBody(SendVoice.VOICE_FIELD, new java.io.File(sendVoice.getVoice()), ContentType.create("audio/ogg"), sendVoice.getVoiceName()); } From 78bbe0b2c65d14139ebb4a5fafd2f0752aa01b55 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Sun, 7 Aug 2016 14:04:00 +0200 Subject: [PATCH 76/85] Closes #128 --- src/main/java/org/telegram/telegrambots/bots/AbsSender.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index a270898c..b56131c3 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -550,7 +550,7 @@ public abstract class AbsSender { if (sendDocument.getCaption() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.CAPTION_FIELD, sendDocument.getCaption())); } - if (sendDocument.getReplyToMessageId() != null) { + if (sendDocument.getDisableNotification() != null) { nameValuePairs.add(new BasicNameValuePair(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString())); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8)); From b039558c21f66d52a5f0cbf1049b493419cb7478 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Sun, 7 Aug 2016 14:24:10 +0200 Subject: [PATCH 77/85] Closes #126 --- .../telegrambots/bots/TelegramLongPollingCommandBot.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index e6d2b25f..d28d4947 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -50,7 +50,6 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB } /** - * function message filter. * Override this function in your bot implementation to filter messages with commands * * For example, if you want to prevent commands execution incoming from group chat: @@ -58,12 +57,13 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * # return !message.getChat().isGroupChat(); * # * + * @note Default implementation doesn't filter anything * @param message Received message * @return true if the message must be ignored by the command bot and treated as a non command message, * false otherwise */ protected boolean filter(Message message) { - return true; + return false; } @Override From 5db05165166d9df702794cde3f9133a93472fcfd Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Sun, 7 Aug 2016 14:34:27 +0200 Subject: [PATCH 78/85] Update version 2.3.3.7 --- README.md | 4 +++- pom.xml | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d058aefe..7048c3b9 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.6) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.6) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.7) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.7) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. @@ -46,6 +46,8 @@ Once done, you just need to create a `org.telegram.telegrambots.TelegramBotsApi` ``` +For detailed explanation, visite our [How To](HOWTO.md) (thanks Clevero) + ## Example bots Open them and send them */help* command to get some information about their capabilities: diff --git a/pom.xml b/pom.xml index e41e3a4f..c158fa39 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.6 + 2.3.3.7 Telegram Bots https://telegram.me/JavaBotsApi From f1cfe327eaadd7f168c4c6e6e0346e3f985a414b Mon Sep 17 00:00:00 2001 From: Clevero Date: Wed, 10 Aug 2016 00:09:14 +0200 Subject: [PATCH 79/85] Fix issue in HOWTO (#134) * Message filter for TelegramLongPollingCommandBot * Revert "Message filter for TelegramLongPollingCommandBot" * Fix issue in HOWTO I've removed the code for custom keyboards and linked to the weather bot in the example repo - it was not fully working (weatherbot is) - it was just an approach on how to use custom keyboards but was not showing all details (weatherbot has much more details) - why managing multiple code "snippets"? The code can change but the HOWTO still works --- HOWTO.md | 50 +------------------------------------------------- 1 file changed, 1 insertion(+), 49 deletions(-) diff --git a/HOWTO.md b/HOWTO.md index 50857c4b..fac0dc7b 100644 --- a/HOWTO.md +++ b/HOWTO.md @@ -183,55 +183,7 @@ public void onUpdateReceived(Update update) { Question: How to use custom keyboards? - Answer: -```java -//first, create a normal SendMessage object. Our CutsomKeyboard is attached to this object. But don't forget to assign a text. Otherwise the user get's no message -SendMessage sendMessageRequest = this.selectLanguage(); - -sendMessageRequest.setChatId(message.getChatId().toString()); -sendMessageRequest.setText("Change language"); - -//ready top takeoff! -sendMessage(sendMessageRequest); -``` - -The selectLanguage() method could look like this (you also could put the code of the extra method in your main() ) - -```java -public static List selectLanguage(Message message){ - /* changed from "List>" to "List" - * Now we have just a one dimension array. Like a stack or something like that - */ - List rows = new ArrayList(); - rows.add(ReplyKeyboardFabricator.getHeader(message)); - - //Instead of a list that collects our strings, or "buttons" for each row, now we have a own Object for that - KeyboardRow row = new KeyboardRow(); - row.add(LocalisationService.getInstance().getString("change_language", DatabaseManager.getInstance().getUserLanguage(EchoHandler.getUserId(message)))); - rows.add(row); - - row = new KeyboardRow(); - row.add("🇦🇹 Deutsch (Östereich)"); - rows.add(row); - - //I just reused the object above. Of cource you could also create a new Keyboardrow for each real row - row = new KeyboardRow(); - row.add("🇩🇪 Deutsch (Deutschland)"); - rows.add(row); - - row = new KeyboardRow(); - row.add("🇧🇷 Português"); - rows.add(row); - - row = new KeyboardRow(); - row.add("🇺🇸 English (United States)"); - rows.add(row); - - return rows; -} -``` - -For more example on this, please have a look at [this](https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java) bot in the example repo + Answer: You can look at the [source code](https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java) for [@Weatherbot](https://telegram.me/weatherbot) in the [TelegramBotsExample](https://github.com/rubenlagus/TelegramBotsExample) repo. It should contain all necessary information about using custom keyboards. Question: How can I compile my project? From 6421d624c8a2fe2abf095632f9fbd91c737dab7d Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 12 Aug 2016 21:23:30 +0200 Subject: [PATCH 80/85] Add Get webhook information method --- .../api/methods/updates/GetWebhookInfo.java | 64 +++++++++++++ .../telegrambots/api/objects/WebhookInfo.java | 94 +++++++++++++++++++ .../telegram/telegrambots/bots/AbsSender.java | 17 +++- 3 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java create mode 100644 src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java diff --git a/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java b/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java new file mode 100644 index 00000000..ef89fc24 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/methods/updates/GetWebhookInfo.java @@ -0,0 +1,64 @@ +package org.telegram.telegrambots.api.methods.updates; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; + +import org.json.JSONObject; +import org.telegram.telegrambots.Constants; +import org.telegram.telegrambots.api.methods.BotApiMethod; +import org.telegram.telegrambots.api.objects.WebhookInfo; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.1 + * @brief Return webhook information for current bot. + * + * If webhook is not configured, this method raise an exception + * + * @date 12 of August of 2016 + */ +public class GetWebhookInfo extends BotApiMethod { + public static final String PATH = "getwebhookinfo"; + + public GetWebhookInfo() { + } + + @Override + public String toString() { + return "GetWebhookInfo{}"; + } + + @Override + public String getPath() { + return PATH; + } + + @Override + public WebhookInfo deserializeResponse(JSONObject answer) { + if (answer.getBoolean(Constants.RESPONSEFIELDOK)) { + return new WebhookInfo(answer.getJSONObject(Constants.RESPONSEFIELDRESULT)); + } + return null; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(METHOD_FIELD, PATH); + gen.writeEndObject(); + gen.flush(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } + + @Override + public JSONObject toJson() { + return new JSONObject(); + } +} diff --git a/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java b/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java new file mode 100644 index 00000000..63fc70f9 --- /dev/null +++ b/src/main/java/org/telegram/telegrambots/api/objects/WebhookInfo.java @@ -0,0 +1,94 @@ +package org.telegram.telegrambots.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; + +import org.json.JSONObject; +import org.telegram.telegrambots.api.interfaces.IBotApiObject; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.1 + * @brief Information about configured webhook + * @date 12 of August of 2016 + */ +public class WebhookInfo implements IBotApiObject { + + private static final String URL_FIELD = "url"; + private static final String HASCUSTOMCERTIFICATE_FIELD = "has_custom_certificate"; + private static final String PENDINGUPDATESCOUNT_FIELD = "pending_updates_count"; + private static final String LASTERRORDATE_FIELD = "last_error_date"; + private static final String LASTERRORMESSAGE_FIELD = "last_error_message"; + + @JsonProperty(URL_FIELD) + private String url; ///< Url of the webhook + @JsonProperty(HASCUSTOMCERTIFICATE_FIELD) + private Boolean hasCustomCertificate; ///< True if the webhook use a self signed certificate + @JsonProperty(PENDINGUPDATESCOUNT_FIELD) + private Integer pendingUpdatesCount; ///< Number of updates pending to be delivered + @JsonProperty(LASTERRORDATE_FIELD) + private Integer lastErrorDate; ///< Optional. Date of that error + @JsonProperty(LASTERRORMESSAGE_FIELD) + private String lastErrorMessage; ///< Optional. Error message + + + public WebhookInfo() { + } + + public WebhookInfo(JSONObject object) { + url = object.getString(URL_FIELD); + hasCustomCertificate = object.getBoolean(HASCUSTOMCERTIFICATE_FIELD); + pendingUpdatesCount = object.getInt(PENDINGUPDATESCOUNT_FIELD); + if (object.has(LASTERRORDATE_FIELD)) { + lastErrorDate = object.getInt(LASTERRORDATE_FIELD); + } + if (object.has(LASTERRORMESSAGE_FIELD)) { + lastErrorMessage = object.getString(LASTERRORMESSAGE_FIELD); + } + + } + + public String getUrl() { + return url; + } + + public boolean isHasCustomCertificate() { + return hasCustomCertificate; + } + + public int getPendingUpdatesCount() { + return pendingUpdatesCount; + } + + public int getLastErrorDate() { + return lastErrorDate; + } + + public String getLastErrorMessage() { + return lastErrorMessage; + } + + @Override + public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + gen.writeStringField(URL_FIELD, url); + gen.writeBooleanField(HASCUSTOMCERTIFICATE_FIELD, hasCustomCertificate); + gen.writeNumberField(PENDINGUPDATESCOUNT_FIELD, pendingUpdatesCount); + if (lastErrorDate != null) { + gen.writeNumberField(LASTERRORDATE_FIELD, lastErrorDate); + } + if (lastErrorMessage != null) { + gen.writeStringField(LASTERRORMESSAGE_FIELD, lastErrorMessage); + } + gen.writeEndObject(); + } + + @Override + public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { + serialize(gen, serializers); + } +} diff --git a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java index b56131c3..c88b0575 100644 --- a/src/main/java/org/telegram/telegrambots/bots/AbsSender.java +++ b/src/main/java/org/telegram/telegrambots/bots/AbsSender.java @@ -44,6 +44,7 @@ import org.telegram.telegrambots.api.methods.send.SendSticker; import org.telegram.telegrambots.api.methods.send.SendVenue; import org.telegram.telegrambots.api.methods.send.SendVideo; import org.telegram.telegrambots.api.methods.send.SendVoice; +import org.telegram.telegrambots.api.methods.updates.GetWebhookInfo; import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageCaption; import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageReplyMarkup; import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText; @@ -53,6 +54,7 @@ import org.telegram.telegrambots.api.objects.File; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.User; import org.telegram.telegrambots.api.objects.UserProfilePhotos; +import org.telegram.telegrambots.api.objects.WebhookInfo; import org.telegram.telegrambots.updateshandlers.SentCallback; import java.io.IOException; @@ -270,6 +272,11 @@ public abstract class AbsSender { return sendApiMethod(getMe); } + public final WebhookInfo getWebhookInfo() throws TelegramApiException { + GetWebhookInfo getWebhookInfo = new GetWebhookInfo(); + return sendApiMethod(getWebhookInfo); + } + // Send Requests Async public final void sendMessageAsync(SendMessage sendMessage, SentCallback sentCallback) throws TelegramApiException { @@ -428,7 +435,6 @@ public abstract class AbsSender { sendApiMethodAsync(getChatMemberCount, sentCallback); } - public final void editMessageTextAsync(EditMessageText editMessageText, SentCallback sentCallback) throws TelegramApiException { if (editMessageText == null) { throw new TelegramApiException("Parameter editMessageText can not be null"); @@ -504,6 +510,15 @@ public abstract class AbsSender { sendApiMethodAsync(getMe, sentCallback); } + public final void getWebhookInfoAsync(SentCallback sentCallback) throws TelegramApiException { + if (sentCallback == null) { + throw new TelegramApiException("Parameter sentCallback can not be null"); + } + + GetWebhookInfo getWebhookInfo = new GetWebhookInfo(); + sendApiMethodAsync(getWebhookInfo, sentCallback); + } + // Specific Send Requests public final Message sendDocument(SendDocument sendDocument) throws TelegramApiException { From c53686dbc3b84b86de16f0ea5e8d7a4c13458ed1 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Fri, 12 Aug 2016 21:24:51 +0200 Subject: [PATCH 81/85] Update to version 2.3.4 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7048c3b9..ecc0533b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.3.7) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.3.7) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.4) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.4) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/pom.xml b/pom.xml index c158fa39..a7e72bf0 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.3.7 + 2.3.4 Telegram Bots https://telegram.me/JavaBotsApi From add72983a377d25ee352dacc3e2413af71cc9b22 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Wed, 24 Aug 2016 23:08:56 +0200 Subject: [PATCH 82/85] Closes #136 --- .../bots/TelegramLongPollingCommandBot.java | 19 ++++++++++--- .../bots/commands/CommandRegistry.java | 27 ++++++++++++++++++- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java index d28d4947..b3b31cef 100644 --- a/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java +++ b/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingCommandBot.java @@ -20,7 +20,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB private final CommandRegistry commandRegistry; /** - * construct creates CommandRegistry for this bot. + * Creates a TelegramLongPollingCommandBot using default options * Use ICommandRegistry's methods on this bot to register commands */ public TelegramLongPollingCommandBot() { @@ -28,12 +28,25 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB } /** - * construct creates CommandRegistry for this bot. + * Creates a TelegramLongPollingCommandBot with custom options and allowing commands with + * usernames * Use ICommandRegistry's methods on this bot to register commands + * @param options Bot options */ public TelegramLongPollingCommandBot(BotOptions options) { + this(options, true); + } + + /** + * Creates a TelegramLongPollingCommandBot + * Use ICommandRegistry's methods on this bot to register commands + * @param options Bot options + * @param allowCommandsWithUsername true to allow commands with parameters (default), + * false otherwise + */ + public TelegramLongPollingCommandBot(BotOptions options, boolean allowCommandsWithUsername) { super(options); - this.commandRegistry = new CommandRegistry(); + this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, getBotUsername()); } @Override diff --git a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java index bdc75e6d..e43c273b 100644 --- a/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java +++ b/src/main/java/org/telegram/telegrambots/bots/commands/CommandRegistry.java @@ -17,8 +17,20 @@ import java.util.function.BiConsumer; public final class CommandRegistry implements ICommandRegistry { private final Map commandRegistryMap = new HashMap<>(); + private final boolean allowCommandsWithUsername; + private final String botUsername; private BiConsumer defaultConsumer; + /** + * Creates a Command registry + * @param allowCommandsWithUsername True to allow commands with username, false otherwise + * @param botUsername Bot username + */ + public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) { + this.allowCommandsWithUsername = allowCommandsWithUsername; + this.botUsername = botUsername; + } + @Override public void registerDefaultAction(BiConsumer defaultConsumer) { this.defaultConsumer = defaultConsumer; @@ -87,7 +99,7 @@ public final class CommandRegistry implements ICommandRegistry { String commandMessage = text.substring(1); String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR); - String command = commandSplit[0]; + String command = removeUsernameFromCommandIfNeeded(commandSplit[0]); if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); @@ -101,4 +113,17 @@ public final class CommandRegistry implements ICommandRegistry { } return false; } + + /** + * if {@link #allowCommandsWithUsername} is enabled, the username of the bot is removed from + * the command + * @param command Command to simplify + * @return Simplified command + */ + private String removeUsernameFromCommandIfNeeded(String command) { + if (allowCommandsWithUsername) { + return command.replace("@" + botUsername, "").trim(); + } + return command; + } } \ No newline at end of file From 52919f2c0430e2e751f88cb5b379c0af633f791b Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Wed, 24 Aug 2016 23:21:24 +0200 Subject: [PATCH 83/85] Fix problem with proxy while setting webhook (#138) --- .../telegrambots/TelegramBotsApi.java | 86 +++++++++++-------- 1 file changed, 52 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java index 4b280b69..0f0577f8 100644 --- a/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java +++ b/src/main/java/org/telegram/telegrambots/TelegramBotsApi.java @@ -1,6 +1,8 @@ package org.telegram.telegrambots; import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.NoopHostnameVerifier; @@ -13,6 +15,7 @@ import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import org.telegram.telegrambots.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.bots.BotOptions; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramWebhookBot; import org.telegram.telegrambots.updatesreceivers.BotSession; @@ -33,11 +36,12 @@ import static org.telegram.telegrambots.Constants.ERRORDESCRIPTIONFIELD; * @date 14 of January of 2016 */ public class TelegramBotsApi { + private static final int SOCKET_TIMEOUT = 75 * 1000; private static final String webhookUrlFormat = "{0}callback/"; - private boolean useWebhook; ///< - private Webhook webhook; ///< - private String extrenalUrl; ///< - private String pathToCertificate; ///< + private boolean useWebhook; ///< True to enable webhook usage + private Webhook webhook; ///< Webhook instance + private String extrenalUrl; ///< External url of the bots + private String pathToCertificate; ///< Path to public key certificate /** * @@ -88,6 +92,26 @@ public class TelegramBotsApi { webhook.startServer(); } + /** + * Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. + * @param bot the bot to register + */ + public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { + setWebhook(bot.getBotToken(), null, bot.getOptions()); + return new BotSession(bot.getBotToken(), bot, bot.getOptions()); + } + + /** + * + * @param bot + */ + public void registerBot(TelegramWebhookBot bot) throws TelegramApiException { + if (useWebhook) { + webhook.registerWebhook(bot); + setWebhook(bot.getBotToken(), bot.getBotPath(), bot.getOptions()); + } + } + /** * * @param externalUrl @@ -101,17 +125,29 @@ public class TelegramBotsApi { } /** - * - * @param webHookURL - * @param botToken - * @param publicCertificatePath - * @throws TelegramApiException + * Set webhook or remove it if necessary + * @param webHookURL Webhook url or empty is removing it + * @param botToken Bot token + * @param publicCertificatePath Path to certificate public key + * @param options Bot options + * @throws TelegramApiException If any error occurs setting the webhook */ - private static void setWebhook(String webHookURL, String botToken, String publicCertificatePath) throws TelegramApiException { + private static void setWebhook(String webHookURL, String botToken, + String publicCertificatePath, BotOptions options) throws TelegramApiException { try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) { String url = Constants.BASEURL + botToken + "/" + SetWebhook.PATH; + RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.custom().build()) + .setSocketTimeout(SOCKET_TIMEOUT) + .setConnectTimeout(SOCKET_TIMEOUT) + .setConnectionRequestTimeout(SOCKET_TIMEOUT); + + if (options.hasProxy()) { + configBuilder.setProxy(new HttpHost(options.getProxyHost(), options.getProxyPort())); + } + HttpPost httppost = new HttpPost(url); + httppost.setConfig(configBuilder.build()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(SetWebhook.URL_FIELD, webHookURL); if (publicCertificatePath != null) { @@ -139,34 +175,16 @@ public class TelegramBotsApi { } /** - * Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. - * @param bot the bot to register + * Set the webhook or remove it if necessary + * @param botToken Bot token + * @param urlPath Url for the webhook or null to remove it + * @param botOptions Bot Options */ - public BotSession registerBot(TelegramLongPollingBot bot) throws TelegramApiException { - setWebhook(bot.getBotToken(), null); - return new BotSession(bot.getBotToken(), bot, bot.getOptions()); - } - - /** - * - * @param bot - */ - public void registerBot(TelegramWebhookBot bot) throws TelegramApiException { - if (useWebhook) { - webhook.registerWebhook(bot); - setWebhook(bot.getBotToken(), bot.getBotPath()); - } - } - - /** - * - * @param botToken - */ - private void setWebhook(String botToken, String urlPath) throws TelegramApiException { + private void setWebhook(String botToken, String urlPath, BotOptions botOptions) throws TelegramApiException { if (botToken == null) { throw new TelegramApiException("Parameter botToken can not be null"); } String completeExternalUrl = urlPath == null ? "" : extrenalUrl + urlPath; - setWebhook(completeExternalUrl, botToken, pathToCertificate); + setWebhook(completeExternalUrl, botToken, pathToCertificate, botOptions); } } From 2acb9d13c62fc15270231b8608777c1b1d4086e2 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 25 Aug 2016 17:29:19 +0200 Subject: [PATCH 84/85] Fix typo (#139) --- HOWTO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HOWTO.md b/HOWTO.md index fac0dc7b..c4a31f9d 100644 --- a/HOWTO.md +++ b/HOWTO.md @@ -123,7 +123,7 @@ public void onUpdateReceived(Update update) { */ for (int i = 0; i < photos.size(); i++) { GetFile getFileRequest = new GetFile(); - getFileRequest.setFileId(photos.get(0).getFileId()); + getFileRequest.setFileId(photos.get(i).getFileId()); try { //we send a request with our fileId to get our filePath. From b7cbbaae424fee372e5160d5f78dd8d38137b850 Mon Sep 17 00:00:00 2001 From: Rubenlagus Date: Thu, 25 Aug 2016 17:31:22 +0200 Subject: [PATCH 85/85] Update version 2.3.5 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ecc0533b..e6456a41 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Both ways are supported, but I recommend long polling method. ## Usage -Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.4) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.4) +Just import add the library to your project using [Maven, Gradle, ...](https://jitpack.io/#rubenlagus/TelegramBots/v2.3.5) or download the jar(including all dependencies) from [here](https://github.com/rubenlagus/TelegramBots/releases/tag/v2.3.5) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/pom.xml b/pom.xml index a7e72bf0..a78d0f91 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar org.telegram telegrambots - 2.3.4 + 2.3.5 Telegram Bots https://telegram.me/JavaBotsApi