Sha256: 72fd198183ea43773569c93796c26aa025344fce5faa089f1d4db1aa98289029

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 KB

Contents

module Telegram
  module Bot
    class Client
      TIMEOUT_EXCEPTIONS = [Timeout::Error]
      TIMEOUT_EXCEPTIONS << Net::ReadTimeout if Net.const_defined?(:ReadTimeout)

      attr_reader :api, :offset, :timeout, :logger

      def self.run(*args, &block)
        new(*args).run(&block)
      end

      def initialize(token, h = {})
        options = default_options.merge(h)
        @api = Api.new(token)
        @offset = options[:offset]
        @timeout = options[:timeout]
        @logger = options[:logger]
      end

      def run
        yield self
      end

      def listen(&block)
        loop { fetch_updates(&block) }
      end

      def fetch_updates
        response = api.getUpdates(offset: offset, timeout: timeout)
        return unless response['ok']

        response['result'].each do |data|
          update = Types::Update.new(data)
          @offset = update.update_id.next
          log_incoming_message(update.message)
          yield update.message
        end
      rescue *TIMEOUT_EXCEPTIONS
        retry
      end

      private

      def default_options
        { offset: 0, timeout: 20, logger: NullLogger.new }
      end

      def log_incoming_message(message)
        logger.info(
          format(
            'Incoming message: text="%s" uid=%i',
            message.text,
            message.from.id
          )
        )
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
telegram-bot-ruby-0.3.5 lib/telegram/bot/client.rb
telegram-bot-ruby-0.3.4 lib/telegram/bot/client.rb
telegram-bot-ruby-0.3.3 lib/telegram/bot/client.rb