Guest User

Untitled

a guest
Dec 30th, 2016
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.48 KB | None | 0 0
  1. require 'telegram/bot'
  2. require 'accuweather'
  3. require 'yandex-translator'
  4. token = '***'
  5.  
  6. class Float
  7.     def to_cel
  8.         (self-32)*5/9
  9.     end
  10. end
  11.  
  12. module Answer
  13.     TRANSLATOR = Yandex::Translator.new('***')
  14.     RE = /(\/\w*)(\s)/
  15.  
  16.     def self.command_extraction message
  17.         match1 = message.text.match RE
  18.         begin
  19.             match1[1]
  20.         rescue
  21.             nil
  22.         end
  23.     end
  24.  
  25.     def self.content_extraction message
  26.         message.text.sub RE, ""
  27.     end
  28.  
  29.     @translation_of = lambda do |word|
  30.         ans = TRANSLATOR.translate word, to: 'ru'
  31.     end
  32.  
  33.     @weather_of = lambda do |word|
  34.         city = Accuweather.city_search(name: word).first
  35.         if city
  36.             current_weather = Accuweather.get_conditions(location_id: city.id).current
  37.             temp = current_weather.temperature.to_f.to_cel.round
  38.             sky = current_weather.weather_text
  39.             real_feel = current_weather.real_feel.to_f.to_cel.round
  40.             ans = "#{temp} C, #{sky}, real_feel: #{real_feel}"
  41.         end
  42.     end
  43.  
  44.     ACTION = {'/trans' => @translation_of, '/weather' => @weather_of}
  45.  
  46.     def answer message
  47.         command = command_extraction message
  48.         action = ACTION.fetch(command, nil)
  49.         if action
  50.             action.call content_extraction message
  51.         else
  52.             nil
  53.         end
  54.     end
  55.  
  56.     module_function :answer
  57.     class << self
  58.         private :command_extraction, :content_extraction
  59.     end
  60. end
  61.  
  62.  
  63. Telegram::Bot::Client.run(token) do |bot|
  64.     bot.listen do |message|
  65.         answer = Answer.answer message
  66.         begin
  67.             bot.api.sendMessage(chat_id: message.chat.id, text: answer)
  68.         rescue
  69.             nil
  70.         end
  71.     end
  72. end
Advertisement
Add Comment
Please, Sign In to add comment