/
main.py
executable file
·166 lines (161 loc) · 5.97 KB
/
main.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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
###########################################
#Простой wiki бот для вк от MrArthur4Ik :)#
###########################################
import requests
import wikipedia
import vk_api
import traceback
import random
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from wikipedia.exceptions import PageError
wikipedia.set_lang("RU")
def get_corona_info():
response = requests.get("https://api.thevirustracker.com/free-api?global=stats")
return response.json()
def get_corona_info_in_russia(str):
response = requests.get("https://api.thevirustracker.com/free-api?countryTotal=" + str)
return response.json()
class RichVkBotLongPoll(VkBotLongPoll):
def listen(self):
while True:
try:
for event in self.check():
yield event
except Exception as e:
print('error', e)
vk_session = vk_api.VkApi(token="токен...");
search_requests = {}
groupid = '171098026'
longpoll = RichVkBotLongPoll(vk_session, groupid);
vk = vk_session.get_api();
def msg(label):
if event.from_user:
vk.messages.send(
random_id=random.randint(1, 2147483647),
peer_id=event.obj.from_id,
message=label,
v='5.45'
)
if event.from_chat:
vk.messages.send(
random_id=random.randint(1, 2147483647),
chat_id=event.chat_id,
message=label,
v='5.45'
)
def msg_with_photo(label, att):
if event.from_user:
vk.messages.send(
random_id=random.randint(1, 2147483647),
peer_id=event.obj.from_id,
message=label,
attachment=att,
v='5.45'
)
if event.from_chat:
vk.messages.send(
random_id=random.randint(1, 2147483647),
chat_id=event.chat_id,
message=label,
attachment=att,
v='5.45'
)
for event in longpoll.listen():
try:
if event.type == VkBotEventType.MESSAGE_NEW:
with_verify = False
screen_name = vk.groups.getById(
group_id=groupid,
v='5.45'
)[0]['screen_name'];
msg_text = event.object.text
user_id = event.obj.from_id
args = msg_text.split(" ")
if args[0].startswith("[club" + str(event.group_id)):
args = args[1:]
with_verify = True
if len(args) == 0:
if event.from_chat:
msg("Меня кто-то звал?")
else:
msg("😟 Такой команды нет!")
continue
if args[0].lower() == "помощь" or args[0].lower() == "начать":
msg("Мои команды:\n"
""
"📰 Статья <название> - открыть статью по его названию.\n"
"🌐 Вики/Найти <текст> - найти статьи и получить их список.\n"
"📂 Открыть <число> - открыть статью из полученого списка.\n"
"🦠 Коронавирус - данные о коронавирусе.")
elif args[0].lower() == "статья":
if len(args) < 2:
msg("❗ Недостаточно аргументов в команде!")
else:
msg("🔎 Уже ищу...")
result_str = ""
request = args[1:]
for s in request:
result_str = result_str + s + " "
try:
result = wikipedia.summary(result_str)
msg("📰 Результат: \n" + result)
except PageError:
msg("❗ В Википедии нет статьи с таким названием")
except Exception:
msg("❗ Произошла ошибка!")
elif args[0].lower() == "найти" or args[0].lower() == "вики":
if len(args) < 2:
msg("❗ Недостаточно аргументов в команде!")
else:
msg("🔎 Уже ищу...")
result_str = ""
request = args[1:]
for s in request:
result_str = result_str + s + " "
try:
result = wikipedia.search(result_str)
if len(result) == 0:
msg("😞 Ничего не найдено.")
else:
result_search = ""
for i in range(len(result)):
s = result[i]
result_search = result_search + "📎 " + str(i + 1) + ": " + s + "\n"
search_requests[user_id] = result
msg("📰 Результат: \n" + result_search + "📰 Напишите \"Открыть <число>\" чтобы открыть соответствующую статью из списка.")
except Exception:
msg("❗ Произошла ошибка!")
print(traceback.format_exc())
elif args[0].lower() == "открыть":
if user_id in search_requests:
if len(args) < 2:
msg("❗ Недостаточно аргументов в команде!")
else:
try:
page = int(args[1])
msg("🔎 Уже ищу...")
if (page - 1) >= 0 and (page - 1) < len(search_requests[user_id]):
result = wikipedia.summary(search_requests[user_id][page - 1])
msg("📰 Результат: \n" + result)
else:
msg("❗ По этому номеру нет статьи.")
except ValueError:
msg("❗ Введите целое число!")
except Exception:
msg("❗ Произошла ошибка!")
else:
msg("❗ Для начала найдите статьи чтобы получить список.")
elif args[0].lower() == "коронавирус":
try:
viruses = get_corona_info()["results"][0]["total_cases"]
viruses_in_ru = get_corona_info_in_russia("RU")["countrydata"][0]["total_cases"]
msg("🤒 Всего больных: " + str(viruses) + "\n"
"🤧 Всего больных в России: " + str(viruses_in_ru)
)
except Exception:
msg("❗ Произошла ошибка!")
else:
if with_verify or event.from_user:
msg("😟 Такой команды нет!")
except Exception:
print(traceback.format_exc())