Skip to content

Getting Updates

Roman Samoilov edited this page Aug 6, 2020 · 2 revisions

The gem implements both methods of getting updates from the Telegram API.

Webhooks

  • Configure the gem with webhook_url value.
  • Process the updates with the following code in your controller:
class TelegramWebhooksController < ApplicationController
  def create
    TelegramWorkflow.process(params)
    head :ok
  end
end

Long polling

  • Make sure you don't configure the gem with webhook_url value.
  • Run the following code:
TelegramWorkflow.updates.each do |params|
  TelegramWorkflow.process(params)
end

Be aware that TelegramWorkflow.updates.each call is blocking.

TelegramWorkflow.updates accepts all the parameters getUpdates does.

TelegramWorkflow.updates(timeout: 60, allowed_updates: %w(channel_post edited_channel_post)).each do |params|
  ...
end

Since most of the time will be spent on waiting for the Telegram API to respond, you might also want to process the updates in parallel:

require "concurrent-ruby"

pool = Concurrent::CachedThreadPool.new

TelegramWorkflow.updates.each do |params|
  pool.post { TelegramWorkflow.process(params) }
end

Use stop_updates call to exit the updates loop:

trap "SIGINT" do
  TelegramWorkflow.stop_updates
end

# decrease the timeout to wait no more than 10 seconds when exiting
TelegramWorkflow.updates(timeout: 10).each do |params|
  TelegramWorkflow.process(params)
end

Previous: Configuration Next: Customization

Clone this wiki locally