Telegram Bot Java Library
repository·master·Indexed 26 days ago
https://github.com/rubenlagus/telegrambotsA Java library providing a high-level wrapper around the official Telegram Bot API to simplify the creation and management of Telegram bots. It supports Long Polling (GetUpdates) and Webhooks, and includes the AbilityBot abstraction for defining bot features as Ability objects. The library also offers extensions for custom bot commands via BotCommand and CommandRegistry, as well as a pre-built HelpCommand for automated command documentation.
What's inside telegrambots
- The Telegram Bot Java Library is a simple-to-use library designed for creating Telegram Bots using the Java programming language. It interfaces directly with the official Telegram Bot API.
Core features of AbilityBot
masterThe
AbilityBotabstraction provides several built-in management features:- Per-Ability Settings: Define argument length, privacy, and locality per method.
- Embedded Database: Automatically available for every declared ability to manage state.
- User Management: Automatically maintains an up-to-date set of users (updates usernames/names in the DB) and supports banning/unbanning users.
- Admin Management: Tools to promote or demote users to bot administrators.
- Backup & Recovery: The embedded database supports backup and recovery, with a default implementation using JSON/Jackson.
- Testability: Uses a proxy sender interface to enhance unit testing capabilities.
Create an Ability using the AbilityBot abstraction
masterThe
AbilityBotabstraction allows you to define bot features asAbilityobjects using a builder pattern. This reduces boilerplate compared to the basic API by centralizing command logic, privacy settings, and input requirements.An
Abilityconsists of:.name(String): The command name..info(String): Description of the command..input(int): Number of required arguments (use0for no arguments)..locality(Locality): Where the ability is available (USER,GROUP, orALL)..privacy(Privacy): Access level (CREATOR,ADMIN, orPUBLIC)..action(Consumer<MessageContext>): The main logic, receiving aMessageContextwhich provides access tochatId,user, and the underlyingupdate..post(Consumer<MessageContext>): Logic executed after the main action completes.
public Ability sayHelloWorld() { return Ability .builder() .name("hello") .info("says hello world!") .input(0) .locality(USER) .privacy(ADMIN) .action(ctx -> sender.send("Hello world!", ctx.chatId())) .post(ctx -> sender.send("Bye world!", ctx.chatId())) .build(); }Choose between Webhooks and GetUpdates
masterThe library supports two methods for receiving updates from Telegram:
- Long Polling (GetUpdates): The library periodically requests updates from the Telegram server. This is the recommended method for most use cases.
- Webhooks: Telegram pushes updates to a specified URL on your server. This is useful for high-scale applications but requires a public URL and SSL.
Install Telegram Bot Extensions
masterTo use the Telegram Bot Extensions, which provide additional functionality to the default Telegram Bots library implementation, add the dependency to your project using Maven or Gradle.
<!-- Maven --> <dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots-extensions</artifactId> <version>10.1.1</version> </dependency> <!-- Gradle --> implementation 'org.telegram:telegrambots-extensions:10.1.1'Explore Telegram Bot capabilities via examples
masterYou can explore different bot features by interacting with these live bots on Telegram. Send the
/helpcommand to any of them to see what they can do:- Custom Keyboards: @weatherbot
- Basic Messages: @directionsbot
- Sending files by
file_id: @filesbot - Uploading and sending files: @TGlanguagesbot
- Inline Mode support: @RaeBot
- Webhook support: @SnowcrashBot
For the source code implementation of these bots, refer to the TelegramBotsExample repository.
Configure Ability Locality and Privacy
masterWhen building an
Ability, you can control where it is accessible and who can use it using the following settings:Locality (Where the ability is available):
USER: Private chats only.GROUP: Group chats only.ALL: Both private and group chats.
Privacy (Who can access the ability):
CREATOR: Only the bot creator.ADMIN: Bot administrators.PUBLIC: Everyone.
Retrieve the bot's current command list with GetMyCommands
masterUse the
GetMyCommandsmethod to retrieve the current list of commands available to the bot for a specific scope and user language. On success, it returns anArrayList<BotCommand>. If no commands are set, an empty list is returned.Parameters
Parameter Type Description scopeBotCommandScopeOptional. A JSON-serialized object describing the scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.languageCodeStringOptional. A two-letter ISO 639-1 language code. If empty, commands apply to all users in the given scope for whom there are no dedicated commands. Note: An empty string is invalid and will trigger a TelegramApiValidationException.Define the scope of bot commands using BotCommandScope
masterThe
BotCommandScopeinterface is used to define the scope to which bot commands are applied. When setting commands, you can specify different scopes to control which users or chats see specific command menus.Supported Scopes
BotCommandScopeDefault(type:default)BotCommandScopeAllPrivateChats(type:all_private_chats)BotCommandScopeAllGroupChats(type:all_group_chats)BotCommandScopeAllChatAdministrators(type:all_chat_administrators)BotCommandScopeChat(type:chat)BotCommandScopeChatAdministrators(type:chat_administrators)BotCommandScopeChatMember(type:chat_member)
Command Resolution Algorithm
Telegram determines which commands a user sees by checking scopes in a specific order. The first non-empty list found is returned.
For Private Chats:
BotCommandScopeChat(withlanguage_codeif available)BotCommandScopeAllPrivateChats(withlanguage_codeif available)BotCommandScopeDefault(withlanguage_codeif available)
For Group and Supergroup Chats:
BotCommandScopeChatMember(withlanguage_code)BotCommandScopeChatAdministrators(withlanguage_code, admins only)BotCommandScopeChat(withlanguage_code)BotCommandScopeAllChatAdministrators(withlanguage_code, admins only)BotCommandScopeAllGroupChats(withlanguage_code)BotCommandScopeDefault(withlanguage_code)
Execute Commands from Messages
masterTo process an incoming Telegram message as a command, call
executeCommand(Message message).This method:
- Checks if the message contains text starting with the command initialization character (defined by
BotCommand.COMMAND_INIT_CHARACTER). - Splits the text into the command identifier and parameters using the separator defined by
BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP. - If
allowCommandsWithUsernamewas enabled during initialization, it strips the bot's username from the command. - If a matching
IBotCommandis found, it callsprocessMessageon that command. - If no match is found but a default consumer is registered, it executes the default consumer.
Returns
trueif a command or the default action was executed,falseotherwise.- Checks if the message contains text starting with the command initialization character (defined by
Initialize CommandRegistry
masterTo manage bot commands, instantiate
CommandRegistrywith aTelegramClient, a boolean flag for username handling, and aSupplier<String>that provides the bot's username.Setting
allowCommandsWithUsernametotrueallows the bot to process commands even when they are prefixed with the bot's username (e.g.,/start@my_bot).Configure a Default Action for Unrecognized Commands
masterYou can define a fallback action that executes when a user sends a command that is not found in the registry. UseregisterDefaultAction(BiConsumer<TelegramClient, Message> defaultConsumer)to set this. The consumer receives theTelegramClientand the incomingMessage.