diff --git a/app/controllers/message_controller.rb b/app/controllers/message_controller.rb index bf1508c..a821616 100644 --- a/app/controllers/message_controller.rb +++ b/app/controllers/message_controller.rb @@ -1,296 +1,289 @@ +# frozen_string_literal: true + class MessageController < ActionController::API def message_process - begin - message = params[:message] - return if message.nil? || message[:chat].nil? || message[:text].nil? - unless message[:text].nil? - text = message[:text] - else - text = message[:caption] - end - if text.split('@').count == 2 - if text.split('@')[1] == ENV['BOT_USERNAME'] - text = text.split('@')[0] - end + message = params[:message] + return if message.nil? || message[:chat].nil? || message[:text].nil? + + text = if message[:text].nil? + message[:caption] + else + message[:text] end - type = message[:chat][:type] - id = message[:chat][:id] - username = message[:chat][:username] - update_id = params[:update_id] - fromid = message[:from][:id] - fromusername = message[:from][:username] - - unless Group.find_by(chat_id: id) && (type == 'group' || type == 'supergroup') - @group = Group.create(chat_id: id, username: username, title: message[:chat][:title]) if id < 0 - else - @group = Group.find_by(chat_id: id) - title = message[:chat][:title] - if @group.title.nil? || @group.title != title - @group.update_attribute(:title, title) + if text.split('@').count == 2 + text = text.split('@')[0] if text.split('@')[1] == ENV['BOT_USERNAME'] + end + type = message[:chat][:type] + id = message[:chat][:id] + username = message[:chat][:username] + update_id = params[:update_id] + fromid = message[:from][:id] + fromusername = message[:from][:username] + + if Group.find_by(chat_id: id) && (type == 'group' || type == 'supergroup') + @group = Group.find_by(chat_id: id) + title = message[:chat][:title] + if @group.title.nil? || @group.title != title + @group.update_attribute(:title, title) + end + + if @group.username != message[:chat][:username] + @group.update_attribute(:username, message[:chat][:username]) + end + else + @group = Group.create(chat_id: id, username: username, title: message[:chat][:title]) if id < 0 + end + + unless @group.nil? + unless @group.welcomesent + Telegram.bot.send_message(chat_id: @group.chat_id, text: "Bella zio! Sono il bot asdoso creato da Ferdinando Traversa (ferdinando.me) da idea di Valerio Bozzolan, asd! Digita /grafico per ricevere il link ad un grafico, anche in privato per averne uno personale, asd o /classifica per scoprire cose interessanti. L'impostazione automaticaè che io invii il conto degli ASD alla fine della serata, così però ti perdi cose belle e non è più così funny. Per modificare questa impostazione, basta digitare /nightsend ed invierò il messaggio di conteggio appena invii un asd. Se vuoi che il bot non parli, ma veda e senta, usa /silent. Ti prego! Non togliere il bot, lascialo per fini statistici. Il gruppo ufficiale è @asdfest, entra lì per suggerire nuove funzionalità o per asdare insieme.") + @group.update_attribute(:welcomesent, true) + end + + @admins = Telegram.bot.get_chat_administrators(chat_id: @group.chat_id) + @admins['result'].each do |result| + next if result.nil? + next if result['user'].nil? + + next if result['user']['username'].nil? + + if result['user']['username'].downcase == ENV['BOT_USERNAME'].downcase + @adminok = true end - - if @group.username != message[:chat][:username] - @group.update_attribute(:username, message[:chat][:username]) + end + if @adminok + @group.update_attribute(:admin, true) + else + @group.update_attribute(:admin, false) + end + end + + if Sender.find_by(chat_id: fromid) + @sender = Sender.find_by(chat_id: fromid) + first_name = message[:from][:first_name] + last_name = message[:from][:last_name] + totalname = "#{first_name} #{last_name}" + if @sender.name.nil? || @sender.name != totalname + @sender.update_attribute(:name, totalname) + end + + if @sender.username != message[:from][:username] + @sender.update_attribute(:username, message[:from][:username]) + end + + else + first_name = message[:from][:first_name] + last_name = message[:from][:last_name] + totalname = "#{first_name} #{last_name}" + @sender = Sender.create(chat_id: fromid, username: fromusername, name: totalname) + end + + if type == 'group' || type == 'supergroup' + if text =~ /asd/i + multiplevalue = text.scan(/asd/i).count + defmultiplevalue = multiplevalue - 1 + precedenteconto = @group.asds.totalcount + @asd = Asd.create(group: @group, sender: @sender, text: text, update_id: update_id, multiple_times: defmultiplevalue) + + unless Asd.find_by(sender: @sender) + unless @group.classifica + Telegram.bot.send_message(chat_id: @group.chat_id, text: 'Ciao amico, questo gruppo ha la classifica privata. È la prima volta che ti vedo e quindi imposto la classifica privata anche per te, non sarai visto in classifica! Se vai invece fiero della tua asdosità, manda il comando /fuoriclassifica in privato e riattiverò la tua presenza in classifica. Puoi anche dare /classifica per vedere questa classifica di cui tutti parlano o /grafico per il tuo grafico personal personal.') + @sender.update_attribute(classifica: false) end end - - unless @group.nil? - unless @group.welcomesent - Telegram.bot.send_message(chat_id: @group.chat_id, text: "Bella zio! Sono il bot asdoso creato da Ferdinando Traversa (ferdinando.me) da idea di Valerio Bozzolan, asd! Digita /grafico per ricevere il link ad un grafico, anche in privato per averne uno personale, asd o /classifica per scoprire cose interessanti. L'impostazione automaticaè che io invii il conto degli ASD alla fine della serata, così però ti perdi cose belle e non è più così funny. Per modificare questa impostazione, basta digitare /nightsend ed invierò il messaggio di conteggio appena invii un asd. Se vuoi che il bot non parli, ma veda e senta, usa /silent. Ti prego! Non togliere il bot, lascialo per fini statistici. Il gruppo ufficiale è @asdfest, entra lì per suggerire nuove funzionalità o per asdare insieme.") - @group.update_attribute(:welcomesent, true) + asdcount = @group.asds.count + case @group.asds.totalcount + when 100 + addtext = 'IL CENTESIMO ASD, ASD! COMPLIMENTS CONGRATULATIONS AUF WIDERSHEN' + SpecialEvent.create(text: addtext, group: @group, asd: @asd) + when 1000 + addtext = '1000 asd, wow! Questo gruppo, così asdoso, asd' + SpecialEvent.create(text: addtext, group: @group, asd: @asd) + when 10_000 + addtext = '10000è un record mondiale, asd' + SpecialEvent.create(text: addtext, group: @group, asd: @asd) + when 100_000 + addtext = '100000, sei il campione degli asd.' + SpecialEvent.create(text: addtext, group: @group, asd: @asd) end - - @admins = Telegram.bot.get_chat_administrators(chat_id: @group.chat_id) - @admins['result'].each do |result| - unless result.nil? - unless result['user'].nil? - unless result['user']['username'].nil? - if result['user']['username'].downcase == ENV['BOT_USERNAME'].downcase - @adminok = true - end + if SpecialEvent.find_by(asd: @asd) && !@group.silent + Telegram.bot.send_photo(chat_id: @group.chat_id, photo: 'http://www.lanciano.it/faccine/asdone.gif', caption: "Così asdoso, asd. #{SpecialEvent.find_by(asd: @asd).text}") + SpecialEvent.find_by(asd: @asd).destroy end + + unless @group.nightsend || @group.silent + position = Group.all.sort_by { |group| group.asds.totalcount }.pluck(:id).reverse.find_index(@group.id) + 1 + altdef = " (+#{defmultiplevalue})" if defmultiplevalue > 0 + altdef = '' if defmultiplevalue == 0 + Telegram.bot.send_message(chat_id: @group.chat_id, text: "Il contasd conta ben #{precedenteconto + 1}#{altdef}, asd. Sei il #{position}º gruppo per ASD inviati.") end - + unless @asd.created_at.nil? + if @asd.created_at.strftime('%H:%M') == '00:00' + Telegram.bot.send_message(chat_id: @group.chat_id, text: 'Asd di mezzanotte 🌚') end - end - if @adminok - @group.update_attribute(:admin, true) - else - @group.update_attribute(:admin, false) - end end + end - unless Sender.find_by(chat_id: fromid) - first_name = message[:from][:first_name] - last_name = message[:from][:last_name] - totalname = "#{first_name} #{last_name}" - @sender = Sender.create(chat_id: fromid, username: fromusername, name: totalname) - else - @sender = Sender.find_by(chat_id: fromid) - first_name = message[:from][:first_name] - last_name = message[:from][:last_name] - totalname = "#{first_name} #{last_name}" - if @sender.name.nil? || @sender.name != totalname - @sender.update_attribute(:name, totalname) - end - - if @sender.username != message[:from][:username] - @sender.update_attribute(:username, message[:from][:username]) - end - + if @group.eliminazione && text.match?(/asd/i) == false + Telegram.bot.delete_message(chat_id: @group.chat_id, message_id: message[:message_id]) end - - if type == 'group' || type == 'supergroup' - if text =~ /asd/i - multiplevalue = text.scan(/asd/i).count - defmultiplevalue = multiplevalue - 1 - precedenteconto = @group.asds.totalcount - @asd = Asd.create(group: @group, sender: @sender, text: text, update_id: update_id, multiple_times: defmultiplevalue) - - unless Asd.find_by(sender: @sender) - unless @group.classifica - Telegram.bot.send_message(chat_id: @group.chat_id, text: "Ciao amico, questo gruppo ha la classifica privata. È la prima volta che ti vedo e quindi imposto la classifica privata anche per te, non sarai visto in classifica! Se vai invece fiero della tua asdosità, manda il comando /fuoriclassifica in privato e riattiverò la tua presenza in classifica. Puoi anche dare /classifica per vedere questa classifica di cui tutti parlano o /grafico per il tuo grafico personal personal.") - @sender.update_attribute(classifica: false) - end - end - asdcount = @group.asds.count - case @group.asds.totalcount - when 100 - addtext = 'IL CENTESIMO ASD, ASD! COMPLIMENTS CONGRATULATIONS AUF WIDERSHEN' - SpecialEvent.create(text: addtext, group: @group, asd: @asd) - when 1000 - addtext = '1000 asd, wow! Questo gruppo, così asdoso, asd' - SpecialEvent.create(text: addtext, group: @group, asd: @asd) - when 10000 - addtext = '10000è un record mondiale, asd' - SpecialEvent.create(text: addtext, group: @group, asd: @asd) - when 100000 - addtext = '100000, sei il campione degli asd.' - SpecialEvent.create(text: addtext, group: @group, asd: @asd) - end - if SpecialEvent.find_by(asd: @asd) && !@group.silent - Telegram.bot.send_photo(chat_id: @group.chat_id, photo: 'http://www.lanciano.it/faccine/asdone.gif', caption: "Così asdoso, asd. #{SpecialEvent.find_by(asd: @asd).text}") - SpecialEvent.find_by(asd: @asd).destroy - end - unless @group.nightsend || @group.silent - position = Group.all.sort_by{|group| group.asds.totalcount}.pluck(:id).reverse.find_index(@group.id) + 1 - altdef = " (+#{defmultiplevalue})" if defmultiplevalue > 0 - altdef = "" if defmultiplevalue == 0 - Telegram.bot.send_message(chat_id: @group.chat_id, text: "Il contasd conta ben #{precedenteconto + 1}#{altdef}, asd. Sei il #{position}º gruppo per ASD inviati.") - end - unless @asd.created_at.nil? - if @asd.created_at.strftime('%H:%M') == '00:00' - Telegram.bot.send_message(chat_id: @group.chat_id, text: "Asd di mezzanotte 🌚") - end - end - end - - if @group.eliminazione && text.match?(/asd/i) == false - Telegram.bot.delete_message(chat_id: @group.chat_id, message_id: message[:message_id]) - end + end - end - - if text == '/start' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - @group = Group.create(chat_id: id, username: username) if id < 0 - else - @group = Group.find_by(chat_id: id) - end - Telegram.bot.send_message(chat_id: @group.chat_id, text: "Bella zio! Sono il bot asdoso creato da Ferdinando Traversa (ferdinando.me) da idea di Valerio Bozzolan, asd! Digita /grafico per ricevere il link ad un grafico, anche in privato per averne uno personale, asd o /classifica per scoprire cose interessanti. L'impostazione automaticaè che io invii il conto degli ASD alla fine della serata, così però ti perdi cose belle e non è più così funny. Per modificare questa impostazione, basta digitare /nightsend ed invierò il messaggio di conteggio appena invii un asd. Se vuoi che il bot non parli, ma veda e senta, usa /silent. Ti prego! Non togliere il bot, lascialo per fini statistici. Il gruppo ufficiale è @asdfest, entra lì per suggerire nuove funzionalità o per asdare insieme.") - @group.update_attribute(:welcomesent, true) - end + if text == '/start' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + else + @group = Group.create(chat_id: id, username: username) if id < 0 + end + Telegram.bot.send_message(chat_id: @group.chat_id, text: "Bella zio! Sono il bot asdoso creato da Ferdinando Traversa (ferdinando.me) da idea di Valerio Bozzolan, asd! Digita /grafico per ricevere il link ad un grafico, anche in privato per averne uno personale, asd o /classifica per scoprire cose interessanti. L'impostazione automaticaè che io invii il conto degli ASD alla fine della serata, così però ti perdi cose belle e non è più così funny. Per modificare questa impostazione, basta digitare /nightsend ed invierò il messaggio di conteggio appena invii un asd. Se vuoi che il bot non parli, ma veda e senta, usa /silent. Ti prego! Non togliere il bot, lascialo per fini statistici. Il gruppo ufficiale è @asdfest, entra lì per suggerire nuove funzionalità o per asdare insieme.") + @group.update_attribute(:welcomesent, true) + end - if text == '/classifica' - Telegram.bot.send_message(chat_id: id, text: "Vai su #{ENV['DOMAIN']}/classifica per vedere la classifica.") - end - - if text == '/start' && type == 'private' - Telegram.bot.send_message(chat_id: id, text: "Bella zio! Sono il bot asdoso creato da Ferdinando Traversa (ferdinando.me @ferdi2005) da idea di Valerio Bozzolan, asd! Aggiungimi ad un bel gruppo e conterò gli asd, altrimenti digita /grafico per il tuo grafico personal personal. Il gruppo ufficiale è @asdfest, entra lì per suggerire nuove funzionalità o per asdare insieme.") - end + if text == '/classifica' + Telegram.bot.send_message(chat_id: id, text: "Vai su #{ENV['DOMAIN']}/classifica per vedere la classifica.") + end - if text == '/grafico' && type == 'private' - unless Sender.find_by(chat_id: fromid) - Telegram.bot.send_message(chat_id: id, text: 'Non ho ancora un grafico per te, sei nuovo per me, non ti conosco. Iscriviti in qualche gruppo con questo bot e manda asd a ripetizione, poi torna da me.') - else - @sender = Sender.find_by(chat_id: fromid) - position = Sender.all.sort_by{|sender| sender.asds.totalcount}.pluck(:id).reverse.find_index(@sender.id) + 1 if Sender.count > 0 - Telegram.bot.send_message(chat_id: id, text: "Guarda il tuo grafico personalizzato per il gruppo su #{ENV['DOMAIN']}/grafico?s=#{@sender.chat_id} Inoltre sappi che sei il #{position}º inviatore di asd nel mondo!") - end + if text == '/start' && type == 'private' + Telegram.bot.send_message(chat_id: id, text: 'Bella zio! Sono il bot asdoso creato da Ferdinando Traversa (ferdinando.me @ferdi2005) da idea di Valerio Bozzolan, asd! Aggiungimi ad un bel gruppo e conterò gli asd, altrimenti digita /grafico per il tuo grafico personal personal. Il gruppo ufficiale è @asdfest, entra lì per suggerire nuove funzionalità o per asdare insieme.') + end + + if text == '/grafico' && type == 'private' + if Sender.find_by(chat_id: fromid) + @sender = Sender.find_by(chat_id: fromid) + position = Sender.all.sort_by { |sender| sender.asds.totalcount }.pluck(:id).reverse.find_index(@sender.id) + 1 if Sender.count > 0 + Telegram.bot.send_message(chat_id: id, text: "Guarda il tuo grafico personalizzato per il gruppo su #{ENV['DOMAIN']}/grafico?s=#{@sender.chat_id} Inoltre sappi che sei il #{position}º inviatore di asd nel mondo!") + else + Telegram.bot.send_message(chat_id: id, text: 'Non ho ancora un grafico per te, sei nuovo per me, non ti conosco. Iscriviti in qualche gruppo con questo bot e manda asd a ripetizione, poi torna da me.') + end + end + + if text == '/grafico' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + Telegram.bot.send_message(chat_id: id, text: "Guarda il tuo grafico personalizzato per il gruppo su #{ENV['DOMAIN']}/grafico?g=#{@group.chat_id}") + else + Telegram.bot.send_message(chat_id: id, text: 'Non ho ancora un grafico per te, sei nuovo per me, non ti conosco. Invia qualche asd e prova questo comando.') + end + end + + if text == '/nightsend' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + if @group.nightsend + Telegram.bot.send_message(chat_id: id, text: "Ok, l'impostazione predefinita è che l'invio del conto degli asd avvenga a mezzanotte, ma con questo comando la modifico. Procedo, ora avrai un messaggio ogni asd, asd.") + @group.update_attribute(:nightsend, false) + else + Telegram.bot.send_message(chat_id: id, text: 'Sei una persona triste, asd. Vuoi che il conteggio venga inviato a mezzanotte. Bozzolan dice sì, Ferdi dice no. Tu dici sì, allora conteggio a mezzanotte sia, asd') + @group.update_attribute(:nightsend, true) end - - if text == '/grafico' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: 'Non ho ancora un grafico per te, sei nuovo per me, non ti conosco. Invia qualche asd e prova questo comando.') - else - @group = Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Guarda il tuo grafico personalizzato per il gruppo su #{ENV['DOMAIN']}/grafico?g=#{@group.chat_id}") + else + Telegram.bot.send_message(chat_id: id, text: 'Non conosco questo gruppo.') end - end + end - if text == '/nightsend' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Non conosco questo gruppo.") - else - @group = Group.find_by(chat_id: id) - if @group.nightsend - Telegram.bot.send_message(chat_id: id, text: "Ok, l'impostazione predefinita è che l'invio del conto degli asd avvenga a mezzanotte, ma con questo comando la modifico. Procedo, ora avrai un messaggio ogni asd, asd.") - @group.update_attribute(:nightsend, false) - else - Telegram.bot.send_message(chat_id: id, text: "Sei una persona triste, asd. Vuoi che il conteggio venga inviato a mezzanotte. Bozzolan dice sì, Ferdi dice no. Tu dici sì, allora conteggio a mezzanotte sia, asd") - @group.update_attribute(:nightsend, true) - end - end + if text == '/silent' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + if @group.silent + Telegram.bot.send_message(chat_id: id, text: "Oh grazie, sei tornato nella luce, pensavo di dover rimanere muto per sempre! Ora, il tuo gruppo ha l'invio del conto notturno degli asd impostato a #{@group.nightsend ? 'attivo' : 'disattivo'}. Se vuoi che invii il conto degli asd la notte attivalo, altrimenti se vuoi un messaggio ogni asd disattivalo. Lo fai col comando /nightsend") + @group.update_attribute(:silent, false) + else + Telegram.bot.send_message(chat_id: id, text: 'Se vuoi che me ne rimanga zitto zitto nelle tenebre allora usa questo comando, per far che ritorni a parlare digitalo di nuovo.') + @group.update_attribute(:silent, true) end - - if text == '/silent' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Non conosco questo gruppo.") - else - @group = Group.find_by(chat_id: id) - if @group.silent - Telegram.bot.send_message(chat_id: id, text: "Oh grazie, sei tornato nella luce, pensavo di dover rimanere muto per sempre! Ora, il tuo gruppo ha l'invio del conto notturno degli asd impostato a #{@group.nightsend ? 'attivo' : 'disattivo'}. Se vuoi che invii il conto degli asd la notte attivalo, altrimenti se vuoi un messaggio ogni asd disattivalo. Lo fai col comando /nightsend") - @group.update_attribute(:silent, false) - else - Telegram.bot.send_message(chat_id: id, text: "Se vuoi che me ne rimanga zitto zitto nelle tenebre allora usa questo comando, per far che ritorni a parlare digitalo di nuovo.") - @group.update_attribute(:silent, true) - end + else + Telegram.bot.send_message(chat_id: id, text: 'Non conosco questo gruppo.') end - end + end - if text == '/fuoriclassifica' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Non conosco questo gruppo.") - else - @group = Group.find_by(chat_id: id) - if @group.classifica - Telegram.bot.send_message(chat_id: id, text: "Siete delle persone tristi e/o poco competitive? Amate la privasi anche se Google sa tutto di voi, anche come vi siete vestiti ieri, asd? Allora questo è il comando per voi. Da oggi siete fuori dalla classifica, per scelta. Datelo di nuovo per riattivare (sicuramente avete sbagliato, vero?)") - @group.update_attribute(:classifica, false) - else - Telegram.bot.send_message(chat_id: id, text: "Bravo! Hai fatto la scelta giusta, fai ritornare il tuo gruppo nella classifica pubblica con questo semplice comandino") - @group.update_attribute(:classifica, true) - end - end + if text == '/fuoriclassifica' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + if @group.classifica + Telegram.bot.send_message(chat_id: id, text: 'Siete delle persone tristi e/o poco competitive? Amate la privasi anche se Google sa tutto di voi, anche come vi siete vestiti ieri, asd? Allora questo è il comando per voi. Da oggi siete fuori dalla classifica, per scelta. Datelo di nuovo per riattivare (sicuramente avete sbagliato, vero?)') + @group.update_attribute(:classifica, false) + else + Telegram.bot.send_message(chat_id: id, text: 'Bravo! Hai fatto la scelta giusta, fai ritornare il tuo gruppo nella classifica pubblica con questo semplice comandino') + @group.update_attribute(:classifica, true) end - if text == '/statistiche' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Non conosco questo gruppo.") - else - @group = Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Asd inviati: #{@group.asds.count}") + else + Telegram.bot.send_message(chat_id: id, text: 'Non conosco questo gruppo.') end - end - - if text == '/eliminazione' && (type == 'group' || type == 'supergroup') - unless Group.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Non conosco questo gruppo.") - else - @group = Group.find_by(chat_id: id) - if @group.admin && @group.eliminazione - Telegram.bot.send_message(chat_id: id, text: "Ora basta eliminare tutti i messaggi insieme bot.") - @group.update_attribute(:eliminazione, false) - elsif !@group.eliminazione - Telegram.bot.send_message(chat_id: id, text: "Da ora eliminerò tutti i messaggi che non sono asd, perché questo è il gruppo @asdfest o una sua imitazione scrausa!") - @group.update_attribute(:eliminazione, true) - elsif !@group.admin - Telegram.bot.send_message(chat_id: id, text: "Non mi hai messo admin!") - end + end + if text == '/statistiche' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + Telegram.bot.send_message(chat_id: id, text: "Asd inviati: #{@group.asds.count}") + else + Telegram.bot.send_message(chat_id: id, text: 'Non conosco questo gruppo.') end - end + end - if text == '/fuoriclassifica' && type == 'private' - unless Sender.find_by(chat_id: id) - Telegram.bot.send_message(chat_id: id, text: "Non ti conosco, asd.") - else - @group = Sender.find_by(chat_id: id) - if @group.classifica - Telegram.bot.send_message(chat_id: id, text: "Sei una persona triste o poco competitiva? Questo è il comando giusto per te. Da oggi non apparirai più nella classifica pubblica.") - @group.update_attribute(:classifica, false) - else - Telegram.bot.send_message(chat_id: id, text: "Bravo! Hai fatto la scelta giusta, ritorna nella classifica pubblica con questo semplice comandino") - @group.update_attribute(:classifica, true) - end - end + if text == '/eliminazione' && (type == 'group' || type == 'supergroup') + if Group.find_by(chat_id: id) + @group = Group.find_by(chat_id: id) + if @group.admin && @group.eliminazione + Telegram.bot.send_message(chat_id: id, text: 'Ora basta eliminare tutti i messaggi insieme bot.') + @group.update_attribute(:eliminazione, false) + elsif !@group.eliminazione + Telegram.bot.send_message(chat_id: id, text: 'Da ora eliminerò tutti i messaggi che non sono asd, perché questo è il gruppo @asdfest o una sua imitazione scrausa!') + @group.update_attribute(:eliminazione, true) + elsif !@group.admin + Telegram.bot.send_message(chat_id: id, text: 'Non mi hai messo admin!') end + else + Telegram.bot.send_message(chat_id: id, text: 'Non conosco questo gruppo.') + end + end - comandi = ["/fuoriclassifica", "/classifica", "/start", "/grafico", "/nightsend", "/annuncio", "/todo"] - admins = [82247861, 55632382] - if !text.in?(comandi) && type == 'private' - Telegram.bot.send_message(chat_id: id, text: "Cos…? asd") + if text == '/fuoriclassifica' && type == 'private' + if Sender.find_by(chat_id: id) + @group = Sender.find_by(chat_id: id) + if @group.classifica + Telegram.bot.send_message(chat_id: id, text: 'Sei una persona triste o poco competitiva? Questo è il comando giusto per te. Da oggi non apparirai più nella classifica pubblica.') + @group.update_attribute(:classifica, false) + else + Telegram.bot.send_message(chat_id: id, text: 'Bravo! Hai fatto la scelta giusta, ritorna nella classifica pubblica con questo semplice comandino') + @group.update_attribute(:classifica, true) end - - if text.match?(/\/annunciogruppo/) && admins.include?(fromid) - annuncio = text.split('/annunciogruppo')[1].strip - Group.all.each do |group| - begin - Telegram.bot.send_message(chat_id: group.chat_id, text: annuncio) - rescue => e - Telegram.bot.send_message(chat_id: 82247861, text: e.to_s) - end + else + Telegram.bot.send_message(chat_id: id, text: 'Non ti conosco, asd.') end - end + end - if text.match?(/\/annuncioprivato/) && admins.include?(fromid) - annuncio = text.split('/annuncioprivato')[1].strip - Sender.all.each do |group| - begin - Telegram.bot.send_message(chat_id: group.chat_id, text: annuncio) - rescue => e - Telegram.bot.send_message(chat_id: 82247861, text: e.to_s) - end - end - end + comandi = ['/fuoriclassifica', '/classifica', '/start', '/grafico', '/nightsend', '/annuncio', '/todo'] + admins = [82_247_861, 55_632_382] + if !text.in?(comandi) && type == 'private' + Telegram.bot.send_message(chat_id: id, text: 'Cos…? asd') + end - if text == '/todo' - Telegram.bot.send_message(chat_id: id, text: 'Invia una mail a todo@ferdinando.me') - end + if text.match?(%r{/annunciogruppo}) && admins.include?(fromid) + annuncio = text.split('/annunciogruppo')[1].strip + Group.all.each do |group| + Telegram.bot.send_message(chat_id: group.chat_id, text: annuncio) + rescue StandardError => e + Telegram.bot.send_message(chat_id: 82_247_861, text: e.to_s) + end + end - if text == '/gruppoufficiale' - Telegram.bot.send_message(chat_id: id, text: 'Entra nel gruppo ufficiale del nostro bot, dove solo asd sono ammessi: @asdfest') - end - rescue => e - Telegram.bot.send_message(chat_id: 82247861, text: e.to_s) + if text.match?(%r{/annuncioprivato}) && admins.include?(fromid) + annuncio = text.split('/annuncioprivato')[1].strip + Sender.all.each do |group| + Telegram.bot.send_message(chat_id: group.chat_id, text: annuncio) + rescue StandardError => e + Telegram.bot.send_message(chat_id: 82_247_861, text: e.to_s) end + end + + if text == '/todo' + Telegram.bot.send_message(chat_id: id, text: 'Invia una mail a todo@ferdinando.me') + end + + if text == '/gruppoufficiale' + Telegram.bot.send_message(chat_id: id, text: 'Entra nel gruppo ufficiale del nostro bot, dove solo asd sono ammessi: @asdfest') + end + rescue StandardError => e + Telegram.bot.send_message(chat_id: 82_247_861, text: e.to_s) end -end \ No newline at end of file +end diff --git a/app/controllers/standardpage_controller.rb b/app/controllers/standardpage_controller.rb index aa08644..4fe20cb 100644 --- a/app/controllers/standardpage_controller.rb +++ b/app/controllers/standardpage_controller.rb @@ -1,39 +1,40 @@ +# frozen_string_literal: true + class StandardpageController < ApplicationController def classifica - @groups = Group.all.sort_by{|sender| sender.asds.totalcount}.reverse - @senders = Sender.all.sort_by{|sender| sender.asds.totalcount}.reverse + @groups = Group.all.sort_by { |sender| sender.asds.totalcount }.reverse + @senders = Sender.all.sort_by { |sender| sender.asds.totalcount }.reverse end def usernametoid if params[:username].split('@').count == 2 params[:username] = params[:username].split('@')[1] end - if Group.where('lower(username) LIKE lower(?)', "#{params[:username]}").any? - @group = Group.where('lower(username) LIKE lower(?)', "#{params[:username]}").first + if Group.where('lower(username) LIKE lower(?)', params[:username].to_s).any? + @group = Group.where('lower(username) LIKE lower(?)', params[:username].to_s).first respond_to do |format| - format.json { render json: {status: '200', chat_id: @group.chat_id} } - end - elsif Sender.where('lower(username) LIKE lower(?)', "#{params[:username]}").any? - @sender = Sender.where('lower(username) LIKE lower(?)', "#{params[:username]}").first + format.json { render json: { status: '200', chat_id: @group.chat_id } } + end + elsif Sender.where('lower(username) LIKE lower(?)', params[:username].to_s).any? + @sender = Sender.where('lower(username) LIKE lower(?)', params[:username].to_s).first respond_to do |format| - format.json { render json: {status: '201', chat_id: @sender.chat_id} } + format.json { render json: { status: '201', chat_id: @sender.chat_id } } end else respond_to do |format| error = { status: '404' } - format.json { render json: error, status: :not_found} + format.json { render json: error, status: :not_found } end end end - + def grafico if !params[:s].nil? @sender = Sender.find_by(chat_id: params[:s]) elsif !params[:g].nil? @group = Group.find_by(chat_id: params[:g]) end end - def home - end + def home; end end diff --git a/app/jobs/send_asd_count_job.rb b/app/jobs/send_asd_count_job.rb index 248bdc9..99afc20 100644 --- a/app/jobs/send_asd_count_job.rb +++ b/app/jobs/send_asd_count_job.rb @@ -1,20 +1,20 @@ +# frozen_string_literal: true + class SendAsdCountJob < ApplicationJob queue_as :default - def perform(*args) + def perform(*_args) Group.where(nightsend: true).each do |group| - begin @group = group - date = Date.yesterday + date = Date.yesterday @asds = Asd.where(created_at: date.midnight..date.end_of_day, group: group) - position = Group.all.sort_by{|gp| gp.asds.totalcount}.pluck(:id).reverse.find_index(@group.id) + 1 + position = Group.all.sort_by { |gp| gp.asds.totalcount }.pluck(:id).reverse.find_index(@group.id) + 1 defmultipletimes = @asds.pluck(:multiple_times).sum if @asds.count > 0 && !@group.silent - Telegram.bot.send_message(chat_id: @group.chat_id, text: "È mezzanotte, ora di sapere! Il contasd di ieri conta ben #{@asds.count} (+#{defmultipletimes} multipli) per un totale di #{@asds.totalcount} asds, asd. Sei il #{position}º gruppo per ASD inviati. (Digita /silent per disattivarmi, non togliermi!)") - end - rescue => e - puts e + Telegram.bot.send_message(chat_id: @group.chat_id, text: "È mezzanotte, ora di sapere! Il contasd di ieri conta ben #{@asds.count} (+#{defmultipletimes} multipli) per un totale di #{@asds.totalcount} asds, asd. Sei il #{position}º gruppo per ASD inviati. (Digita /silent per disattivarmi, non togliermi!)") end + rescue StandardError => e + puts e end end end diff --git a/app/models/asd.rb b/app/models/asd.rb index 8463c5a..6325495 100644 --- a/app/models/asd.rb +++ b/app/models/asd.rb @@ -1,13 +1,16 @@ +# frozen_string_literal: true + class Asd < ApplicationRecord belongs_to :group belongs_to :sender validates :update_id, uniqueness: true, presence: false has_many :special_events before_create :default_values def default_values self.multiple_times = multiple_times.presence || 0 end + def self.totalcount - self.count + pluck(:multiple_times).sum + count + pluck(:multiple_times).sum end end diff --git a/app/models/group.rb b/app/models/group.rb index 8b8fa4e..551dea0 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Group < ApplicationRecord has_many :asds has_many :special_events validates :chat_id, uniqueness: true - validates :chat_id, :numericality => {:less_than_or_equal_to => 0 } + validates :chat_id, numericality: { less_than_or_equal_to: 0 } end diff --git a/app/models/sender.rb b/app/models/sender.rb index aa00841..c070709 100644 --- a/app/models/sender.rb +++ b/app/models/sender.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class Sender < ApplicationRecord has_many :asds validates :chat_id, uniqueness: true - validates :chat_id, :numericality => { :greater_than_or_equal_to => 0 } + validates :chat_id, numericality: { greater_than_or_equal_to: 0 } end diff --git a/config/application.rb b/config/application.rb index b0246d3..c671a53 100644 --- a/config/application.rb +++ b/config/application.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Asdbot class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. - config.time_zone = "Rome" + config.time_zone = 'Rome' config.active_job.queue_adapter = :sidekiq Raven.configure do |config| config.dsn = 'https://0990a682fc9a4c2691cc14c1f81c6da3:99ef32af76c9457bb64bbad21305368a@sentry.io/1527516' - end + end end end diff --git a/config/environments/production.rb b/config/environments/production.rb index 36214e1..5e55e71 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -1,94 +1,96 @@ +# frozen_string_literal: true + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = false # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] + config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "asdbot_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') - if ENV["RAILS_LOG_TO_STDOUT"].present? + if ENV['RAILS_LOG_TO_STDOUT'].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end diff --git a/config/routes.rb b/config/routes.rb index 26e27af..4d387a4 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + Rails.application.routes.draw do root 'standardpage#home' post 'message_process', to: 'message#message_process' get 'classifica', to: 'standardpage#classifica' get 'grafico', to: 'standardpage#grafico' get 'usernametoid', to: 'standardpage#usernametoid' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end diff --git a/db/migrate/20190811222510_add_classifica_to_groups.rb b/db/migrate/20190811222510_add_classifica_to_groups.rb index 2394733..8099ca7 100644 --- a/db/migrate/20190811222510_add_classifica_to_groups.rb +++ b/db/migrate/20190811222510_add_classifica_to_groups.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class AddClassificaToGroups < ActiveRecord::Migration[5.2] def change add_column :groups, :classifica, :boolean, default: true end end diff --git a/db/migrate/20190811222520_add_classifica_to_senders.rb b/db/migrate/20190811222520_add_classifica_to_senders.rb index ed62a08..5070c8a 100644 --- a/db/migrate/20190811222520_add_classifica_to_senders.rb +++ b/db/migrate/20190811222520_add_classifica_to_senders.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class AddClassificaToSenders < ActiveRecord::Migration[5.2] def change add_column :senders, :classifica, :boolean, default: true end end diff --git a/db/migrate/20190814132440_add_silent_to_groups.rb b/db/migrate/20190814132440_add_silent_to_groups.rb index 3e99eec..9da08b8 100644 --- a/db/migrate/20190814132440_add_silent_to_groups.rb +++ b/db/migrate/20190814132440_add_silent_to_groups.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class AddSilentToGroups < ActiveRecord::Migration[5.2] def change add_column :groups, :silent, :boolean, default: false end end diff --git a/db/migrate/20190908140055_add_admin_to_groups.rb b/db/migrate/20190908140055_add_admin_to_groups.rb index 1a99d5d..da11a68 100644 --- a/db/migrate/20190908140055_add_admin_to_groups.rb +++ b/db/migrate/20190908140055_add_admin_to_groups.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class AddAdminToGroups < ActiveRecord::Migration[5.2] def change add_column :groups, :admin, :boolean add_column :groups, :deletenotasd, :boolean end end diff --git a/db/migrate/20190911221023_add_eliminazione_to_groups.rb b/db/migrate/20190911221023_add_eliminazione_to_groups.rb index 4584fa9..74fad9b 100644 --- a/db/migrate/20190911221023_add_eliminazione_to_groups.rb +++ b/db/migrate/20190911221023_add_eliminazione_to_groups.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class AddEliminazioneToGroups < ActiveRecord::Migration[5.2] def change add_column :groups, :eliminazione, :boolean, default: false end end diff --git a/db/schema.rb b/db/schema.rb index 29287e0..b24fecf 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,79 +1,80 @@ +# frozen_string_literal: true + # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_09_11_221023) do - +ActiveRecord::Schema.define(version: 20_190_911_221_023) do # These are extensions that must be enabled in order to support this database - enable_extension "plpgsql" + enable_extension 'plpgsql' - create_table "asds", force: :cascade do |t| - t.bigint "group_id" - t.bigint "sender_id" - t.integer "update_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.string "text" - t.boolean "nightsend" - t.integer "multiple_times" - t.index ["group_id"], name: "index_asds_on_group_id" - t.index ["sender_id"], name: "index_asds_on_sender_id" + create_table 'asds', force: :cascade do |t| + t.bigint 'group_id' + t.bigint 'sender_id' + t.integer 'update_id' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.string 'text' + t.boolean 'nightsend' + t.integer 'multiple_times' + t.index ['group_id'], name: 'index_asds_on_group_id' + t.index ['sender_id'], name: 'index_asds_on_sender_id' end - create_table "crono_jobs", force: :cascade do |t| - t.string "job_id", null: false - t.text "log" - t.datetime "last_performed_at" - t.boolean "healthy" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index ["job_id"], name: "index_crono_jobs_on_job_id", unique: true + create_table 'crono_jobs', force: :cascade do |t| + t.string 'job_id', null: false + t.text 'log' + t.datetime 'last_performed_at' + t.boolean 'healthy' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.index ['job_id'], name: 'index_crono_jobs_on_job_id', unique: true end - create_table "groups", force: :cascade do |t| - t.bigint "chat_id" - t.string "username" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.boolean "welcomesent", default: false - t.boolean "nightsend" - t.string "title" - t.boolean "classifica", default: true - t.boolean "silent", default: false - t.boolean "admin" - t.boolean "deletenotasd" - t.boolean "eliminazione", default: false + create_table 'groups', force: :cascade do |t| + t.bigint 'chat_id' + t.string 'username' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.boolean 'welcomesent', default: false + t.boolean 'nightsend' + t.string 'title' + t.boolean 'classifica', default: true + t.boolean 'silent', default: false + t.boolean 'admin' + t.boolean 'deletenotasd' + t.boolean 'eliminazione', default: false end - create_table "senders", force: :cascade do |t| - t.integer "chat_id" - t.string "username" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.string "name" - t.boolean "classifica", default: true + create_table 'senders', force: :cascade do |t| + t.integer 'chat_id' + t.string 'username' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.string 'name' + t.boolean 'classifica', default: true end - create_table "special_events", force: :cascade do |t| - t.bigint "group_id" - t.string "text" - t.bigint "asd_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index ["asd_id"], name: "index_special_events_on_asd_id" - t.index ["group_id"], name: "index_special_events_on_group_id" + create_table 'special_events', force: :cascade do |t| + t.bigint 'group_id' + t.string 'text' + t.bigint 'asd_id' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.index ['asd_id'], name: 'index_special_events_on_asd_id' + t.index ['group_id'], name: 'index_special_events_on_group_id' end - add_foreign_key "asds", "groups" - add_foreign_key "asds", "senders" - add_foreign_key "special_events", "asds" - add_foreign_key "special_events", "groups" + add_foreign_key 'asds', 'groups' + add_foreign_key 'asds', 'senders' + add_foreign_key 'special_events', 'asds' + add_foreign_key 'special_events', 'groups' end