2

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

bot.message_handler(commands=['start'])
def welcome(message):
    sti = open('static/welcome.webp', 'rb')
    bot.send_sticker(message.chat.id, sti)

    # keyboard
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton("🎲 Рандомное число")
    item2 = types.KeyboardButton("😊 Как дела?")
    item3 = types.KeyboardButton("☁️ Погода")

    markup.add(item1, item2, item3)

    bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b>, бот созданный чтобы быть подопытным кроликом.".format(message.from_user, bot.get_me()),
        parse_mode='html', reply_markup=markup)

@bot.message_handler(content_types=['text'])
def lalala(message):
    if message.chat.type == 'private':
        if message.text == '🎲 Рандомное число':
            bot.send_message(message.chat.id, str(random.randint(0,100)))
        if message.text == '☁️ Погода':
            weather = bot.send_message(message.chat.id, "Введи название своего города пожалуйста.")

            @bot.message_handler(content_types=['text'])
            def prognoz(message):
                try:
                    observation = owm.weather_at_place(message.text) 
                    w = observation.get_weather()  
                    temp = w.get_temperature('celsius')["temp"]

                    answer = "В городе " + message.text + " сейчас " +  w.get_detailed_status() + "\n"
                    answer += "Температура сейчас в районе " + str(temp) + "\n\n"

                    if temp < 10:
                        answer += "Оденься потеплее"
                    elif temp < 20:
                        answer += "Сейчас холодно, надень шапку!"
                    else:
                        answer += "Погода класс!"

                    bot.send_message(message.chat.id, answer)
                except:
                    bot.send_message(message.chat.id, "Такого города не существуе, или я его ещё не знаю)\nПожалуйста введите другой город.")
        elif message.text == '😊 Как дела?':




            markup = types.InlineKeyboardMarkup(row_width=2)
            item1 = types.InlineKeyboardButton("Хорошо", callback_data='good')
            item2 = types.InlineKeyboardButton("Не очень", callback_data='bad')
            item3 = types.InlineKeyboardButton("Балдежь", callback_data='baldez')
            markup.add(item1, item2, item3)

            bot.send_message(message.chat.id, 'Отлично, сам как?', reply_markup=markup)



@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    try:
        if call.message:
            if call.data == 'good':
                bot.send_message(call.message.chat.id, 'Вот и отличненько 😊')
            elif call.data == 'bad':
                bot.send_message(call.message.chat.id, 'Бывает 😢')
            elif call.data == 'baldez':
                bot.send_message(call.message.chat.id, 'Великий балдежь')

            # remove inline buttons
            bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="😊 Как дела?",
                reply_markup=None)

            # show alert
            bot.answer_callback_query(callback_query_id=call.id, show_alert=False,
                text="Боты захватят мир!!11")

    except Exception as e:
        print(repr(e))


# RUN
bot.polling(none_stop=True)

2 ответа 2

3
@bot.message_handler(commands=['city'])
def cmd_city(message):
    send = bot.send_message(message.chat.id, 'Введи город')
    bot.register_next_step_handler(send, city)
    log(message)

def city(message):
    bot.send_message(message.chat.id, 'Ищу погоду в городе {city}'.format(city=message.text))
0

вот здесь два if подряд

Мне кажется, что в этой части кода не должно идти два if подряд, нужно прописать if и elif. Но я, конечно, могу ошибаться.

@bot.message_handler(content_types=['text'])
def lalala(message):
    if message.chat.type == 'private':
        if message.text == '🎲 Рандомное число':
            bot.send_message(message.chat.id, str(random.randint(0,100)))
        if message.text == '☁️ Погода':
            weather = bot.send_message(message.chat.id, "Введи название своего города пожалуйста.")

Ваш ответ

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

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