Skip to content

Public API

Roman Samoilov edited this page Jul 21, 2023 · 5 revisions

Each action has a set of globally accessible objects:

Object Description
params Instance of TelegramWorkflow::Params.
client Instance of TelegramWorkflow::Client. Can be customized.
session Persistent store to keep session data. Instance of Hash.
flash A temporary store to keep some data between different steps. Instance of Hash.
logger A configured logger object. Use ActiveSupport::TaggedLogging to have TelegramWorkflow automatically tag every request.

params

The params object encapsulates the logic to parse Telegram params. It implements useful methods, like message_text, callback_data or deep_link_payload to fetch user submitted data from the params.

client

This is an instance of TelegramWorkflow::Client class which implements a complete Telegram Bot API. The methods to access the API are called after raw Telegram API methods. For example, if you needed to call a sendLocation method, you would use the following code:

client.send_location latitude: 40.748, longitude: -73.985, live_period: 120

chat_id parameter should be omitted.

session

This is a persistent store to save the data associated with a user, e.g. current user's id, some settings or anything you would store in a session in a regular web application.

flash

This is a temporary store to save the data between the steps. The data persists while redirecting between the steps, but gets deleted automatically when redirecting to another action.

redirect_to(action_or_class, flash_params = {})

As you already know, this function allows to build complex workflows by redirecting between actions and steps. The function expects either a symbol or instance of Class as a first argument. Passing a symbol will redirect to another step inside the current action. Passing instance of Class will redirect to another action.

# redirect to a step
redirect_to :suggest

# redirect to an action
redirect_to RateMovie

Sometimes you will need to share some data between the actions. You could use session for this, but a more appropriate solution would be to have redirect_to function to preserve the flash between actions. Check out this example:

class AskForBirthday < TelegramWorkflow::Action
  def initial
    on_redirect do
      client.send_message text: "What year is your birthday?"
    end

    on_message do
      birthday = params.message_text.to_i
      redirect_to DisplayAge, birthday: birthday
    end
  end
end

class DisplayAge < TelegramWorkflow::Action
  def initial
    on_redirect do
      age = Date.today.year - flash[:birthday]
      client.send_message text: "You are #{age}!"
    end
  end
end

You can see that despite the fact that flash is being cleared when redirecting to another action, passing birthday value to the redirect_to call made it accessible via flash in the action we redirected to.

Next: Configuration

Clone this wiki locally