diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index e5c3d60..a304db3 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -30,16 +30,17 @@ class ApplicationController < ActionController::API # @param :subject [Symbol|String] Título del mensaje para I18n # @param :urgency [Symbol] Nivel de urgencia def notify(subject:, urgency: :normal, ttl: 7.days) - # Notificar a todas las piratas que hay una nueva barca para que - # se puedan sumar - payload = WebpushPayload.new(subject: get_subject(subject), - message: get_message(subject), - endpoint: get_endpoint(subject)) + payload = { subject: get_subject(subject), + message: get_message(subject), + endpoint: get_endpoint(subject) } WebpushJob.perform_later(piratas: todas_menos_yo_ids, ttl: ttl.to_i, urgency: urgency.to_s, - payload: payload.to_json) + payload: WebpushPayload.new(payload).to_json) + + TelegramJob.perform_later(piratas: todas_menos_yo_ids, + payload: payload.to_json) end # Autenticar a la pirata usando HTTP Basic Auth diff --git a/app/jobs/telegram_job.rb b/app/jobs/telegram_job.rb new file mode 100644 index 0000000..cf0672e --- /dev/null +++ b/app/jobs/telegram_job.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +# Envía las notificaciones por Telegram +class TelegramJob < ApplicationJob + queue_as :default + + # @param :piratas [Symbol,Array] :all para traer todas, array de IDs para filtrar + # @param :payload [String] La notificación a enviar en JSON + def perform(piratas:, payload:) + # Encontrar todas las piratas con Telegram + piratas = find_piratas(piratas) + payload = JSON.parse payload + + piratas.find_each do |pirata| + Telegram.bots[:default].send_message chat_id: pirata.telegram_user, + parse_mode: 'MarkdownV2', + text: "*#{payload['subject']}*\n\n#{payload['message']}" + end + end + + private + + def find_piratas(ids) + piratas = Pirata.where.not(telegram_user: nil) + + unless ids == 'all' + piratas.where(id: ids) + end + + piratas + end +end