-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweatherBot.py
79 lines (69 loc) · 2.61 KB
/
weatherBot.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import telebot
import requests
import images_generation
TOKEN = "TOKEN"
key = "KEY"
api = "https://api.openweathermap.org/data/2.5/weather?q="
#{city name}&appid={API key}"
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=["start"])
def start_message(message):
bot.send_message(message.chat.id, text="Type your city and you will know the weather! ☁️")
@bot.message_handler(content_types=["text"])
def text_message(message):
city = message.text.strip()
result, description = get_weather(city)
if (result == "city not found"):
bot.send_message(message.chat.id, text="Next city 💋")
else:
image = images_generation.generate_picture(f"In the city {city} the weather is {description}")
if image is not None:
with open("generated_image.jpg", "rb") as file:
bot.send_photo(message.chat.id, file, caption=result)
else:
bot.send_message(message.chat.id, result)
@bot.inline_handler(lambda query: len(query.query) > 0)
def query_text(inline_query):
city = inline_query.query.strip()
result, description = get_weather(city)
if result == "city not found":
results = [
telebot.types.InlineQueryResultArticle(
id='1',
title="City not found!",
input_message_content=telebot.types.InputTextMessageContent(
message_text="Next city ❓"
)
)
]
else:
results = [
telebot.types.InlineQueryResultArticle(
id='1',
title=f"Weather in {city}",
input_message_content=telebot.types.InputTextMessageContent(
message_text=result
)
)
]
bot.answer_inline_query(inline_query.id, results)
def get_weather(city):
url = api + city + "&appid=" + key
response = requests.get(url).json()
if response["cod"] == 200:
return get_weather_info(response, city)
else:
return response["message"], None
def get_weather_info(response, city):
description = response["weather"][0]["description"]
temperature = round(response["main"]['temp'] - 273.15, 2) # Преобразование в Цельсии
temperature_feels = round(response['main']['feels_like'] - 273.15) # Преобразование в Цельсии
humidity = response["main"]['humidity']
info = f"""In the city {city} {description}
Temperature: {temperature} °C
Temperature feels like: {temperature_feels} °C
Humidity: {humidity}%
😎😎😎😎😎
"""
return info, description
bot.polling()