diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4acd06b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.py diff --git a/README.md b/README.md index ae279cd..5fa56c0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ -# dan63047pythonbot - lol +#### Мой личный бот на python для ВК +# от dan63047 + diff --git a/__pycache__/config.cpython-38.pyc b/__pycache__/config.cpython-38.pyc new file mode 100644 index 0000000..0c317ce Binary files /dev/null and b/__pycache__/config.cpython-38.pyc differ diff --git a/__pycache__/dan63047bot.cpython-38.pyc b/__pycache__/dan63047bot.cpython-38.pyc index e3fb019..b5b0799 100644 Binary files a/__pycache__/dan63047bot.cpython-38.pyc and b/__pycache__/dan63047bot.cpython-38.pyc differ diff --git a/dan63047bot.py b/dan63047bot.py index ae6d1e1..25427e7 100644 --- a/dan63047bot.py +++ b/dan63047bot.py @@ -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", "пока"] - 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") + self._COMMANDS = ["!image", "!my_id", "!h", "!user_id", "!group_id", "!help"] + + @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 + + 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 = "Пользователь не найден
"+str(lol) + return answer - user_name = self._clean_all_tag_from_str(bs.findAll("title")[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']+"
Его ид: "+str(user_info[0]['id'])+"
Профиль закрыт: "+is_closed+"
Пол: "+sex+"
Последний онлайн: "+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 = "Группа не найдена
"+str(lol) + return answer - return user_name.split()[0] + if group_info[0]['description'] == "": + description = "Отсутствует" + else: + description = group_info[0]['description'] + + answer = group_info[0]['name']+"
Описание: "+description+"
Ид группы: "+str(group_info[0]['id'])+"
Подписчиков: "+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'] = "Я бот, призванный доставлять неудобства.
Команды:
!my_id - сообщит ваш id в ВК
!user_id *id* - сообщит информацию о этом пользователе
!group_id *id* - сообщит информацию о этой группе
!image - отправляет пока что только одну картинку (скоро планируется отправлять рандомную картинку из альбома)
!h, !help - справка
Дата последнего обновления: 04.04.2020 (перевод на python)" - elif message == self._COMMANDS[2]: - return f"Я бот, призванный доставлять неудобства.
Команды:
!my_id - сообщит ваш id в ВК
!user_id *id* - сообщит информацию о этом пользователе
!group_id *id* - сообщит информацию о этой группе
!image - отправляет пока что только одну картинку (скоро планируется отправлять рандомную картинку из альбома)
!h, !help - справка
Дата последнего обновления: 08.03.2020" + elif message[0] == self._COMMANDS[3]: + respond['text'] = self.get_info_user(message[1]) - # Пока - elif message == self._COMMANDS[3]: - return f"Пока-пока!" - - else: - return "Не понимаю о чем вы..." + elif message[0] == self._COMMANDS[4]: + respond['text'] = self.get_info_group(message[1]) + + return respond diff --git a/start.py b/start.py index d99cb7a..ecff752 100644 --- a/start.py +++ b/start.py @@ -1,22 +1,29 @@ -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 +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)# Авторизуемся как сообщество -longpoll = VkLongPoll(vk)# Работа с сообщениями +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(): if event.type == VkEventType.MESSAGE_NEW: if event.to_me: - + print('New message:') print(f'For me by: {event.peer_id}', end='') - + bot = VkBot(event.peer_id) - write_msg(event.peer_id, bot.new_message(event.text)) - - print('Text: ', event.text) \ No newline at end of file + 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)