A
A
artem_music2015-10-14 17:38:15
Ruby on Rails
artem_music, 2015-10-14 17:38:15

How to attach a Telegram bot to Ruby on Rails?

There is a site on RoR. There is a telegram.rb file with the following code:

require 'telegram/bot'
token = 'тут-токен-бота'
Telegram::Bot::Client.run(token) do |bot|
  bot.listen do |message|
    case message.text
    when '/start'
      bot.api.sendMessage(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}")
    end
  end
end

When you run the code from the console (ruby telegram.rb), the bot works, responds, and so on. I would like the bot to work when the site is launched - for example, when a new model object is added, it notifies users in the telegram, and so on.
I don’t really understand how to do it all right - create a controller? And how to tie it with the rest?
Sorry if this is a dumb question, I'm new to RoR.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Jeiwan, 2015-10-15
@artem_music

You need to write a service (app/services) to work with the bot, make a callback on the model (for example, after_create), call the service when the callback fires, and send a message. You can do without the service and call the bot API directly in the model, but this is shit code.
Better yet, use sidekiq and make a worker so that the message to the chat is sent in the background process and does not block the request.
There may also be various pitfalls here, I don’t know how the bot is implemented, but judging by Telegram::Bot::Client.run, it blocks the flow. Therefore, it is necessary to use sidekiq and a separate worker.
PS If there is time, I will try to make an example application. It became interesting to myself ...
Sawed: https://github.com/Jeiwan/rails_telegram_botInstruction in the README, used by sidekiq, only posting done. Receiving messages will be more difficult to do, because an infinite loop is started there.

B
Biggless, 2015-10-14
@Biggless

Run foreman .

gem 'foreman'
in Gemfile
At the root of the project, create a Procfile with the content:
web: bundle exec rails s
bot: ruby ​​telegram.rb
launch
foreman start

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question