-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.py
More file actions
75 lines (54 loc) · 2.54 KB
/
Copy pathAPI.py
File metadata and controls
75 lines (54 loc) · 2.54 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
import telebot
import requests
import json
bot = telebot.TeleBot('8275243110:AAE24Zad8mxJxe6PMY6D_lAm6p6agYolXII')
API = '835b099ace154b116e1370b87dff6898'
user_city = {}
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, 'Привіт напиши назву свого города.')
@bot.message_handler(content_types=['text'])
def get_city(message):
city = message.text.strip().capitalize()
res = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API}&units=metric')
if res.status_code != 200:
bot.send_message(message.chat.id, 'Місто не знайдено.')
return
user_city[message.chat.id] = city
markup = telebot.types.InlineKeyboardMarkup()
markup.row(
telebot.types.InlineKeyboardButton('Погода', callback_data='weather'),
telebot.types.InlineKeyboardButton('Вітер', callback_data='wind')
)
markup.row(
telebot.types.InlineKeyboardButton('Все', callback_data='all')
)
bot.send_message(message.chat.id, 'Виберіть опцію:', reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
print(f"Отримано callback: {call.data}")
city = user_city.get(call.message.chat.id)
if not city:
bot.send_message(call.message.chat.id, 'Спочатку введіть назву міста.')
return
res = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API}&units=metric')
data = json.loads(res.text)
temp = data['main']['temp']
wind = data['wind']['speed']
file = None
image = None
if call.data == 'weather':
bot.send_message(call.message.chat.id, f'Погода зараз {temp} граудсів цельсія.')
image = 'sun.png' if temp > 10.0 else 'cloudy.png'
file = open('./' + image, 'rb')
bot.send_photo(call.message.chat.id, file)
elif call.data == 'wind':
bot.send_message(call.message.chat.id, f'Швидкість вітру {wind}км/ч.')
image = 'wind.png' if wind > 13.0 else 'sun.png'
file = open('./' + image, 'rb')
bot.send_photo(call.message.chat.id, file)
elif call.data == 'all':
bot.send_message(call.message.chat.id, f'Погода {temp}°C.\nШвидкість вітру {wind}км/ч.')
else:
bot.send_message(call.message.chat.id, 'Неправельно написаний город.')
bot.polling(none_stop=True, interval=0, timeout=20)