~michalr/telegram-covid-bot

7448c8226051852aacaaf95cf7df3f164348f662 — MichaƂ Rudowicz 4 years ago dc965a1
Rubocop autocorrect
2 files changed, 57 insertions(+), 49 deletions(-)

A .editorconfig
M bot.rb
A .editorconfig => .editorconfig +8 -0
@@ 0,0 1,8 @@
root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

M bot.rb => bot.rb +49 -49
@@ 1,81 1,81 @@
# frozen_string_literal: true

require 'yaml'
require 'json'
require 'net/http'
require 'date'
require 'csv'

unless ARGV.length == 2 then
    puts "Usage: bot.rb [path-to-config.yml] [path-to-previous-data.json]"
    exit 1
unless ARGV.length == 2
  puts 'Usage: bot.rb [path-to-config.yml] [path-to-previous-data.json]'
  exit 1
end

Config = YAML.load_file(ARGV[0]).freeze
begin
    PreviousData = JSON.parse(File.open(ARGV[1], 'r').read).freeze
rescue
    PreviousData = {}
  PreviousData = JSON.parse(File.open(ARGV[1], 'r').read).freeze
rescue StandardError
  PreviousData = {}.freeze
end
Lang = Config['Translation'].freeze

def sendToTelegram(country)
    textToSend = "<b>#{Lang['StatusFor']} #{country['CountryCode']} #{Lang['For']}:</b> <code>#{country['Date']}</code>\n"\
                 "<b>#{Lang['TotalConfirmed']}:</b> <code>#{country['TotalConfirmed']}</code> "\
                 "<i>(#{country['totalConfirmedDiff']})</i>\n"\
                 "<b>#{Lang['TotalRecovered']}:</b> <code>#{country['TotalRecovered']}</code> "\
                 "(<i>#{country['TotalRecovered'].to_f/country['TotalConfirmed'].to_f*100}%, "\
                 "#{country['totalRecoveredDiff']}</i>)\n"\
                 "<b>#{Lang['TotalDeaths']}:</b> <code>#{country['TotalDeaths']}</code> "\
                 "(<i>#{country['TotalDeaths'].to_f/country['TotalConfirmed'].to_f*100}%, "\
                 "#{country['totalDeathsDiff']}</i>)"
  textToSend = "<b>#{Lang['StatusFor']} #{country['CountryCode']} #{Lang['For']}:</b> <code>#{country['Date']}</code>\n"\
               "<b>#{Lang['TotalConfirmed']}:</b> <code>#{country['TotalConfirmed']}</code> "\
               "<i>(#{country['totalConfirmedDiff']})</i>\n"\
               "<b>#{Lang['TotalRecovered']}:</b> <code>#{country['TotalRecovered']}</code> "\
               "(<i>#{country['TotalRecovered'].to_f / country['TotalConfirmed'].to_f * 100}%, "\
               "#{country['totalRecoveredDiff']}</i>)\n"\
               "<b>#{Lang['TotalDeaths']}:</b> <code>#{country['TotalDeaths']}</code> "\
               "(<i>#{country['TotalDeaths'].to_f / country['TotalConfirmed'].to_f * 100}%, "\
               "#{country['totalDeathsDiff']}</i>)"

    res = Net::HTTP.post_form(URI("https://api.telegram.org/bot#{Config['TelegramToken']}/sendMessage"),
                        'chat_id' => Config['TelegramChatId'],
                        'parse_mode' => 'HTML',
                        'text' => textToSend)
    if (res.code != 200) then
            puts res.message
    end
  res = Net::HTTP.post_form(URI("https://api.telegram.org/bot#{Config['TelegramToken']}/sendMessage"),
                            'chat_id' => Config['TelegramChatId'],
                            'parse_mode' => 'HTML',
                            'text' => textToSend)
  puts res.message if res.code != 200
end

def s(value)
    value_sign = '+' if value > 0
    "#{value_sign}#{value}"
  value_sign = '+' if value > 0
  "#{value_sign}#{value}"
end

def get_current_data(for_when)
    data_uri = URI("https://raw.githubusercontent.com/CSSEGISandData/"\
        "COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/"\
        "#{for_when.strftime('%m-%d-%Y')}.csv")
  data_uri = URI('https://raw.githubusercontent.com/CSSEGISandData/'\
      'COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/'\
      "#{for_when.strftime('%m-%d-%Y')}.csv")

    raw_csv = Net::HTTP.get(data_uri)
  raw_csv = Net::HTTP.get(data_uri)

    current_from_csv = CSV.parse(raw_csv, :headers => true)
        .select { |e| e['Country_Region'] == Config['CountryCode']}
        .first
  current_from_csv = CSV.parse(raw_csv, headers: true)
                        .select { |e| e['Country_Region'] == Config['CountryCode'] }
                        .first

    {
        "Country" => current_from_csv['Country_Region'],
        "CountryCode" => current_from_csv['Country_Region'],
        "Slug" => current_from_csv['Country_Region'],
        "TotalConfirmed" => current_from_csv['Confirmed'].to_i,
        "TotalDeaths" => current_from_csv['Deaths'].to_i,
        "TotalRecovered" => current_from_csv['Recovered'].to_i,
        "Date" => current_from_csv['Last_Update']
    }
  {
    'Country' => current_from_csv['Country_Region'],
    'CountryCode' => current_from_csv['Country_Region'],
    'Slug' => current_from_csv['Country_Region'],
    'TotalConfirmed' => current_from_csv['Confirmed'].to_i,
    'TotalDeaths' => current_from_csv['Deaths'].to_i,
    'TotalRecovered' => current_from_csv['Recovered'].to_i,
    'Date' => current_from_csv['Last_Update']
  }
end

yesterday = Date.today - 1
current_data = get_current_data(yesterday)

unless current_data.reject { |k,_| k == 'Date' } == PreviousData.reject { |k,_| k == 'Date' } then
    previous_data = PreviousData unless PreviousData.empty?
    previous_data = current_data if PreviousData.empty?
unless current_data.reject { |k, _| k == 'Date' } == PreviousData.reject { |k, _| k == 'Date' }
  previous_data = PreviousData unless PreviousData.empty?
  previous_data = current_data if PreviousData.empty?

    File.open(ARGV[1], 'w') { |f| f.write(JSON.dump(current_data)) }
  File.open(ARGV[1], 'w') { |f| f.write(JSON.dump(current_data)) }

    sendToTelegram(current_data.merge({
        'totalConfirmedDiff' => s(current_data['TotalConfirmed'] - previous_data['TotalConfirmed']),
        'totalRecoveredDiff' => s(current_data['TotalRecovered'] - previous_data['TotalRecovered']),
        'totalDeathsDiff' => s(current_data['TotalDeaths'] - previous_data['TotalDeaths']),
    }))
  sendToTelegram(current_data.merge({
                                      'totalConfirmedDiff' => s(current_data['TotalConfirmed'] - previous_data['TotalConfirmed']),
                                      'totalRecoveredDiff' => s(current_data['TotalRecovered'] - previous_data['TotalRecovered']),
                                      'totalDeathsDiff' => s(current_data['TotalDeaths'] - previous_data['TotalDeaths'])
                                    }))
end