~michalr/telegram-covid-bot

49c60776e0e97953008fb55b8a8d89ad9001a51f — Michał Rudowicz 4 years ago 65ef3a0
Simple translation support
2 files changed, 21 insertions(+), 10 deletions(-)

M bot.rb
M config.example.yml
M bot.rb => bot.rb +15 -10
@@ 1,24 1,29 @@
require 'yaml'
require 'json'
require 'open-uri'
require 'net/http'

Config = YAML.load_file(ARGV[0]).freeze
Lang = Config['Translation'].freeze

def sendToTelegram(country)
    textToSend = "<b>Stan dla #{country['CountryCode']} na:</b> <code>#{country['Date']}</code>\n"\
                 "<b>Łącznie potwierdzonych:</b> <code>#{country['TotalConfirmed']}</code>\n"\
                 "<b>Łącznie wyzdrowiało:</b> <code>#{country['TotalRecovered']}</code> (<i>#{country['TotalRecovered'].to_f/country['TotalConfirmed'].to_f*100}%</i>)\n"\
                 "<b>Łącznie zmarło:</b> <code>#{country['TotalDeaths']}</code> (<i>#{country['TotalDeaths'].to_f/country['TotalConfirmed'].to_f*100}%</i>)"
    textToSend = "<b>#{Lang['StatusFor']} #{country['CountryCode']} #{Lang['For']}:</b> <code>#{country['Date']}</code>\n"\
                 "<b>#{Lang['TotalConfirmed']}:</b> <code>#{country['TotalConfirmed']}</code>\n"\
                 "<b>#{Lang['TotalRecovered']}:</b> <code>#{country['TotalRecovered']}</code> "\
                 "(<i>#{country['TotalRecovered'].to_f/country['TotalConfirmed'].to_f*100}%</i>)\n"\
                 "<b>#{Lang['TotalDeaths']}:</b> <code>#{country['TotalDeaths']}</code> "\
                 "(<i>#{country['TotalDeaths'].to_f/country['TotalConfirmed'].to_f*100}%</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
end

open("https://api.covid19api.com/summary") do |raw_json|
    JSON.parse(raw_json.read)['Countries']
      .select { |e| e['CountryCode'] == Config['CountryCode'] }
      .each { |country| sendToTelegram country }
end
raw_json = Net::HTTP.get(URI("https://api.covid19api.com/summary"))
JSON.parse(raw_json)['Countries']
    .select { |e| e['CountryCode'] == Config['CountryCode'] }
    .each { |country| sendToTelegram country }


M config.example.yml => config.example.yml +6 -0
@@ 1,3 1,9 @@
CountryCode: 'PL'
TelegramToken: 'Your telegram token obtained from @BotFather'
TelegramChatId: '@your-channel-id'
Translation:
  StatusFor:        'Status for'
  For:              'for'
  TotalConfirmed:   'Total confirmed'
  TotalRecovered:   'Total recovered'
  TotalDeaths:      'Total deaths'