Notificar por Telegram

This commit is contained in:
fauno 2020-06-20 21:59:13 -03:00
parent b922a689a4
commit 12c3cb7436
2 changed files with 39 additions and 6 deletions

View file

@ -30,15 +30,16 @@ 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),
payload = { subject: get_subject(subject),
message: get_message(subject),
endpoint: get_endpoint(subject))
endpoint: get_endpoint(subject) }
WebpushJob.perform_later(piratas: todas_menos_yo_ids,
ttl: ttl.to_i,
urgency: urgency.to_s,
payload: WebpushPayload.new(payload).to_json)
TelegramJob.perform_later(piratas: todas_menos_yo_ids,
payload: payload.to_json)
end

32
app/jobs/telegram_job.rb Normal file
View file

@ -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