From 12c3cb74363ad26dedb12b95eda5439ba32b24f0 Mon Sep 17 00:00:00 2001 From: fauno Date: Sat, 20 Jun 2020 21:59:13 -0300 Subject: [PATCH] Notificar por Telegram --- app/controllers/application_controller.rb | 13 ++++----- app/jobs/telegram_job.rb | 32 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 app/jobs/telegram_job.rb 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