Telegram Bot Java Library

repository·master·Indexed 26 days ago

https://github.com/rubenlagus/telegrambots

A 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.

Tokens
4.9K
Snippets
2
Records
32
Agent score
90%

What's inside telegrambots

  1. Core features of AbilityBot

    master

    The AbilityBot abstraction 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.
  2. Create an Ability using the AbilityBot abstraction

    master

    The AbilityBot abstraction allows you to define bot features as Ability objects using a builder pattern. This reduces boilerplate compared to the basic API by centralizing command logic, privacy settings, and input requirements.

    An Ability consists of:

    • .name(String): The command name.
    • .info(String): Description of the command.
    • .input(int): Number of required arguments (use 0 for no arguments).
    • .locality(Locality): Where the ability is available (USER, GROUP, or ALL).
    • .privacy(Privacy): Access level (CREATOR, ADMIN, or PUBLIC).
    • .action(Consumer<MessageContext>): The main logic, receiving a MessageContext which provides access to chatId, user, and the underlying update.
    • .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();
    }
  3. Choose between Webhooks and GetUpdates

    master

    The library supports two methods for receiving updates from Telegram:

    1. Long Polling (GetUpdates): The library periodically requests updates from the Telegram server. This is the recommended method for most use cases.
    2. 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.
  4. Install Telegram Bot Extensions

    master

    To 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'
  5. Explore Telegram Bot capabilities via examples

    master

    You can explore different bot features by interacting with these live bots on Telegram. Send the /help command to any of them to see what they can do:

    For the source code implementation of these bots, refer to the TelegramBotsExample repository.

  6. Configure Ability Locality and Privacy

    master

    When 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.
  7. Retrieve the bot's current command list with GetMyCommands

    master

    Use the GetMyCommands method to retrieve the current list of commands available to the bot for a specific scope and user language. On success, it returns an ArrayList<BotCommand>. If no commands are set, an empty list is returned.

    Parameters

    ParameterTypeDescription
    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.
  8. Define the scope of bot commands using BotCommandScope

    master

    The BotCommandScope interface 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:

    1. BotCommandScopeChat (with language_code if available)
    2. BotCommandScopeAllPrivateChats (with language_code if available)
    3. BotCommandScopeDefault (with language_code if available)

    For Group and Supergroup Chats:

    1. BotCommandScopeChatMember (with language_code)
    2. BotCommandScopeChatAdministrators (with language_code, admins only)
    3. BotCommandScopeChat (with language_code)
    4. BotCommandScopeAllChatAdministrators (with language_code, admins only)
    5. BotCommandScopeAllGroupChats (with language_code)
    6. BotCommandScopeDefault (with language_code)
  9. Execute Commands from Messages

    master

    To process an incoming Telegram message as a command, call executeCommand(Message message).

    This method:

    1. Checks if the message contains text starting with the command initialization character (defined by BotCommand.COMMAND_INIT_CHARACTER).
    2. Splits the text into the command identifier and parameters using the separator defined by BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP.
    3. If allowCommandsWithUsername was enabled during initialization, it strips the bot's username from the command.
    4. If a matching IBotCommand is found, it calls processMessage on that command.
    5. If no match is found but a default consumer is registered, it executes the default consumer.

    Returns true if a command or the default action was executed, false otherwise.

  10. Initialize CommandRegistry

    master

    To manage bot commands, instantiate CommandRegistry with a TelegramClient, a boolean flag for username handling, and a Supplier<String> that provides the bot's username.

    Setting allowCommandsWithUsername to true allows the bot to process commands even when they are prefixed with the bot's username (e.g., /start@my_bot).

  11. Configure a Default Action for Unrecognized Commands

    master
    You can define a fallback action that executes when a user sends a command that is not found in the registry. Use registerDefaultAction(BiConsumer<TelegramClient, Message> defaultConsumer) to set this. The consumer receives the TelegramClient and the incoming Message.