Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question