telegram-bot-ruby

repository·master·Indexed 23 days ago

https://github.com/atipugin/telegram-bot-ruby

A Ruby wrapper for the Telegram Bot API providing a high-level interface for building bots. It supports long polling, webhooks, custom reply and inline keyboards, and inline bot implementation. The library includes a client for handling updates via `Telegram::Bot::Client.run` and a low-level API client `Telegram::Bot::Api` that allows invoking Telegram endpoints using snake_case methods.

Tokens
4K
Snippets
10
Records
22
Agent score
80%

What's inside telegram-bot-ruby

  1. Install telegram-bot-ruby

    master

    You can install the gem using Bundler or by installing it system-wide.

    To use with Bundler, add this to your Gemfile:

    gem 'telegram-bot-ruby', '~> 2.8'

    Then run bundle.

    To install system-wide, use:

    gem install telegram-bot-ruby
    gem 'telegram-bot-ruby', '~> 2.8'
  2. Basic usage with Telegram::Bot::Client.run

    master

    The simplest way to start a bot is using Telegram::Bot::Client.run. This method starts a long-polling loop that listens for updates. Inside the block, you can use bot.listen to handle incoming messages.

    Note that bot.api implements the Telegram Bot API methods directly. You can call these methods using either snake_case or camelCase.

    To run in development/test mode, pass environment: :test to the run method.

    require 'telegram/bot'
    
    token = 'YOUR_TELEGRAM_BOT_API_TOKEN'
    
    Telegram::Bot::Client.run(token) do |bot|
      bot.listen do |message|
        case message.text
        when '/start'
          bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}")
        when '/stop'
          bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}")
        end
      end
    end
  3. Gracefully stop the bot

    master

    To ensure the bot stops gracefully (e.g., when receiving an INT signal like Ctrl-C), instantiate the client manually and call bot.stop within a signal trap.

    bot = Telegram::Bot::Client.new(token)
    
    Signal.trap('INT') do
      bot.stop
    end
    
    bot.listen do |message|
      # bot will loop until bot.stop is called
    end
  4. Configure a Proxy

    master

    If you need to access the Telegram API through a proxy, you can configure the url or use a specific adapter like Excon for SOCKS5 support.

    To set a custom API URL:

    Telegram::Bot::Client.run(token, url: 'https://proxy.example.com') do |bot|
      # ...
    end

    To use a SOCKS5 proxy with the Excon adapter:

    Telegram::Bot.configure do |config|
      config.adapter = :excon
      config.adapter_options = { socks5_proxy: 'socks5://socks.proxy:1080' }
    end
    Telegram::Bot.configure do |config|
      config.adapter = :excon
      config.adapter_options = { socks5_proxy: 'socks5://socks.proxy:1080' }
    end
  5. Configure Logging

    master

    By default, the bot uses NullLogger. You can provide your own logger (e.g., a standard Ruby Logger) when starting the client.

    Telegram::Bot::Client.run(token, logger: Logger.new($stderr)) do |bot|
      bot.logger.info('Bot has been started')
      bot.listen do |message|
        # ...
      end
    end
  6. Configure Connection Adapters

    master

    The library uses faraday under the hood. You can change the adapter or pass additional configuration options via Telegram::Bot.configure.

    require 'net/http/persistent'
    
    Telegram::Bot.configure do |config|
      config.adapter = :net_http_persistent
    end
    
    # With additional options:
    Telegram::Bot.configure do |config|
      config.adapter = :httpx
      config.adapter_options = { persistent: false }
    end
  7. Initialize and run a Telegram Bot

    master

    To start a bot, you can use the Telegram::Bot::Client.run class method or instantiate Telegram::Bot::Client.new and call .run.

    When initializing, you must provide your Telegram Bot Token. You can also pass an optional hash of configuration options.

    Common configuration options include:

    • :url: The base URL for the Telegram API (defaults to https://api.telegram.org).
    • :environment: The environment setting (defaults to :production).
    • :logger: A logger instance (defaults to NullLogger).
    • :offset: The update offset.
    • :timeout: The request timeout.
  8. Implement an Inline Bot

    master

    Inline bots allow users to interact with your bot from any chat. You must handle Telegram::Bot::Types::InlineQuery updates and use bot.api.answer_inline_query to return results. Results must be an array of query result objects (e.g., Telegram::Bot::Types::InlineQueryResultArticle).

    bot.listen do |message|
      case message
      when Telegram::Bot::Types::InlineQuery
        results = [
          ['1', 'First article', 'Very interesting text goes here.'],
          ['2', 'Second article', 'Another interesting text here.']
        ].map do |arr|
          Telegram::Bot::Types::InlineQueryResultArticle.new(
            id: arr[0],
            title: arr[1],
            input_message_content: Telegram::Bot::Types::InputTextMessageContent.new(message_text: arr[2])
          )
        end
    
        bot.api.answer_inline_query(inline_query_id: message.id, results: results)
      when Telegram::Bot::Types::Message
        bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}!"!)
      end
    end
  9. Use Inline Keyboards and handle Callbacks

    master

    Inline keyboards are attached to messages and allow users to interact via CallbackQuery. You must check the type of the incoming message object to handle these interactions.

    Key classes:

    • Telegram::Bot::Types::InlineKeyboardMarkup: The container for the keyboard.
    • Telegram::Bot::Types::InlineKeyboardButton: Individual buttons (can have url, callback_data, or switch_inline_query).
    • Telegram::Bot::Types::CallbackQuery: The update type received when an inline button is pressed.
    bot.listen do |message|
      case message
      when Telegram::Bot::Types::CallbackQuery
        if message.data == 'touch'
          bot.api.send_message(chat_id: message.from.id, text: "Don't touch me!")
        end
      when Telegram::Bot::Types::Message
        kb = [[
          Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Go to Google', url: 'https://google.com'),
          Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Touch me', callback_data: 'touch'),
          Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Switch to inline', switch_inline_query: 'some text')
        ]]
        markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb)
        bot.api.send_message(chat_id: message.chat.id, text: 'Make a choice', reply_markup: markup)
      end
    end
  10. Upload files to Telegram

    master

    You can upload files (photos, audio, documents, stickers, video) using the bot.api methods. For file uploads, it is recommended to use a multipart file part (e.g., from the Faraday::Multipart gem).

    bot.listen do |message|
      case message.text
      when '/photo'
        path_to_photo = File.expand_path('~/Desktop/jennifer.jpg')
        bot.api.send_photo(chat_id: message.chat.id, photo: Faraday::Multipart::FilePart.new(path_to_photo, 'image/jpeg'))
      end
    end
  11. Use Custom Reply Keyboards

    master

    You can create custom keyboards using Telegram::Bot::Types::ReplyKeyboardMarkup. You can also request specific user data like contact or location using KeyboardButton.

    To remove a keyboard, use Telegram::Bot::Types::ReplyKeyboardRemove.

    bot.listen do |message|
      case message.text
      when '/start'
        question = 'London is a capital of which country?'
        answers = Telegram::Bot::Types::ReplyKeyboardMarkup.new(
          keyboard: [
            [{ text: 'A' }, { text: 'B' }],
            [{ text: 'C' }, { text: 'D' }]
          ],
          one_time_keyboard: true
        )
        bot.api.send_message(chat_id: message.chat.id, text: question, reply_markup: answers)
      when '/stop'
        kb = Telegram::Bot::Types::ReplyKeyboardRemove.new(remove_keyboard: true)
        bot.api.send_message(chat_id: message.chat.id, text: 'Sorry to see you go :(', reply_markup: kb)
      end
    end
  12. Configure connection timeouts and Faraday adapter

    master

    The Telegram::Bot::Api client uses Faraday for HTTP requests. Connection settings are pulled from the global Telegram::Bot.configuration object. You can control:

    • connection_timeout: The timeout for the request.
    • connection_open_timeout: The timeout for opening the connection.
    • adapter: The Faraday adapter to use (e.g., :net_http).
    • adapter_options: Additional options passed to the Faraday adapter.