2018-11-29 08:07:20 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-12-06 21:43:30 -05:00
|
|
|
class TelegramBots::UpdatesController < ApplicationController
|
2018-11-29 08:34:40 -05:00
|
|
|
before_action :set_telegram_bot
|
|
|
|
before_action :verify_telegram_bot_secret
|
|
|
|
|
2018-11-29 19:17:26 -05:00
|
|
|
skip_after_action :verify_authorized
|
|
|
|
|
2018-12-06 21:43:30 -05:00
|
|
|
# POST /telegram_bots/:telegram_bot_id/updates
|
2018-11-29 08:07:20 -05:00
|
|
|
def create
|
2018-12-06 22:48:31 -05:00
|
|
|
handle_message params[:message]
|
2018-12-06 22:16:35 -05:00
|
|
|
|
2018-11-29 08:07:20 -05:00
|
|
|
render status: :no_content, json: {}
|
|
|
|
end
|
2018-11-29 08:34:40 -05:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def set_telegram_bot
|
|
|
|
@telegram_bot = TelegramBot.find params[:telegram_bot_id]
|
|
|
|
end
|
|
|
|
|
|
|
|
def verify_telegram_bot_secret
|
2018-11-29 19:02:04 -05:00
|
|
|
return if params[:secret] == @telegram_bot.secret
|
|
|
|
|
|
|
|
raise NotAuthorizedError.new query: "#{action_name}?",
|
|
|
|
record: @telegram_bot
|
2018-11-29 08:34:40 -05:00
|
|
|
end
|
2018-12-06 22:16:35 -05:00
|
|
|
|
2018-12-07 17:20:58 -05:00
|
|
|
def handle_message(message)
|
2018-12-06 22:48:31 -05:00
|
|
|
return if message.blank?
|
|
|
|
|
2018-12-06 22:54:59 -05:00
|
|
|
telegram_chat = handle_chat message[:chat]
|
|
|
|
|
|
|
|
return if @telegram_bot.username.nil?
|
|
|
|
|
2018-12-07 17:20:58 -05:00
|
|
|
case message[:text]
|
|
|
|
when '/shrug', "/shrug@#{@telegram_bot.username}"
|
|
|
|
@telegram_bot.client.send_message(
|
|
|
|
chat_id: telegram_chat.remote_id,
|
|
|
|
text: '¯\_(ツ)_/¯',
|
|
|
|
)
|
|
|
|
end
|
2018-12-06 22:48:31 -05:00
|
|
|
end
|
|
|
|
|
2018-12-06 22:16:35 -05:00
|
|
|
def handle_chat(chat)
|
|
|
|
return if chat.blank?
|
|
|
|
|
2018-12-06 22:28:34 -05:00
|
|
|
telegram_chat = TelegramChat.where(remote_id: chat[:id]).first_or_initialize
|
2018-12-06 22:21:58 -05:00
|
|
|
|
|
|
|
telegram_chat.chat_type = chat[:type]
|
|
|
|
telegram_chat.title = chat[:title]
|
|
|
|
telegram_chat.username = chat[:username]
|
|
|
|
telegram_chat.first_name = chat[:first_name]
|
|
|
|
telegram_chat.last_name = chat[:last_name]
|
|
|
|
|
|
|
|
telegram_chat.save!
|
2018-12-06 22:48:31 -05:00
|
|
|
|
|
|
|
telegram_chat
|
2018-12-06 22:16:35 -05:00
|
|
|
end
|
2018-11-29 08:07:20 -05:00
|
|
|
end
|