forked from pythontoday/weather_telegram_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_weather_tg_bot.py
65 lines (51 loc) · 2.52 KB
/
main_weather_tg_bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import requests
import datetime
from config import tg_bot_token, open_weather_token
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
bot = Bot(token=tg_bot_token)
dp = Dispatcher(bot)
@dp.message_handler(commands=["start"])
async def start_command(message: types.Message):
await message.reply("Привет! Напиши мне название города и я пришлю сводку погоды!")
@dp.message_handler()
async def get_weather(message: types.Message):
code_to_smile = {
"Clear": "Ясно \U00002600",
"Clouds": "Облачно \U00002601",
"Rain": "Дождь \U00002614",
"Drizzle": "Дождь \U00002614",
"Thunderstorm": "Гроза \U000026A1",
"Snow": "Снег \U0001F328",
"Mist": "Туман \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_smile:
wd = code_to_smile[weather_description]
else:
wd = "Посмотри в окно, не пойму что там за погода!"
humidity = data["main"]["humidity"]
pressure = data["main"]["pressure"]
wind = data["wind"]["speed"]
sunrise_timestamp = datetime.datetime.fromtimestamp(data["sys"]["sunrise"])
sunset_timestamp = datetime.datetime.fromtimestamp(data["sys"]["sunset"])
length_of_the_day = datetime.datetime.fromtimestamp(data["sys"]["sunset"]) - datetime.datetime.fromtimestamp(
data["sys"]["sunrise"])
await message.reply(f"***{datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}***\n"
f"Погода в городе: {city}\nТемпература: {cur_weather}C° {wd}\n"
f"Влажность: {humidity}%\nДавление: {pressure} мм.рт.ст\nВетер: {wind} м/с\n"
f"Восход солнца: {sunrise_timestamp}\nЗакат солнца: {sunset_timestamp}\nПродолжительность дня: {length_of_the_day}\n"
f"***Хорошего дня!***"
)
except:
await message.reply("\U00002620 Проверьте название города \U00002620")
if __name__ == '__main__':
executor.start_polling(dp)