0

При нажатии на кнопку "Random" - всё работает.
При нажатии на кнопку "Погода" - код умерает.

import telebot
import random
import pyowm

from telebot import types
from random import choice
from pyowm.owm import OWM

TOKEN = 'токен'
bot = telebot.TeleBot(TOKEN)

owm = pyowm.OWM('токен')

number = ['00', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '1st 12', '2nd 12', '3rd 12', '2 to 1 (верхний)', '2 to 1 (средний)', '2 to 1 (нижний)', '1 to 18', 'EVEN', 'На красное', 'На чёрное', 'ODD', '19 to 36']

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard = True)
    item1 = types.KeyboardButton('Random🎲')
    item2 = types.KeyboardButton('Погода🌤')

    markup.add(item1, item2)

    bot.send_message(message.chat.id, 'Привет, {0.first_name}! Выбери две любые кнопки!' .format(message.from_user), reply_markup = markup)

@bot.message_handler(content_types=['text'])
def send_echo(message):
    if message.chat.type == 'private':
        if message.text == 'Random🎲':
            bot.send_message(message.chat.id, str(random.choice(number)))
        elif message.text == 'Погода🌤':
            bot.send_message(message.chat.id, 'В каком городе/стране?')
            mgr = owm.weather_manager()
            observation = mgr.weather_at_place(message.text)
            w = observation.get_weather()
            temp = w.get_temperature('celsius')["temp"]
            answer = "В городе/стране" + message.text + "сейчас" + w.get_detailed_status()
            answer += "Температура сейчас в районе" + str(temp) + "\n\n"
            if temp < 10:
                answer += "Сейчас холодно! Оденьтесь теплее." 
            elif temp < 20:
                answer += "Сейчас температура в норме. Одевайте что пожалаете"
            else:
                answer += "Сейчас очень жарко! Советуем сходить на речку, соблюдая все правила!"

            bot.send_message(message.chat.id, answer)


print('Программа запущена, можете писать боту.')

#Запуск бота
bot.polling(none_stop = True)

print('Программа остановлена!')

Ошибка

Программа запущена, можете писать боту.
Traceback (most recent call last):
  File "C:\Users\Farente\Documents\Python\senderfuckingbot.py", line 56, in <module>
    bot.polling(none_stop = True)
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 620, in polling
    self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 694, in __threaded_polling
    raise e
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 650, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\util.py", line 143, in raise_exceptions
    raise self.exception_info
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\util.py", line 89, in run
    task(*args, **kwargs)
  File "C:\Users\Farente\Documents\Python\senderfuckingbot.py", line 38, in send_echo
    observation = mgr.weather_at_place(message.text)
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\pyowm\weatherapi25\weather_manager.py", line 53, in weather_at_place
    _, json_data = self.http_client.get_json(OBSERVATION_URI, params=params)
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\pyowm\commons\http_client.py", line 158, in get_json
    HttpClient.check_status_code(resp.status_code, resp.text)
  File "C:\Users\Farente\AppData\Local\Programs\Python\Python310\lib\site-packages\pyowm\commons\http_client.py", line 315, in check_status_code
    raise exceptions.NotFoundError('Unable to find the resource')
pyowm.commons.exceptions.NotFoundError: Unable to find the resource

1 ответ 1

0

У тебя message.text равен "Погода🌤", у нас ведь нет города под названием "Погода🌤" ?

observation = mgr.weather_at_place(message.text)

Вот полностью готовый код:

import telebot
import random
import pyowm

from telebot import types
from random import choice
from pyowm.owm import OWM

TOKEN = 'token_bot'
bot = telebot.TeleBot(TOKEN)

owm = OWM('token_own')

number = ['00', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '1st 12', '2nd 12', '3rd 12', '2 to 1 (верхний)', '2 to 1 (средний)', '2 to 1 (нижний)', '1 to 18', 'EVEN', 'На красное', 'На чёрное', 'ODD', '19 to 36']

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard = True)
    item1 = types.KeyboardButton('Random🎲')
    item2 = types.KeyboardButton('Погода🌤')

    markup.add(item1, item2)

    bot.send_message(message.chat.id, 'Привет, {0.first_name}! Выбери две любые кнопки!' .format(message.from_user), reply_markup = markup)

@bot.message_handler(content_types=['text'])
def send_echo(message):
    if message.chat.type == 'private':
        if message.text == 'Random🎲':
            bot.send_message(message.chat.id, str(random.choice(number)))
        elif message.text == 'Погода🌤':
            msg = bot.send_message(message.chat.id, 'В каком городе/стране?')
            bot.register_next_step_handler(msg, message_city)

def message_city(message):
    mgr = owm.weather_manager()
    observation = mgr.weather_at_place(message.text)
    w = observation.weather
    temp = w.temperature('celsius')["temp"]
    answer = f"В городе/стране {message.text} сейчас {w.detailed_status}"
    answer += "\nТемпература сейчас в районе " + str(temp) + "\n\n"
    if temp < 10:
        answer += "Сейчас холодно! Оденьтесь теплее." 
    elif temp < 20:
        answer += "Сейчас температура в норме. Одевайте что пожалаете"
    else:
        answer += "Сейчас очень жарко! Советуем сходить на речку, соблюдая все правила!"

    bot.send_message(message.chat.id, answer)


print('Программа запущена, можете писать боту.')

#Запуск бота
bot.polling(none_stop = True)

print('Программа остановлена!')
1
  • 1
    Спасибо большое, не знал как исправить. Тоже думал, что ругается на Погода и то, что такого города нет. Ещё раз, спасибо. 1 июн 2022 в 14:56

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.