O
O
oldziggy2022-04-11 00:03:23
Python
oldziggy, 2022-04-11 00:03:23

How to make the bot execute the command 1 time?

I am making a telegram bot in python using pyTelegramBotAPI.
The task is as follows: the bot, receiving the /weather command, asks the user what weather he needs to know in which city.
How to make it possible to get weather data only 1 time after the bot requested the name of the city?
Now you can endlessly enter cities, and the bot will display data.

import pyowm
from pyowm.owm import OWM
from pyowm.utils.config import get_default_config
import telebot
config_dict = get_default_config()
config_dict['language'] = 'ru'
owm = OWM('ded24f42ea01e055a761c651727ffaf3', config_dict)
mgr = owm.weather_manager()



bot = telebot.TeleBot("5188340734:AAHuYIaiLeL-3JQRGQwxcIFk_rUQP2kMd2c")

@bot.message_handler(commands=['weather'])
def send_message(message):
    bot.send_message(message.chat.id, "Введи название города.")
    @bot.message_handler(content_types = ['text'])
    def send_message(message):
        country = str("RU")
        city = (message.text)
        place = city + ", " + country

        observation = mgr.weather_at_place(message.text)
        w = observation.weather.detailed_status
        temp = temp_dict_celsius = observation.weather.temperature('celsius')

        answer = "Погода в городе " + city + ":" + "\n"
        answer += w + "\n"
        answer += "Температура воздуха " + str((temp['temp'])) + " по цельсию." + "\n"
        if temp['temp'] <= 0:
            answer += ('Стоит надеть пуховик!')
        elif (temp['temp'] >0) and (temp['temp'] <10):
            answer += ('Тепло будет и в легкой куртке!')
        elif (temp['temp'] >11) and (temp['temp'] <20):
            answer += ('Выходи без куртки, а то только вспотеешь.')
        elif temp['temp'] >= 20:
            answer += ('Лучше остаться дома и включить кондиционер')


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


@bot.message_handler(commands=['start'])
def send_welcome(message):
  bot.send_message(message.chat.id, "Это тренировочный бот. Введи /weather, чтобы узнать информацию о погоде.")




bot.infinity_polling()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2022-04-11
@oldziggy

Oh, well, this is all wrong.
No need to shove another send_message function inside send_message. They need to be brought to the same level. And in general, to name more adequately their content. After all, the first one processes the /weather command, and the second one processes the name of the city. It's strange to call them equally undefined send_message (so that the enemies don't guess?).
What is happening in this code? First, we register the /weather and /start command handlers with a decorator. When /weather is called, we EVERY time (after all, this is part of the handler function at the next level of nesting!) Re-define the handler for content_type=text. Further, after the first call to /weather, this handler starts working on all text messages. And on the messages of ALL users of our bot. That is, really, one calls /weather and thereby changes the behavior of the bot for all users at once. If another handler content_type=text is defined somewhere else in the bot with the same "internal" description, then it will always be ignored until the next restart of the bot, because there is already one text message handler and it will always be applied.
What is surprising in the fact that the bot works exactly as strangely as it is written in its code?
It should be understood that the message handler receives ONE message and processes it. He cannot receive the message and the next one immediately. Each will be processed by its handler. In order for message processing to depend on a number of messages, FSM (Finite State Machine), a state machine, is used. telebot has a pretty easy to use FSM based on register_next_step_handler call. Calling register_next_step_handler overrides which handler will handle the next message with this user (more precisely, in this chat_id, which can also be a group ID).
Actually, the principle of operation is as follows: when the user calls /weather, we must register a custom handler for the next message using the bot.register_next_step_handler call. This handler will only process messages from this user, this behavior will not affect other users. For more complex interactions, you can make long and even branching chains of handlers, ask the user for different data, offer to change previously entered data, etc., etc.
See the official usage example here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question