-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather_send_bot.py
More file actions
151 lines (124 loc) · 7.17 KB
/
weather_send_bot.py
File metadata and controls
151 lines (124 loc) · 7.17 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# импортим либы
import telebot
from pyowm import OWM
from pyowm.utils.config import get_default_config
from datetime import datetime, timedelta
# задаем язык и api ключи
config_dict = get_default_config()
config_dict['language'] = 'ru'
owm = OWM('api-owm-key', config_dict)
mgr = owm.weather_manager()
bot = telebot.TeleBot('api-telegram-key')
print('Бот работает')
# функция старт
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, 'Привет! Я бот для отправки погоды.\nИспользуй команды:\n/weather <город> \n/forecast <город>')
print(f'Отправлено приветствие {message.from_user.id}')
# функция текущая погода
@bot.message_handler(commands=['weather'])
def weather_now(message):
try:
# срезаем только город с ответа
city = message.text[9:]
observation = mgr.weather_at_place(city)
w = observation.weather
# показатели
temp = round(w.temperature('celsius')['temp'])
status = w.detailed_status
hum = w.humidity
wind = round(w.wind()['speed'])
# добавляем к статусу соответствующий смайлик
if 'ясно' in str(w.detailed_status):
smile = '☀️'
elif 'небольшая облачность' in str(w.detailed_status) or 'переменная облачность' in str(w.detailed_status):
smile = '🌤️'
elif 'облачно с прояснениями' in str(w.detailed_status):
smile = '⛅'
elif 'пасмурно' in str(w.detailed_status) or 'полностью облачно' in str(w.detailed_status):
smile = '☁️'
elif 'кратковременный дождь' in str(w.detailed_status):
smile = '🌧️'
elif 'дождь' in str(w.detailed_status):
smile = '☔'
elif 'гроза' in str(w.detailed_status):
smile = '⛈️'
elif 'снег' in str(w.detailed_status):
smile = '❄️'
elif 'туман' in str(w.detailed_status):
smile = '🌫️'
else:
smile = ''
# склоняем градусы
if 1 == int(temp):
grad = 'градус'
elif 2 <= int(temp) <= 4 or -2 >= int(temp) >= -4:
grad = 'градуса'
else:
grad = 'градусов'
# формируем ответ и отправляем его
text = f"В городе {city} сейчас {status}{smile}\n🌡️ Температура: {temp} {grad} по Цельсию.\n💨 Ветер: {wind} м\с\n💧 Текущая влажность составляет {hum} %"
bot.send_message(message.chat.id, text)
print(f'Отправлена текущая погода пользователю {message.from_user.id}')
# если что-то пошло не так, отправляем сообщение пользователю об ошибке
except:
bot.send_message(message.chat.id, f'Упс, что-то пошло не так. \nСкорее всего \'{city}\' не город.\nПроверьте правильность написания названия города.')
print(f'Ошибка в текущей погоде у пользователя {message.from_user.id}')
# функция прогноз
@bot.message_handler(commands=['forecast'])
def weather_tomorrow(message):
try:
# задаем дату завтрашнего дня
tomorrow = (datetime.now() + timedelta(days=1)).replace(hour=12, minute=0, second=0, microsecond=0)
# срезаем только город с ответа
city = message.text[10:]
mgr = owm.weather_manager()
forecaster = mgr.forecast_at_place(city, '3h')
# перебираем всю погоду за 3 часа(потому что меньше чем на 3 часа нельзя делать прогноз)
for weather in forecaster.forecast:
date = datetime.fromtimestamp(weather.reference_time())
if date >= tomorrow:
# показатели
status = weather.detailed_status
temp = round(weather.temperature('celsius')['temp'])
hum = weather.humidity
wind = round(weather.wind()['speed'])
# добавляем к статусу соответствующий смайлик
if 'ясно' in str(weather.detailed_status):
smile = '☀️'
elif 'небольшая облачность' in str(weather.detailed_status) or 'переменная облачность' in str(weather.detailed_status):
smile = '🌤️'
elif 'облачно с прояснениями' in str(weather.detailed_status):
smile = '⛅'
elif 'пасмурно' in str(weather.detailed_status) or 'полностью облачно' in str(weather.detailed_status):
smile = '☁️'
elif 'кратковременный дождь' in str(weather.detailed_status):
smile = '🌧️'
elif 'дождь' in str(weather.detailed_status):
smile = '☔'
elif 'гроза' in str(weather.detailed_status):
smile = '⛈️'
elif 'снег' in str(weather.detailed_status):
smile = '❄️'
elif 'туман' in str(weather.detailed_status):
smile = '🌫️'
else:
smile = ''
# склоняем градусы
if str(1) in str(temp):
grad = 'градус'
elif 2 <= int(temp) <= 4 or -2 >= int(temp) >= -4:
grad = 'градуса'
else:
grad = 'градусов'
# формируем ответ и отправляем его
text = f'Завтра в городе {city} будет {status}{smile}\n🌡️ Температура: {temp} {grad} по Цельсию\n💨 Ветер: {wind} м\с\n💧 Влажность будет составлять {hum} %'
bot.send_message(message.chat.id, text)
print(f'Отправлен прогноз пользователю {message.from_user.id}')
break
# если что-то пошло не так, отправляем сообщение пользователю об ошибке
except:
bot.send_message(message.chat.id, f'Упс, что-то пошло не так. \nСкорее всего \'{city}\' не город.\nПроверьте правильность написания названия города.')
print(f'Ошибка в прогнозе у пользователя {message.from_user.id}')
bot.polling()
print('Бот выключен')