Fix command detection and improve weather timing

This commit is contained in:
2026-02-02 23:30:57 +03:00
parent 845ef7c531
commit a61f526ce4
5 changed files with 38 additions and 18 deletions

View File

@@ -74,19 +74,23 @@ def _command_exists(command):
True, если команда существует True, если команда существует
""" """
try: try:
subprocess.run(["which", command], result = subprocess.run(
["which", command],
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
check=False) check=False,
return True )
return result.returncode == 0
except: except:
try: try:
# Альтернативная проверка для Windows # Альтернативная проверка для Windows
subprocess.run(["where", command], result = subprocess.run(
["where", command],
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
check=False) check=False,
return True )
return result.returncode == 0
except: except:
return False return False

View File

@@ -38,6 +38,8 @@ def _send_request(messages, max_tokens, temperature, error_text):
temperature: "Креативность" (0.2 - строго, 1.0 - креативно). temperature: "Креативность" (0.2 - строго, 1.0 - креативно).
error_text: Текст ошибки для пользователя в случае сбоя. error_text: Текст ошибки для пользователя в случае сбоя.
""" """
if not PERPLEXITY_API_KEY:
return "Не настроен PERPLEXITY_API_KEY. Проверьте файл .env."
headers = { headers = {
"Authorization": f"Bearer {PERPLEXITY_API_KEY}", "Authorization": f"Bearer {PERPLEXITY_API_KEY}",
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -102,6 +104,9 @@ def ask_ai_stream(messages_history: list):
""" """
Generator that yields chunks of the AI response as they arrive. Generator that yields chunks of the AI response as they arrive.
""" """
if not PERPLEXITY_API_KEY:
yield "Не настроен ключ PERPLEXITY_API_KEY. Проверьте файл .env."
return
if not messages_history: if not messages_history:
yield "Извините, я не расслышал вашу команду." yield "Извините, я не расслышал вашу команду."
return return

View File

@@ -271,7 +271,12 @@ class SpotifyMusicController:
r"(следующ|дальше|скип|пропусти|next|skip)", r"(следующ|дальше|скип|пропусти|next|skip)",
] ]
for pattern in next_patterns: for pattern in next_patterns:
if re.search(pattern, text_lower) and "трек" in text_lower or "песн" in text_lower or "skip" in text_lower or "next" in text_lower: if re.search(pattern, text_lower) and (
"трек" in text_lower
or "песн" in text_lower
or "skip" in text_lower
or "next" in text_lower
):
return self.next_track() return self.next_track()
# Предыдущий трек # Предыдущий трек

View File

@@ -427,12 +427,17 @@ def get_weather_report(requested_city: str = None) -> str:
report += f" Сегодня температура будет от {get_temperature_text(t_min)} до {get_temperature_text(t_max)}." report += f" Сегодня температура будет от {get_temperature_text(t_min)} до {get_temperature_text(t_max)}."
# --- 3. Forecast Next 4 Hours --- # --- 3. Forecast Next 4 Hours ---
current_hour = datetime.now().hour
hourly_temps = data["hourly"]["temperature_2m"] hourly_temps = data["hourly"]["temperature_2m"]
hourly_precip = data["hourly"]["precipitation"] hourly_precip = data["hourly"]["precipitation"]
hourly_codes = data["hourly"]["weather_code"] hourly_codes = data["hourly"]["weather_code"]
hourly_times = data["hourly"].get("time", [])
# Start from next hour # Start from the next hour based on the API's current time (timezone-aware for the location).
current_time_iso = data.get("current", {}).get("time")
if current_time_iso and current_time_iso in hourly_times:
start_idx = hourly_times.index(current_time_iso) + 1
else:
current_hour = datetime.now().hour
start_idx = current_hour + 1 start_idx = current_hour + 1
end_idx = min(start_idx + 4, len(hourly_temps)) end_idx = min(start_idx + 4, len(hourly_temps))

View File

@@ -49,6 +49,7 @@ from .audio.wakeword import (
stop_monitoring as stop_wakeword_monitoring, stop_monitoring as stop_wakeword_monitoring,
) )
from .core.ai import ask_ai_stream, translate_text from .core.ai import ask_ai_stream, translate_text
from .core.config import BASE_DIR
from .core.cleaner import clean_response from .core.cleaner import clean_response
from .core.commands import is_stop_command from .core.commands import is_stop_command
from .features.alarm import get_alarm_clock from .features.alarm import get_alarm_clock
@@ -164,9 +165,9 @@ def main():
except Exception as exc: except Exception as exc:
print(f"Warning: pygame mixer init failed; sound effects disabled. ({exc})") print(f"Warning: pygame mixer init failed; sound effects disabled. ({exc})")
else: else:
ding_sound_path = "assets/sounds/ding.wav" ding_sound_path = BASE_DIR / "assets" / "sounds" / "ding.wav"
if os.path.exists(ding_sound_path): if ding_sound_path.exists():
ding_sound = mixer.Sound(ding_sound_path) ding_sound = mixer.Sound(str(ding_sound_path))
ding_sound.set_volume(0.3) ding_sound.set_volume(0.3)
else: else:
print(f"⚠️ Звук {ding_sound_path} не найден") print(f"⚠️ Звук {ding_sound_path} не найден")