timezone fix

This commit is contained in:
2026-04-02 09:53:14 +03:00
parent e8544ebb38
commit 684a952158
3 changed files with 67 additions and 30 deletions

36
bot.py
View File

@@ -17,7 +17,8 @@ from weather import (
get_daily_weather_summary,
get_coords_by_city,
get_tomorrow_weather_summary,
get_weekly_weather_summary
get_weekly_weather_summary,
get_timezone_by_coords
)
import database as db # Импортируем нашу базу данных
@@ -90,22 +91,29 @@ async def cmd_change_city(message: types.Message, state: FSMContext):
async def process_location_input(message: types.Message, state: FSMContext):
user_id = message.from_user.id
city_name_display = "Выбранная локация"
timezone = None
if message.location:
lat = message.location.latitude
lon = message.location.longitude
# Для координат нужно определить часовой пояс отдельным запросом
timezone = await get_timezone_by_coords(lat, lon)
if not timezone:
await message.answer("Не удалось определить часовой пояс для вашей геопозиции. Попробуйте ввести название города.")
return
elif message.text:
lat, lon, found_name = await get_coords_by_city(message.text)
lat, lon, found_name, timezone = await get_coords_by_city(message.text)
if not lat:
await message.answer("К сожалению, я не нашел такой город 😔. Попробуй уточнить название.")
return
city_name_display = found_name
else:
return
# Сохраняем локацию в БД
await db.save_user_location(user_id, lat, lon)
# Сохраняем локацию и часовой пояс в БД
await db.save_user_location(user_id, lat, lon, timezone)
logging.info(f"Сохранена локация для {user_id}: lat={lat}, lon={lon}, timezone={timezone}")
# Проверяем, есть ли уже у пользователя настроенное время
user = await db.get_user(user_id)
if user and user["time"]:
@@ -114,7 +122,7 @@ async def process_location_input(message: types.Message, state: FSMContext):
else:
await state.set_state(WeatherSetup.waiting_for_time)
await message.answer(
f"Отлично! Локация **{city_name_display}** найдена.\n\nТеперь напиши время (в формате ЧЧ:ММ):",
f"Отлично! Локация **{city_name_display}** найдена (часовой пояс: {timezone}).\n\nТеперь напиши время для ежедневной рассылки (в формате ЧЧ:ММ):",
reply_markup=ReplyKeyboardRemove()
)
@@ -136,6 +144,12 @@ async def process_time(message: types.Message, state: FSMContext):
try:
dt = datetime.strptime(time_text, "%H:%M")
# Получаем пользователя, чтобы узнать его часовой пояс
user = await db.get_user(user_id)
if not user or not user["timezone"]:
await message.answer("Не удалось найти ваш часовой пояс. Пожалуйста, установите город заново (команда /start).")
return
# Сохраняем время в БД
await db.update_user_time(user_id, time_text)
@@ -144,8 +158,8 @@ async def process_time(message: types.Message, state: FSMContext):
scheduler.add_job(
send_weather_update,
trigger='cron',
hour=dt.hour,
minute=dt.minute,
hour=dt.hour, minute=dt.minute,
timezone=user["timezone"],
args=[user_id],
id=str(user_id),
replace_existing=True
@@ -204,8 +218,8 @@ async def restore_jobs():
scheduler.add_job(
send_weather_update,
trigger='cron',
hour=dt.hour,
minute=dt.minute,
hour=dt.hour, minute=dt.minute,
timezone=user["timezone"],
args=[user["user_id"]],
id=str(user["user_id"]),
replace_existing=True