· 6 years ago · Apr 02, 2020, 02:44 AM
1#! /usr/bin/env python
2# -*- coding: utf-8 -*-
3import vk_api
4from vk_api.bot_longpoll import VkBotLongPoll
5from vk_api.utils import get_random_id
6from datetime import datetime, timezone
7import datetime
8import time
9import random
10import pyowm
11import requests, json # Модуль для обработки URL
12from bs4 import BeautifulSoup # Модуль для работы с HTML
13
14
15
16vk = vk_api.VkApi(token='3709764b230f73dbf6a6fca9c41e726af8c0e28eff5ea171f2e25d6b5d3761711e9cf46b77cbf3d7c47ba') #токен паблика
17
18class MyVkLongPoll(VkBotLongPoll): # создаю класс чтобы он не терял соединение с сервером вк когда тот перезагружается (перезагружается раз в день где-то глубоко ночью)
19 def listen(self):
20 while True:
21 try:
22 for event in self.check():
23 yield event
24 except Exception as e:
25 print(e) #будет писать в консоль что таймаут произошел, при желании просто впишите сюда pass
26
27bot_id = '193179464' # сюда id паблика
28longpoll = MyVkLongPoll(vk, bot_id)
29
30def send_message(msg):
31 vk.method('messages.send',{'random_id':get_random_id(),'peer_id':event.obj.peer_id,'message':msg})
32
33
34
35
36
37
38
39citymoscow = ['moscow','время мск' ,'мск', 'время москва'] #Время Москва UTC + 3
40sityekb = ['ект', 'екб', 'время екатеринбург', 'ekaterinburg', 'время екб'] #Время екб UTC +5
41
42course = ['курсы','курс', 'курсы валют', 'валюта', 'валюты', 'курс доллара', 'доллар', 'usd', 'евро', 'euro', 'курс евро', 'курсы валют', 'Валюта', 'нефть', 'курс нефти', 'oil'] #курсы валют
43
44tlou2 = ['tlou', 'tlou2', 'тлоу', 'тлоу2']
45gost = ['gost', 'гост', 'тсушима']
46
47koronavirus = ['коронавирус', 'covid', 'корона', 'вирус', 'coronavirus', 'мониторинг коронавируса']
48
49for event in longpoll.listen(): #начинаем слушать лонгпулл
50 if event.obj:
51 if event.obj.text.lower() in ('комманды', '/комманды', 'commands', '/commands','команды'):
52 send_message('Вот что я умею: \n1. /rand "число1-число2" \n2. Время "город" \n3. Погода "Город" \n4. Курсы валют \n5. Мониторинг коронавируса \
53 \n6. Дата выхода Gost/tlou2 \n7.Орёл/Решка')
54 print(event.obj.text)
55 elif event.obj.text.lower() == 'привет':
56 send_message('привет')
57 print(event.obj.text)
58 elif event.obj.text.lower() == 'пока':
59 send_message('пока')
60 print(event.obj.text)
61
62 #elif event.obj.text.lower() == 'kick':
63 #chat_id = int(str(event.obj.peer_id)[-1:])
64 #vk.method('messages.removeChatUser',{'chat_id':chat_id,'member_id':504708567})
65
66
67
68 elif event.obj.text.lower() in course:
69
70
71 oil = 'https://yandex.ru/news/quotes/1006/'
72 dollar_rub = 'https://yandex.ru/news/quotes/1.html'
73 euro_rub = 'https://yandex.ru/news/quotes/23.html'
74 # Парсим всю страницу
75 source1 = requests.get(dollar_rub)
76 source2 = requests.get(euro_rub)
77 source3 = requests.get(oil)
78
79 main_text1 = source1.text
80 main_text2 = source2.text
81 main_text3 = source3.text
82 # Разбираем через BeautifulSoup
83 soup1 = BeautifulSoup(main_text1)
84 soup2 = BeautifulSoup(main_text2)
85 soup3 = BeautifulSoup(main_text3)
86
87 # Получаем нужное для нас значение и возвращаем его
88 table1 = soup1.findAll("td", {"class": "quote__value"})
89 table2 = soup2.findAll("td", {"class": "quote__value"})
90 table3 = soup3.findAll("td", {"class": "quote__value"})
91 data = soup3.findAll( "td", { "class": "quote__date" } )
92 #tr = table.find( "span", { "class": "quote__sgn" } )
93
94
95 send_message('Доллар = ' + str(table1[0].text[:5]) + ' рублей' + '\nЕвро = ' + str(table2[0].text[:5]) + ' рублей' +'\nНефть = ' + str(table3[0].text) + ' USD' )
96
97
98 elif event.obj.text.lower() in koronavirus:
99 oil = 'https://dev.by/news/poyavilsya-onlain-servis-dlya-monitoringa-rasprostraneniya-koronavirusa'
100
101 source = requests.get(oil)
102 main_text = source.text
103 soup = BeautifulSoup(main_text)
104
105 USA = soup.findAll( "", { "class": "data row1 col1"} )
106 ITALIA = soup.findAll( "", { "class": "data row2 col1"} )
107 SPANISH = soup.findAll( "", { "class": "data row3 col1"} )
108 CHINA = soup.findAll( "", { "class": "data row4 col1"} )
109 GERMANY = soup.findAll( "", { "class": "data row5 col1"} )
110 RUSSIA = soup.findAll( "", { "class": "data row32 col1"} )
111
112 send_message('Заражённых в сша: ' + str(USA[0].text) + '\nЗаражённых в Италии ' + str(ITALIA[0].text))
113
114
115
116 elif 'погода' in event.obj.text.lower():
117
118 # Enter your API key here
119 #api_key = "c012abf83e8afdf40810863f64ae8618"
120
121 # base_url variable to store url
122 #base_url = "http://api.openweathermap.org/data/2.5/weather?"
123 # Give city name
124 owm = pyowm.OWM('c012abf83e8afdf40810863f64ae8618', language = 'ru')
125
126 try:
127 city_name = event.obj.text.split(' ')[1:][0] #Получаем всё, что идёт после "погода"
128
129 #pyowm
130 observation = owm.weather_at_place(city_name)
131 w = observation.get_weather()
132 temp = w.get_temperature('celsius')['temp']
133 status = w.get_detailed_status()
134
135 # print following values
136 send_message(" Температура (в цельсиях): " +
137 str(temp) + '°' +
138 #"\n atmospheric pressure (in hPa unit) = " +
139 #str(current_pressure) +
140 #"\n humidity (in percentage) = " +
141 #str(current_humidiy) +
142 "\n Состояние: " +
143 str(status))
144 except:
145 send_message('Город не найден')
146
147
148 elif '/rand' in event.obj.text.lower():
149 spis = event.obj.text.split(' ')[1:] #Получаем всё, что идёт после "рандом"
150 pered = event.obj.text.split(' ')[:1] #Получаем всё, что идёт перед "рандом"
151 pred = ' '.join(pered)
152
153 if len(spis)>1:
154 send_message('Неправильно набрана команда!')
155 elif pred != '/rand':
156 send_message('ты нахуй пишешь чото перед /rand')
157 continue
158 else:
159 try:
160 first_number = int(spis[0].split('-')[0]) #Получаем первое число деля строку с числами на две
161 second_number = int(spis[0].split('-')[1]) #Получаем второе число
162 random_num = random.randint(first_number, second_number)
163 send_message(str('Рандомное число: ' + str(random_num)))
164 except:
165 send_message('неправильные числа представлены!')
166
167
168
169 elif 'орёл/решка' in event.obj.text.lower():
170 Headstails = random.randint(1,2)
171
172 if Headstails == 1:
173 d = 'Орёл'
174 elif Headstails == 2:
175 d = 'Решка'
176 send_message(str(d))
177
178
179
180 elif event.obj.text.lower() in tlou2:
181
182 # Значение: datetime.datetime(2017, 4, 5, 0, 18, 51, 980187)
183 now = datetime.datetime.now()
184 then = datetime.datetime(2020, 5, 29)
185 time = then - now
186 days = time.days
187 send_message( 'Until the release of "The Last of Us Part 2" left to wait ' + str(days) + ' days' )
188
189
190
191
192 elif event.obj.text.lower() in gost:
193
194 # Значение: datetime.datetime(2017, 4, 5, 0, 18, 51, 980187)
195 now = datetime.datetime.now()
196 then = datetime.datetime(2020, 6, 26)
197 time = then - now
198 days = time.days
199 send_message( 'Until the release of "Ghost of Tsushima" left to wait ' + str(days) + ' days' )
200
201
202 elif 'время' in event.obj.text.lower():
203 utcp3 = ['москва','киров','адлер','азов','анапа','арзамас','балашиха','балахна','белгород','бор','владимир','воронеж',\
204 'вязьма','казань','липецк','пенза','тверь','тамбов','сочи','смоленск','псков','подольск','питер','санкт-петербург','киев','минск','нижний-новгород']
205 time = datetime.datetime.now(timezone.utc)
206 utc3 = time.hour + 3
207 if utc3 > 24:
208 a = utc3 - 24
209 else:
210 a = time.hour + 3
211 st = (str(a) + ':' + str(time.minute) + ':' + str(time.second) )
212
213 spis = event.obj.text.split(' ')[1:] #Получаем всё, что идёт после "время"
214 city_name = ' '.join(spis)
215 city = city_name.lower()
216
217 pered = event.obj.text.split(' ')[:1] #Получаем всё, что идёт перед "время"
218 pered = ' '.join(pered)
219 pered = pered.lower()
220
221 if city in utcp3:
222 send_message('В городе ' + str(city.title()) + ' сейчас: ' + str(st))
223 continue
224 #elif len(spis)
225 elif len(spis) < 5:
226 if pered != 'время':
227 send_message('ты нахуй пишешь чото перед время')
228 continue
229 elif city not in utcp3:
230 send_message('Город не найден!')
231 continue
232
233 print(pered)
234
235
236 #elif event.obj.text.lower() in sityekb:
237
238
239
240
241 elif event.obj.text.lower() == 'кик':
242 try:
243 chat_id = int(str(event.obj.peer_id)[-1:])
244 user_id = event.obj['reply_message']['from_id']
245 vk.method("messages.removeChatUser", {"chat_id": chat_id ,"user_id": user_id })
246 except Exception as e:
247 print(e)
248
249
250# vk.method('сам метод',{параметры метода})