telegram-bot-ruby
telegram-bot-ruby copied to clipboard
Add an API to build JSON response
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