telegram-bot-ruby icon indicating copy to clipboard operation
telegram-bot-ruby copied to clipboard

Add an API to build JSON response

Open smaximov opened this issue 9 years ago • 0 comments

When using webhooks, it is possible to make an API request by replying directly with JSON payload instead of making a separate HTTP request.

This PR features the Telegram::Bot::ResponseBuilder class. It derives from Telegram::Bot::Api and can be used as a drop-in replacement. When a Telegram API method is invoked on an instance of ResponseBuilder, its parameters are serialized to JSON hash with an additional method parameter derived from the method name.

Example — webhook-based "echo" bot, built on top of Sinatra:

require 'sinatra'
require 'sinatra/json'

class TelegramWebhookBot < Sinatra::Base
  use Rack::PostBodyContentTypeParser
  register Sinatra::JSON

  post '/webhooks/tg' do
    message = Telegram::Bot::Types::Update.new(params).message
    response_builder = Telegram::Bot::ResponseBuilder.new
    json response_builder.send_message(chat_id: message.chat.id, text: message.text)
    # response: {"chat_id":9001,"text":"Hello, World!","method":"sendMessage"}
  end
end

smaximov avatar Jan 21 '17 00:01 smaximov