🌤 Урок 10: Погода через API

💡 Тепер бот буде отримувати реальні дані з інтернету через API.

📦 Встановлення requests

Python не вміє працювати з HTTP-запитами сам по собі, тому ми встановлюємо бібліотеку requests.
pip install requests
✔ pip — менеджер пакетів Python
✔ requests — бібліотека для API та HTTP
✔ через неї Python працює з інтернетом

🌍 API URL

Цей URL повертає JSON з погодою.
https://api.open-meteo.com/v1/forecast?latitude=49.84&longitude=24.03&current_weather=true
✔ latitude — широта
✔ longitude — довгота
✔ current_weather=true — поточна погода

🧠 Як рухаються дані

BOT → requests → API → JSON → Python → Telegram

🤖 Код бота

from bendbandbot import SimpleBot import requests from datetime import datetime # 🔑 читаємо токен with open("token.key", "r", encoding="utf-8") as f: token = f.read().strip() # 🤖 створюємо бота bot = SimpleBot(token) def weather(update): # 🌍 API погоди (Львів) url = "https://api.open-meteo.com/v1/forecast?latitude=49.84&longitude=24.03&current_weather=true" # 📡 HTTP запит response = requests.get(url) # 📦 JSON → Python dict data = response.json() # 🛡 перевірка відповіді if "current_weather" not in data: bot.send(update, "❌ Не вдалося отримати погоду") print(data) return # 🌤 поточна погода w = data["current_weather"] # 🌡 температура temperature = w["temperature"] # 💨 швидкість вітру wind = w["windspeed"] # 🕒 час raw_time = w["time"] # 🔄 ISO → datetime dt = datetime.fromisoformat(raw_time) # ✨ красивий формат nice_time = dt.strftime("%d.%m.%Y %H:%M") # 📤 відповідь bot.send(update, "🌤 Погода у Львові\n\n" f"🌡 Температура: {temperature}°C\n" f"💨 Вітер: {wind} км/год\n" f"🕒 Оновлено: {nice_time}" ) # 🎯 команда /weather bot.on_command("weather", weather) # 🚀 запуск bot.start()

📦 JSON відповідь API

API повертає JSON-об’єкт. Нас цікавить current_weather.
{ "current_weather": { "time": "2026-05-10T16:00", "temperature": 18.1, "windspeed": 6.5 } }
✔ data — увесь JSON
✔ current_weather — вкладений dict
✔ w["temperature"] — температура

🌍 Спробуй інші міста

📍 Львів: 49.84, 24.03
📍 Київ: 50.45, 30.52
📍 Одеса: 46.48, 30.73

🧪 Завдання

✍️ Зміни координати
✍️ Виведи weathercode
✍️ Подивись print(data)
✍️ Спробуй інше місто