@Bloodtorn

Как исправить ошибку: Timeout context manager should be used inside a task?

def get_weather_fd(city, open_weather_token):
print("отработка def get_weather_fd")
global lon, lat
global temperature, def_city, wind_speed, temperature_feels, humandity, pressure, sunrise_time, sunset_time, timee, city_be, lengh_time
try:
cords = requests.get(f"http://api.openweathermap.org/geo/1.0/direct?q={ci...")
lon = cords.json()["lon"]
lat = cords.json()["lat"]

try:
req_openweather = requests.get(f"api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={open_weather_token}&units=metric")
data = req_openweather.json()
pprint(data)
except:
city_be = False
except Exception as ex:
city_be = False
print(ex)
print("не получилас(")
return

#функция прогнозы погоды на сегодня
def get_weather(city, open_weather_token):
print("отработка def get_weather")
global temperature, def_city, wind_speed, temperature_feels, humandity, pressure, sunrise_time, sunset_time, timee, city_be, lengh_time
try:
req_openweath = requests.get(f"http://api.openweathermap.org/data/2.5/weather?q={...")
data = req_openweath.json()
def_city = data["name"]
temperature = data["main"]["temp"]
temperature_feels = data["main"]["feels_like"]
wind_speed = data["wind"]["speed"]
humandity = data["main"]["humidity"]
pressure = data["main"]["pressure"]
sunrise_time = datetime.datetime.fromtimestamp(data["sys"]["sunrise"])
sunset_time = datetime.datetime.fromtimestamp(data["sys"]["sunset"])
timee = datetime.date.fromtimestamp(data["dt"])
lengh_time = sunset_time - sunrise_time
pprint(data)
city_be = True
return
except Exception as ex:
city_be = False
print(ex)
print("не получилас(")
return

#функция перевода времени формата ЧЧ:ММ в минуты
def take_min(timer: str, ii):
print("отработка def take min")
try:
for i in str(timer).split(':'):
if ii == 0:
timer = int(i) * 60
elif ii == 1:
timer = timer + int(i)
ii += 1
return timer
except:
can_countable = False
return can_countable

#функция получения погоды ct
async def get_weather_ct(city, open_weather_token, i):
print("отработка def get_weather_ct")
global temperature, def_city, wind_speed, temperature_feels, humandity, pressure, sunrise_time, sunset_time, timee, city_be, lengh_time
try:
req_openweath = requests.get(f"http://api.openweathermap.org/data/2.5/weather?q={...")
data = req_openweath.json()
def_city = data["name"]
temperature = data["main"]["temp"]
temperature_feels = data["main"]["feels_like"]
wind_speed = data["wind"]["speed"]
humandity = data["main"]["humidity"]
pressure = data["main"]["pressure"]
sunrise_time = datetime.datetime.fromtimestamp(data["sys"]["sunrise"])
sunset_time = datetime.datetime.fromtimestamp(data["sys"]["sunset"])
timee = datetime.date.fromtimestamp(data["dt"])
lengh_time = sunset_time - sunrise_time
pprint(data)
city_be = True
await bot.send_message(chat_id = user_id, text = "✅Информация о городе " + str(user_info[i]["city"]) + "\n\n****" + str(timee) + "****\nТемпература\n ->Температура: " + str(int(temperature)) + "°C\n ->Ощущается, как: " + str(int(temperature_feels)) + "°C\nДругая информация\n ->Влажность: " + str(humandity) + "%\n ->Давление: " + str(pressure) + "мм.рт.ст.\nИнформация о времени\n ->Время рассвета: " + str(sunrise_time) + "\n ->Время заката: " + str(sunset_time) + "\n ->Длина дня: " + str(lengh_time) + "", parse_mode = "HTML")
return
except Exception as ex:
city_be = False
print(ex)
print("не получилас(")
return

#функция старта таймера
def ct():
print("отработка def ct")
global temperature, temperature_feels, humandity, pressure, sunrise_time, sunset_time, timee, city_be, lengh_time
now_time = datetime.datetime.now()
now_timer = int(now_time.hour) * 60
now_timer += now_time.minute
while True:
print("Прохожу по спискам")
for i in range(len(user_info)):
print(user_info[i])
print(now_timer)
if now_timer == user_info[i]["timer"]:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(get_weather_ct(city = user_info[i]["city"], open_weather_token = open_weather_token, i = i))
loop.close()
"""await get_weather_ct(city=user_info[i]["city"], open_weather_token=open_weather_token)
await bot.send_message(chat_id = user_info[i]["user_id"], text = "✅Информация о городе " + str(user_info[i]["city"]) + "\n\n****" + str(timee) + "****\nТемпература\n ->Температура: " + str(int(temperature)) + "°C\n ->Ощущается, как: " + str(int(temperature_feels)) + "°C\nДругая информация\n ->Влажность: " + str(humandity) + "%\n ->Давление: " + str(pressure) + "мм.рт.ст.\nИнформация о времени\n ->Время рассвета: " + str(sunrise_time) + "\n ->Время заката: " + str(sunset_time) + "\n ->Длина дня: " + str(lengh_time) + "", parse_mode = "HTML")"""
#asyncio.run(get_weather_ct(city = user_info[i]["city"], open_weather_token = open_weather_token, i = i))
time.sleep(kd)
now_timer += 1
if now_timer == 1440:
now_timer = 0

#функция старта бота
async def main():
print("отработка async def main")
bot = Bot(token)
dp = Dispatcher()
dp.include_router(form_router)
await dp.start_polling(bot)

#функция старта thread
async def start_services():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(ct())
loop.close()
"""# submit the coroutine to the event loop thread
send_fut = asyncio.run_coroutine_threadsafe(ct(), loop = loop)
# wait for the coroutine to finish
send_fut.result()"""

t1 = Thread(target = ct, args = ())

#функция /timer
@form_router.message(Command("timer"))
async def timer_command(message: Message, state: FSMContext):
print("отработка async def timer_com")
if vip == True:
await message.answer(text = "❌Эта команда доступна только с випкой")
elif vip == False:
await state.set_state(Form.timerr)
await message.answer(text = "✅Меню оповещения\nВведи время (ЧЧ:ММ), в которое я буду отправлять тебе сводку с погодой, например вот-так: 12:30 или 07:10\n\nМожет быть погрешность в минуту", parse_mode = "HTML", reply_markup = ReplyKeyboardRemove())
@form_router.message(Form.timerr)
async def timer_takecity_command(message: Message, state: FSMContext):
print("отработка async def timer_takecity_com")
global timer
timer = take_min(timer=message.text, ii=0)
await state.set_state(Form.timer_city)
await message.answer(text = "Введи город, по которому я пришлю тебе сводку: ", reply_markup = ReplyKeyboardRemove())
@form_router.message(Form.timer_city)
async def timer_forcst_command(message: Message):
print("отработка async def timer_forcst_com")
global city_timer, timer
global temperature, temperature_feels, humandity, pressure, sunrise_time, sunset_time, timee, city_be, lengh_time
city_timer = message.text
user_info.append({"user_id": user_id,
"timer": timer,
"city": city_timer})

if __name__ == "__main__":
t1.start()
asyncio.run(main())
  • Вопрос задан
  • 243 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы