-1

Когда в телеграме нажимаю на "Погода" и мне нужно ввести город или страну, я случайно ввёл не существующий город и код полетел, а как сделать так, чтобы когда пишешь не правильный город, тебе писалось, что выбран не существующий или же не правильный город. Заранее спасибо за помощь.

import telebot
import random
import pyowm

from telebot import types
from random import choice
from pyowm.owm import OWM
from pyowm.utils.config import get_default_config

#Токен телеграмм-бота
TOKEN = 'token_bot'
bot = telebot.TeleBot(TOKEN)

#Для погоды
owm = OWM('token_owm')
config_dict = get_default_config()
config_dict['language'] = 'ru'

#Для рандома
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, 'Выпадает' + "\n\n" + 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 + "\n"
    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
  • Ну как сделать - очень просто. Оформляешь обращение в конструкцию try-except и по ошибке код не будет падать. Описано в любом учебнике по Python. Или предварительно сам пишеш код проверки на наличие соответствующего города и "пропускаешь" только те запросы, в которых город введен корректно.
    – passant
    1 июн 2022 в 17:02

1 ответ 1

0

См. изменения в строке 45, решение через try-except

from telebot import types
from random import choice
from pyowm.owm import OWM
from pyowm.utils.config import get_default_config

import telebot
import random
import pyowm


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

#Для погоды
owm = OWM('token_owm')
config_dict = get_default_config()
config_dict['language'] = 'ru'

#Для рандома
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, 'Выпадает' + "\n\n" + 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()
    try:
        observation = mgr.weather_at_place(message.text)
    except pyowm.commons.exceptions.NotFoundError:
        answer = 'Простите, такого города похоже не существует :('
    else:
        w = observation.weather
        temp = w.temperature('celsius')["temp"]
        answer = f"В городе/стране, {message.text}, сейчас " + w.detailed_status + "\n"
        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('Программа остановлена!')

Ваш ответ

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

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