Search code examples
rubygeolocationtelegram-bot

Can't get longitude and latitude in telegram-bot-ruby


I have a problem. Where I must add message.location.latitude command to get the user's location after getting message with location. I have to replace geocode with user's location requested earlier. Thank's for advice.

require 'open_weather'
require 'telegram/bot'

options_OpenWeather = { units: "metric", APPID: "some text" }
options_Bot = 'some keys'

Telegram::Bot::Client.run(options_Bot) do |bot|

bot.listen do |message|
  kb = [
        Telegram::Bot::Types::KeyboardButton.new(text: 'Show me your location', request_location: true)           
       ]
       markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: kb)

       pp weather = OpenWeather::Current.geocode(53.11, 23.36, options_OpenWeather)
  case message.text
    when '/start'
      bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}!")
    when '/end'
      bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}!")     
    when '/help'
      bot.api.send_message(chat_id: message.chat.id, text: "Available commands:
      /start
      /end
      /help
      /hi
      /weather
      /test")
    when '/hi' 
      bot.api.send_message(chat_id: message.chat.id, text: 'Hey!', reply_markup: markup)         
     when '/weather'
      bot.api.send_message(chat_id: message.chat.id, text: "Weather in your location: #{weather["main"]["temp"]} celcius, #{weather["main"]["pressure"]} hPa. Humidity is #{weather["main"]["humidity"]}% ")                    
    when '/test'
      bot.api.send_message(chat_id: message.chat.id, text:"I'm testing command")
    else
      bot.api.send_message(chat_id: message.chat.id, text: "I don't understand you 😕")
    end
  end
end

Solution

  • I would add this before your case and move all this handling weather stuff to some separate function. But I fell I'm not anwsering your question and writing here some obvious stuff. You can look at my bot's front-end. It's quite old and messy implementation I did a long time ago, but It works. Maybe you can do also some caching with redis if you want your users to save locations and just send comands after they set their location for the first time.

    def(lat, lng)
      return OpenWeather::Current.geocode(lat, lng, options_OpenWeather)
      ...
    end
    
    if message.location != nil
      weather = handle_weather_from_location(
        message.location.lattitude
        message.location.longitude
      )
      bot.api.send_message(chat_id: message.chat.id, text: "Weather in your location: #{weather["main"]["temp"]} celcius, #{weather["main"]["pressure"]} hPa. Humidity is #{weather["main"]["humidity"]}% ")                    
    end