Sha256: 26d4eb24a1cae912b00c332735188c71663a9c2097d377cd3e420530d1a23a0f

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

module Telegram
  module Bot
    class Api
      include HTTParty

      ENDPOINTS = %w(
        getMe sendMessage forwardMessage sendPhoto sendAudio sendDocument
        sendSticker sendVideo sendLocation sendChatAction getUserProfilePhotos
        getUpdates setWebhook
      ).freeze
      REPLY_MARKUP_TYPES = [
        Telegram::Bot::Types::ReplyKeyboardMarkup,
        Telegram::Bot::Types::ReplyKeyboardHide,
        Telegram::Bot::Types::ForceReply
      ].freeze

      attr_reader :token

      base_uri 'https://api.telegram.org'
      persistent_connection_adapter

      def initialize(token)
        @token = token
      end

      def method_missing(method_name, *args, &block)
        ENDPOINTS.include?(method_name.to_s) ? call(method_name, *args) : super
      end

      def call(endpoint, raw_params = {})
        params = build_params(raw_params)
        response = self.class.get("/bot#{token}/#{endpoint}", query: params)
        if response.code == 200
          response.to_h
        else
          fail Exceptions::ResponseError.new(response),
               'Telegram API has returned the error.'
        end
      end

      private

      def build_params(h)
        h.each_with_object({}) do |(key, value), params|
          params[key] = sanitize_value(value)
        end
      end

      def sanitize_value(value)
        jsonify_reply_markup(value)
      end

      def jsonify_reply_markup(value)
        return value unless REPLY_MARKUP_TYPES.include?(value.class)
        value.to_h.to_json
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
telegram-bot-ruby-0.2.2 lib/telegram/bot/api.rb