Home>

I have a weather forecast code, I need it so that when I click on the "Weather Forecast" button in the bot menu, the bot sends a message, enter the city, you enter the city and it sends the weather according to the code,

dp.message_handler()
async def get_weather(message: types.Message):
    code_to_smie= {
        "Clear": "Clear \U00002600",
        "Clouds": "Cloudy \U00002601",
        "Rain": "Rain \U00002614",
        "Drizzle": "Rain \U00002614",
        "Thunderstorm": "Thunderstorm \U000026A1",
        "Snow": "Snow \U0001F328",
        "Mist": "Fog \U0001F32B"
    }
    try:
        r= requests.get(
            f"http://api.openweathermap.org/data/2.5/weather?q={message.text}&
appid={open_weather_token}&
units=metric"
        )
        data= r.json()
        city ​​= data["name"]
        cur_weather= data["main"]["temp"]
        weather_description= data["weather"][0]["main"]
        if weather_description in code_to_smie:
            wd= code_to_smie[weather_description]
        else:
            wd= "Look out the window, I don't know what the weather is like!"
        humidity= data["main"]["humidity"]
        pressure= data["main"]["pressure"]
        wind= data["wind"]["speed"]
        await message.reply(f"Weather in city: {city}\nTemperature: {cur_weather}° {wd}\n"
            f"Humidity: {humidity}%\nPressure: {pressure} mmHg\nWind: {wind} m/s\nHave a nice day!")
    except:
        await message.reply('Check city name')

please help me, I tried everything in my power, I didn’t think of it

  • Answer # 1

    You need to learn the states in the aiogram, the so-called FSM (Final State Machine).

    There is enough information about these states on the Internet, the official documentation has a good one.

    In general, the logic of work is as follows:

    1. Create a list of states (in your case, one is enough -this is a city)
    class Town(StatesGroup):
        town= State()
    
    1. Write a handler -you will need to pass it in addition to the argumentmessagealso an argumentstate, and in the decorator itself specify thatstateto which you want to go. For example:
    async def test(message: types.Message):
        await bot.send_message(message.chat.id, "Enter your city")
        await Town.town.set()
    @dp.message_handler(state=Town.town)
    async def get_town(message: types.Message, state: FSMContext)
        await bot.send_message(message.chat.id, f"Your city is {message.text}")
        await state.finish()
    

    Also in eachstateyou can write down some information, and retrieve it in any other specified by youstate(obviously -this is just a dictionary that is allocated for each user).