20
Мар
2020

Как правильно обработать исключение pyowm при неправильно введенном названии города?

Я создал бот-телеграмму из python, которая показывает погоду, если вы неправильно ввели название города, сразу в консоли:

 2020-03-20 20:36:35,839 (util.py:66 WorkerThread1) ERROR - TeleBot: "NotFoundError occurred, args=('Unable to find the resource',)
Traceback (most recent call last):
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\util.py", line 60, in run
    task(*args, **kwargs)
  File "E:\Python\telegram.py", line 9, in send_echo
    observation = owm.weather_at_place(message.text)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\weatherapi25\owm25.py", line 231, in weather_at_place
    _, json_data = self._wapi.cacheable_get_json(uri, params=params)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 87, in cacheable_get_json
    status_code, data = self.get_json(uri, params=params, headers=headers)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 32, in get_json
    HttpClient.check_status_code(resp.status_code, resp.text)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 155, in check_status_code
    raise api_response_error.NotFoundError('Unable to find the resource')
pyowm.exceptions.api_response_error.NotFoundError: The searched item was not found.
Reason: Unable to find the resource
"
Traceback (most recent call last):
  File "E:\Python\telegram.py", line 25, in <module>
    bot.polling( none_stop = True)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\__init__.py", line 392, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\__init__.py", line 416, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\util.py", line 109, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\util.py", line 60, in run
    task(*args, **kwargs)
  File "E:\Python\telegram.py", line 9, in send_echo
    observation = owm.weather_at_place(message.text)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\weatherapi25\owm25.py", line 231, in weather_at_place
    _, json_data = self._wapi.cacheable_get_json(uri, params=params)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 87, in cacheable_get_json
    status_code, data = self.get_json(uri, params=params, headers=headers)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 32, in get_json
    HttpClient.check_status_code(resp.status_code, resp.text)
  File "C:\Users\мохиржон\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 155, in check_status_code
    raise api_response_error.NotFoundError('Unable to find the resource')
pyowm.exceptions.api_response_error.NotFoundError: The searched item was not found.
Reason: Unable to find the resource

я делаю заметку, которая гласит: «Название города было неверно введено в бот».

Источник: https://ru.stackoverflow.com/questions/1097398/%D0%9A%D0%B0%D0%BA-%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%BE-%D0%BE%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D1%82%D1%8C-%D0%B8%D1%81%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-pyowm-%D0%BF%D1%80%D0%B8-%D0%BD%D0%B5%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%BE-%D0%B2%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%BD%D0%BE%D0%BC-%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D0%B8-%D0%B3%D0%BE%D1%80
Share

Тебе может это понравится...

1 Ответ

  1. Vania Kharyton:

    Пример кода:

    import telebot
    import pyowm

    owm = pyowm.OWM('key', language = "ru")
    bot = telebot.TeleBot('token')

    @bot.message_handler(content_types=['text'])
    def send_echo(message):
    try:
    observation = owm.weather_at_place( message.text )
    w = observation.get_weather()
    temp = w.get_temperature('celsius')["temp"]
    hum = w.get_humidity()
    time = w.get_reference_time(timeformat='iso')
    wind = w.get_wind()["speed"]

    answer ="В городе " + message.text + " сейчас " + w.get_detailed_status() + "\n"
    answer += "Температура сейчас в районе " + str(temp) + "\n\n" + "\nСкорость ветра: " + str(wind) + "м/с" + "\n" + "\nВлажность: " + str(hum) + "%" + "\n" + "\nВремя: " + str(time) + "\n"

    if temp < 11:
    answer += "Сейчас руки засерзнут."
    elif temp < 20:
    answer += "коленки трясутся."
    else:
    answer += "ЖГИ,малышка"

    bot.send_message(message.chat.id, answer)
    except:
    bot.send_message(message.chat.id,'Ошибка! Город не найден.')
    bot.polling( none_stop = True)
    input()

    ____________________
    Не забудь сменить токен телеграм бота і ключ pyowm.
    Всегда пожалуйста.