normal bot

This commit is contained in:
dan63047 2020-04-04 19:07:39 +03:00
parent 1dfd193358
commit 3f81d643ab
6 changed files with 117 additions and 37 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
config.py

View File

@ -1,2 +1,3 @@
# dan63047pythonbot
lol
#### Мой личный бот на python для ВК
# от dan63047

Binary file not shown.

View File

@ -1,38 +1,109 @@
import vk_api, time, bs4
import vk_api
import datetime
import requests
from config import vk
from bs4 import BeautifulSoup
from vk_api.longpoll import VkLongPoll, VkEventType
class VkBot:
def __init__(self, peer_id):
print("\nСоздан объект бота!")
self._USER_ID = peer_id
#self._USERNAME = self._get_user_name_from_vk_id(user_id)
self._COMMANDS = ["привет", "!my_id", "!h", "пока"]
self._COMMANDS = ["!image", "!my_id", "!h", "!user_id", "!group_id", "!help"]
def _get_user_name_from_vk_id(self, user_id):
request = requests.get("https://vk.com/id"+str(user_id))
bs = bs4.BeautifulSoup(request.text, "html.parser")
@staticmethod
def _clean_all_tag_from_str(string_line):
result = ""
not_skip = True
for i in list(string_line):
if not_skip:
if i == "<":
not_skip = False
else:
result += i
else:
if i == ">":
not_skip = True
return result
user_name = self._clean_all_tag_from_str(bs.findAll("title")[0])
def get_info_user(self, id):
try:
user_info = vk.method('users.get', {'user_ids': id, 'fields': 'verified,last_seen,sex'})
except vk_api.exceptions.ApiError as lol:
answer = "Пользователь не найден<br>"+str(lol)
return answer
return user_name.split()[0]
if user_info[0]['is_closed']:
is_closed = "Да"
else:
is_closed = "Нет"
if user_info[0]['sex'] == 1:
sex = "Женский"
elif user_info[0]['sex'] == 2:
sex = "Мужской"
else:
sex = "Неизвестно"
if user_info[0]['last_seen']['platform'] == 1:
platform = "m.vk.com"
elif user_info[0]['last_seen']['platform'] == 2:
platform = "iPhone"
elif user_info[0]['last_seen']['platform'] == 3:
platform = "iPad"
elif user_info[0]['last_seen']['platform'] == 4:
platform = "Android"
elif user_info[0]['last_seen']['platform'] == 5:
platform = "Windows Phone"
elif user_info[0]['last_seen']['platform'] == 6:
platform = "Windows 10"
elif user_info[0]['last_seen']['platform'] == 7:
platform = "vk.com"
else:
platform = "тип платформы неизвестен"
time = datetime.datetime.fromtimestamp(user_info[0]['last_seen']['time'])
answer = user_info[0]['first_name']+" "+user_info[0]['last_name']+"<br>Его ид: "+str(user_info[0]['id'])+"<br>Профиль закрыт: "+is_closed+"<br>Пол: "+sex+"<br>Последний онлайн: "+time.strftime('%d.%m.%Y в %H:%M:%S')+" ("+platform+")"
return answer
def get_info_group(self, id):
try:
group_info = vk.method('groups.getById', {'group_id': id, 'fields': 'description,members_count'})
except vk_api.exceptions.ApiError as lol:
answer = "Группа не найдена<br>"+str(lol)
return answer
if group_info[0]['description'] == "":
description = "Отсутствует"
else:
description = group_info[0]['description']
answer = group_info[0]['name']+"<br>Описание: "+description+"<br>Ид группы: "+str(group_info[0]['id'])+"<br>Подписчиков: "+str(group_info[0]['members_count'])
return answer
def new_message(self, message):
respond = {'attachment': None, 'text': None}
message = message.split(' ')
if message[0] == self._COMMANDS[0]:
respond['text'] = "hueh"
respond['attachment'] = "photo-190322075_457239033"
# Привет
if message == self._COMMANDS[0]:
return f"Привет-привет!"
elif message[0] == self._COMMANDS[1]:
respond['text'] = "Ваш ид: "+str(self._USER_ID)
elif message == self._COMMANDS[1]:
return f"Ваш ид: {self._USER_ID}"
elif message[0] == self._COMMANDS[2] or message[0] == self._COMMANDS[5]:
respond['text'] = "Я бот, призванный доставлять неудобства. <br>Команды:<br>!my_id - сообщит ваш id в ВК<br>!user_id *id* - сообщит информацию о этом пользователе<br>!group_id *id* - сообщит информацию о этой группе<br>!image - отправляет пока что только одну картинку (скоро планируется отправлять рандомную картинку из альбома)<br>!h, !help - справка<br>Дата последнего обновления: 04.04.2020 (перевод на python)"
elif message == self._COMMANDS[2]:
return f"Я бот, призванный доставлять неудобства. <br>Команды:<br>!my_id - сообщит ваш id в ВК<br>!user_id *id* - сообщит информацию о этом пользователе<br>!group_id *id* - сообщит информацию о этой группе<br>!image - отправляет пока что только одну картинку (скоро планируется отправлять рандомную картинку из альбома)<br>!h, !help - справка<br>Дата последнего обновления: 08.03.2020"
elif message[0] == self._COMMANDS[3]:
respond['text'] = self.get_info_user(message[1])
# Пока
elif message == self._COMMANDS[3]:
return f"Пока-пока!"
elif message[0] == self._COMMANDS[4]:
respond['text'] = self.get_info_group(message[1])
else:
return "Не понимаю о чем вы..."
return respond

View File

@ -1,12 +1,18 @@
import vk_api, time, bs4
import vk_api
import time
import requests
from config import vk
from bs4 import BeautifulSoup
from dan63047bot import VkBot
from vk_api.longpoll import VkLongPoll, VkEventType
def write_msg(peer_id, message):
vk.method('messages.send', {'peer_id': peer_id, 'message': message, 'random_id': time.time()})
token = "9c2e8fbc0fb7c846315e2f7758373d92e6961cefe74697ffb335e14a67916e54e20df6082577c8a7ade1c"# API-ключ созданный ранее
vk = vk_api.VkApi(token=token)# Авторизуемся как сообщество
def write_msg(peer_id, message, attachment=None):
vk.method('messages.send', {'peer_id': peer_id,
'message': message,
'random_id': time.time(),
'attachment': attachment})
longpoll = VkLongPoll(vk) # Работа с сообщениями
print("Server started")
for event in longpoll.listen():
@ -17,6 +23,7 @@ for event in longpoll.listen():
print(f'For me by: {event.peer_id}', end='')
bot = VkBot(event.peer_id)
write_msg(event.peer_id, bot.new_message(event.text))
if bot.new_message(event.text)['text']:
write_msg(event.peer_id, bot.new_message(event.text)['text'], bot.new_message(event.text)['attachment'])
print('Text: ', event.text)