Сам код:
import vk_api
from vk_api.bot_longpoll import VkBotLongPoll
from vk_api.utils import get_random_id
from datetime import datetime
from requests import get
from pytz import timezone
class Weather:
def __init__(self, api):
self.api = api
self.city = 'Kaliningrad,RU'
self.city_word = 'Калиниграде'
def get_weather(self):
k = 273.15
weather = get(f"https://api.openweathermap.org/data/2.5/weather?q={self.city}&APPID={self.api}").json()
out = f"В {self.city_word} сейчас:\n" + \
f"Температура: {round(weather['main']['temp'] - k, 2)} °C\n" + \
f"По ощущениям: {round(weather['main']['feels_like'] - k, 2)} °C\n" + \
f"Ветер: {weather['wind']['speed']} м/с\n" + \
f"Статус погоды: {weather['weather'][0]['description']}\n" + \
f"Давление: {weather['main']['pressure']} гПа\n" + \
f"Влажность: {weather['main']['humidity']} %\n" + \
f"Восход солнца: {datetime.fromtimestamp(weather['sys']['sunrise']).strftime('%H:%M')}\n" + \
f"Заход солнца: {datetime.fromtimestamp(weather['sys']['sunset']).strftime('%H:%M')}"
return out
class Bot:
def __init__(self, access_token_group, group_id, weather_access_token):
self.access_token_group = access_token_group
self.group_id = group_id
self.weather = Weather(weather_access_token)
self.vk_session = vk_api.VkApi(token=access_token_group)
self.longpoll = VkBotLongPoll(self.vk_session, group_id=group_id)
self.vk = self.vk_session.get_api()
self.timezone = timezone('Europe/Kaliningrad')
print('The bot is running')
self.mainloop()
def send_message(self, peer_id, message=None, sticker_id=None, keyboard=None):
self.vk.messages.send(random_id=get_random_id(),
peer_id=peer_id,
keyboard=keyboard,
message=message,
sticker_id=sticker_id)
def message_handling(self, event):
request = event.object['message']['text'].lower()
if request[0] == '!':
if 'time' in request or 'врем' in request:
time = datetime.now(self.timezone)
if 'exact' in request or 'точн' in request:
self.send_message(event.object['message']['peer_id'],
message=f'На моих (точных) часах: {time.time().isoformat()}')
else:
self.send_message(event.object['message']['peer_id'],
message=f'На моих часах: ' +
f'{time.strftime("%H:%M:%S")}')
elif 'date' in request or 'дат' in request:
date = datetime.now(self.timezone)
self.send_message(event.object['message']['peer_id'],
message=f'У меня сейчас: {date.strftime("%d-%m-%Y")}')
elif 'weather' in request or 'погод' in request:
self.send_message(event.object['message']['peer_id'],
message=self.weather.get_weather())
def mainloop(self):
while True:
try:
for event in self.longpoll.listen():
if not event.object.message['text'] == '':
self.message_handling(event)
except Exception as error:
print(error)
Bot('Токен вк',
'ид группы',
'api сайта с погодой')