Esempio n. 1
0
def run():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            print('\n' + get_name(event.user_id) + ' (id: ' +
                  str(event.user_id) + ')')
            print('Сообщение пришло в: ' +
                  str(datetime.strftime(datetime.now(), "%H:%M:%S")))
            print('Текст сообщения: ' + str(event.text))
            print("---------------------------------\n")
            response = event.text.lower()
            keyboard = Keyboard()
            if event.from_user and event.to_me:
                if found_user(event.user_id) == False:
                    print(event.user_id)
                    print(type(event.user_id))
                    send = {
                        'lang': '',
                        'level': '',
                        'format': '',
                        'discus': ''
                    }
                    steps = {
                        '1': False,
                        '2': False,
                        '3': False,
                        '4': False,
                        '5': False
                    }
                    bot = VkBot(event.user_id, send, steps)
                    add_into_user_bot(event.user_id, send, steps, bot)
                else:
                    if 'vkbot' not in users_bot[event.user_id].keys():
                        user = users_bot[event.user_id]
                        bot = VkBot(event.user_id, user['send'], user['steps'])
                        add_into_user_bot(event.user_id, user['send'],
                                          user['steps'], bot)
                bot_Object = users_bot[event.user_id]['vkbot']
                keyboard = keyboard.create_keyboard(response,
                                                    bot_Object.get_step())
                bb = bot_Object.message(response, keyboard)
                add_into_user_bot(event.user_id, bot_Object.send,
                                  bot_Object.STEPS, bot_Object)
                print(bb)
                print(users_bot)
                print(bot_Object.send)
                print(bot_Object.STEPS)
                add_data_in_json(event.user_id)
                if bb == None:
                    continue
                elif len(bb) == 4:
                    send_message(vk,
                                 bb[0],
                                 bb[1],
                                 message=bb[2],
                                 keyboard=bb[3])
                elif len(bb) == 3:
                    send_message(vk, bb[0], bb[1], message=bb[2])
Esempio n. 2
0
    def test_on_event(self):
        send_mock = Mock()
        api_mock = Mock()
        api_mock.messages.send = send_mock
        events = []

        for input_text in self.INPUTS:
            event = deepcopy(self.RAW_EVENT)
            event['object']['message']['text'] = input_text
            events.append(VkBotMessageEvent(event))

        long_poller_mock = Mock()
        long_poller_mock.listen = Mock(return_value=events)

        with patch('vk_bot.VkBotLongPoll', return_value=long_poller_mock):
            bot = VkBot('', '')
            bot.api = api_mock
            bot.send_image = Mock()
            bot.run()

        assert send_mock.call_count == len(self.INPUTS)

        real_outputs = []
        for call in send_mock.call_args_list:
            args, kwargs = call
            real_outputs.append(kwargs['message'])
        assert real_outputs == self.EXPECTED_OUTPUTS
Esempio n. 3
0
File: run.py Progetto: ehremut/v_bot
def run():
    try:
        for event in longpoll.listen():
            if event.type == VkEventType.MESSAGE_NEW:
                print('\n' + get_name(event.user_id) + ' (id: ' +
                      str(event.user_id) + ')')
                print('Сообщение пришло в: ' +
                      str(datetime.strftime(datetime.now(), "%H:%M:%S")))
                print('Текст сообщения: ' + str(event.text))
                print("---------------------------------\n")
                response = event.text.lower()
                keyboard = Keyboard.create_keyboard(response)

                if event.from_user and event.to_me:
                    if event.user_id not in users_bot:
                        users_bot[event.user_id] = VkBot(event.user_id)
                    bb = users_bot[event.user_id].message(response, keyboard)
                    print(users_bot[event.user_id].send)
                    print(users_bot[event.user_id].steps)
                    if bb == None:
                        continue
                    if len(bb) == 4:
                        send_message(vk,
                                     bb[0],
                                     bb[1],
                                     message=bb[2],
                                     keyboard=bb[3])
                    elif len(bb) == 3:
                        send_message(vk, bb[0], bb[1], message=bb[2])
    except Exception as E:
        time.sleep(3)
Esempio n. 4
0
def main():
    def write_msg(user_id, message, random_id):
        vk.method('messages.send', {
            'user_id': user_id,
            'message': message,
            "random_id": random_id
        })

    vk = vk_api.VkApi(token=VK_TOKEN)

    longpoll = VkLongPoll(vk)

    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            if event.to_me:

                print('New message:')
                print(f'For me by: {event.user_id}', end='')

                bot = VkBot(event.user_id)
                write_msg(event.user_id,
                          bot.new_message(event.text),
                          random_id=event.random_id)

                print('Text: ', event.text)
Esempio n. 5
0
def mailing():
    while (1):
        t1 = time.time()
        conn = psycopg2.connect(dbname='vkBotDataBase',
                                user='******',
                                password='******',
                                host='localhost')
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM students WHERE time='" +
                       time.strftime("%H.%M", time.localtime()) + "'")
        result = cursor.fetchall()
        if result != []:
            bot = VkBot(result[0][0], conn)
            message = ''
            now = datetime.now()
            next_day = calendar.weekday(now.year, now.month, now.day) + 1
            cursor.execute("SELECT * FROM day WHERE id=" +
                           str(result[0][0] * 10 + next_day))
            result = cursor.fetchall()
            print(result)
            if result != []:
                message += "Расписание на завтра: \n"
                for i in result:
                    message += i[1] + '  ' + i[0] + '\n'
                bot.send_message(message=message)
        conn.close()
        t2 = time.time()
        t = t2 - t1
        time.sleep(60 - t)
Esempio n. 6
0
def run_vk_bot():
    """
    Run vk bot
    """

    logger.info('Attempt to start vk bot.')
    vk_bot = VkBot()
    vk_bot.start()
Esempio n. 7
0
def waiting():
    longpoll = VkLongPoll(vk_session)
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW:

            if event.to_me:
                request = event.text
                bot = VkBot(event.user_id, conn)
                bot.request_handler(request)
Esempio n. 8
0
def main():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
            print('Новое сообщение:')
            print(f'От пользователя: {event.user_id}    ', end='')

            bot = VkBot(event.user_id)
            write_msg(event.user_id, bot.new_message(event.text))

            print(' Сообщение:', event.text)
Esempio n. 9
0
    def start(self):
        print('Server Started!')
        for event in self.long_poll.listen():
            # Пришло новое сообщение
            if event.type == VkBotEventType.MESSAGE_NEW:

                if event.object.message['from_id'] == event.object.message[
                        'peer_id']:
                    bot = VkBot(event.from_user)

                    keyboard = create_keyboard()

                    print(event.object.message['from_id'], ':',
                          event.object.message['text'])
                    bot.send_msg(send_id=event.object.message['from_id'],
                                 message=bot.new_message(
                                     event.object.message['text']),
                                 vk_api=self.vk_api,
                                 keyboard=keyboard)

                elif event.object.message['from_id'] != event.object.message[
                        'peer_id']:
                    bot = VkBot(event.from_user)
                    keyboard = create_empty_keyboard()
                    user = self.vk.method(
                        "users.get",
                        {"user_ids": event.object.message['from_id']})
                    name = user[0]['first_name']
                    try:
                        bot.send_msg(
                            send_id=event.object.message['peer_id'],
                            message=bot.chat_new_message(
                                text=event.object.message['text'],
                                peer_id=event.object.message['peer_id'],
                                from_id=event.object.message['from_id'],
                                name=name,
                                vk_api=self.vk_api),
                            keyboard=keyboard,
                            vk_api=self.vk_api)
                    except:
                        pass
Esempio n. 10
0
def bot_launch(longpoll, vk_comunity, keyboard):
    print('Бот запущен \U0001F916')
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            if event.to_me:
                # Объект бота
                bot = VkBot(event.user_id)

                print('\nНовое сообщение \U0001F4EC')
                print(f'ID: {event.user_id} \U0001F194')
                print(f'Имя: {bot._get_user_name(event.user_id)} \U0001F974')
                print(f'Текст: {event.text} \U0001F4DD')

                # Бот отвечает
                bot_message(event.user_id, bot.new_message(event.text),
                            vk_comunity, keyboard)
Esempio n. 11
0
    def test_run(self):
        count = 5
        events = [{}] * count
        long_poller_mock = Mock(return_value=events)
        long_poller_listen_mock = Mock()
        long_poller_listen_mock.listen = long_poller_mock

        with patch('vk_bot.vk_api.VkApi'):
            with patch('vk_bot.VkBotLongPoll',
                       return_value=long_poller_listen_mock):
                bot = VkBot('', '')
                bot.on_event = Mock()
                bot.send_image = Mock()
                bot.run()

                bot.on_event.assert_called()
                bot.on_event.assert_any_call({})
                assert bot.on_event.call_count == count
Esempio n. 12
0
    def __init__(self, data):
        log = logging.getLogger('bot')
        log_level = getattr(logging, data['log'].upper(), 50)
        log.setLevel(log_level)
        fmt = logging.Formatter('[%(asctime)s] %(levelname)s: %(name)s: %(message)s')

        fh = logging.FileHandler('bot.log', 'w')
        fh.setFormatter(fmt)
        log.addHandler(fh)

        ch = logging.StreamHandler()
        ch.setFormatter(fmt)
        ch.setLevel(logging.WARNING)
        log.addHandler(ch)

        self.group_id = data['group_id']
        self.log = log
        self.log.info('Initializing VkBot class...')
        self.bot = VkBot(data['user_token'], data['group_token'], data['group_id'])
        self.log.info('Running!')
def run():
    print("Server started")
    for event in longpoll.listen():

        if event.type == VkEventType.MESSAGE_NEW:

            if event.to_me:

                print('New message:')
                print('For me by: ', end='')

                print(event.user_id)

                user_id = event.user_id
                if user_id not in users_bot_class_dict:
                    users_bot_class_dict[user_id] = VkBot(event.user_id)
                write_msg(event.user_id, bot.new_message(event.text))
                # # Checking to welcome message send
                # if users_bot_class_dict[user_id].WELCOME_MSG_SEND:
                #     write_msg(event.user_id, users_bot_class_dict[user_id].update_screen(event.text))
                # else:
                #     write_msg(event.user_id, users_bot_class_dict[user_id].get_welcome_msg(event.user_id))

                print('Text: ', event.text)
Esempio n. 14
0
import vk_api
from vk_api import VkUpload
import requests
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from vk_bot import VkBot


token = "5b121f534ed551acff6595ad366534d14a6aa9097556c6c11beb6ab9ad5ac1b43c3189fcf875b74eee580"
bot_session = vk_api.VkApi(token=token)
vk = bot_session.get_api()
longpoll = VkBotLongPoll(bot_session, 177063309)
session = requests.Session()
upload = VkUpload(vk)

for event in longpoll.listen():
    if event.type == VkBotEventType.MESSAGE_NEW and event.message:
        bot = VkBot(event, vk, upload, session)
        bot.console_log()
        if 'треды' in bot.TEXT:
            bot.threads_from_board()
        if 'тред номер' in bot.TEXT:
            bot.single_thread()
        if 'расписание' in bot.TEXT:
            bot.send_schedule(single=True)
        if 'пара' in bot.TEXT:
            bot.send_schedule(specific=True)
        if 'документация' in bot.TEXT:
            bot.send_doc()
Esempio n. 15
0
import time
import logging
from sqlalchemy.orm import sessionmaker

from models import engine, VkUser, Keyword
from vk_bot import VkBot

db_session = sessionmaker(bind=engine)()
vk_bot = VkBot()
vk_bot.gen_api()

log = logging.getLogger("botlog")


def run_mailing():
    while True:
        try:
            keywords = [
                interest.name for interest in db_session.query(Keyword).all()
            ]
            if keywords:
                for keyword in keywords:
                    users_with_that_keyword = db_session.query(
                        VkUser.vk_user_id).filter(
                            VkUser.keyword.any(name=keyword)).all()
                    vk_bot.send_news_for_many_users(
                        [_.vk_user_id for _ in users_with_that_keyword],
                        keyword)
                    time.sleep(5)
            time.sleep(5)
        except Exception as ex:
Esempio n. 16
0
 def run(self):
     for event in long_poll.listen():
         if event.type == VkEventType.MESSAGE_NEW:
             if event.to_me:
                 bot = VkBot(event.user_id, vk)
                 bot.new_message(event.text)
Esempio n. 17
0
def main():
    vk = Vk(VK_TOKEN, '5.130')
    vk_bot = VkBot(VK_BOT_TOKEN)

    start_key = vk_bot.get_keyboard(start_button)
    continue_key = vk_bot.get_keyboard(continue_button)
    change_criteria_key = vk_bot.get_keyboard(change_criteria_button)

    database_users = crud.load_users()
    users = []
    city_dict = {}
    criteria = {}

    long_poll = VkLongPoll(vk_bot.session)
    for event in long_poll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            if event.to_me:
                request = event.text.lower()

                if request == "привет":
                    flag = 0
                    for user_id in database_users:
                        if user_id == event.user_id:
                            criteria = crud.load_criteria(event.user_id)
                            flag = 1
                            break
                    if flag == 0:
                        info = vk.get_user_info(event.user_id)
                        user = User(event.user_id, vk.get_criteria(info))
                        users.append(user)
                        crud.insert_user(user)
                        user.count_to_load, target_users = vk.search_users(
                            user.criteria, user.viewed_list, user.black_list)
                        vk_bot.send_message(
                            event.user_id, f"привет {user.first_name}, "
                            f"нашел для тебя {user.count_to_load} пользователей\n "
                        )
                        vk_bot.send_message(event.user_id,
                                            user.display_criteria())
                        vk_bot.send_message(event.user_id, "сделай выбор:",
                                            start_key)
                    elif flag == 1:
                        user = User(event.user_id, criteria)
                        user.viewed_list = crud.load_viewed_list(event.user_id)
                        user.loaded_list = user.viewed_list.copy()
                        user.black_list = crud.load_black_list(event.user_id)
                        user.favorite_list = crud.load_favorite_list(
                            event.user_id)
                        user.count_to_load, target_users = vk.search_users(
                            user.criteria, [], user.black_list)
                        user.count_loaded = len(
                            user.viewed_list) if user.viewed_list else 0
                        users.append(user)

                        if user.count_not_viewed(
                        ) > 0 and user.count_loaded > 0:
                            vk_bot.send_message(
                                event.user_id,
                                f"привет {user.first_name}, продолжим?\n"
                                f"осталось {user.count_not_viewed()} пользователей\n"
                                f"\n{user.display_criteria()}\n", continue_key)
                        else:
                            clear_current_search_data(user)
                            vk_bot.send_message(
                                event.user_id,
                                f"привет {user.first_name}, искать снова?\n"
                                f"нашел {user.count_to_load} пользователей\n"
                                f"\n{user.display_criteria()}\n", start_key)
                else:
                    for user in users:
                        if request in ('начать поиск', 'продолжить поиск'):
                            if user.id == event.user_id:
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                if request == 'начать поиск':
                                    user.count_to_load = count
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"нашел {user.count_to_load} пользователей"
                                    )
                                else:
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"осталось {count} пользователей")
                                vk_bot.send_message(event.user_id,
                                                    "загружаю...")

                                for i, target_user in enumerate(target_users):
                                    photos = vk.get_photos(target_user)
                                    top_3_photos = vk.get_top_photos(photos, 3)
                                    attachments = vk_bot.get_attachments(
                                        top_3_photos)
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"https://vk.com/id{str(target_user)}",
                                        None, attachments)
                                    user.viewed_list.append(target_user)
                                    if i == user.max_number - 1:
                                        break
                                crud.insert_users_search(user)
                                user.count_loaded = len(user.loaded_list)

                                if user.count_not_viewed() > 0:
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"осталось {user.count_not_viewed()} пользователей"
                                        f"\nсделай выбор:", continue_key)
                                else:
                                    clear_current_search_data(user, 1)
                                    vk_bot.send_message(
                                        event.user_id, "сделай выбор:",
                                        start_key)

                        elif request == 'изменить параметры':
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id,
                                    f"{user.display_criteria()}\n"
                                    "сделай выбор:", change_criteria_key)

                        elif request == 'пол':
                            if user.id == event.user_id:
                                user.change_sex()
                                crud.update_sex(user)
                                clear_current_search_data(user, 1)
                                vk_bot.send_message(
                                    event.user_id, f"пол изменен\n"
                                    f"{user.display_criteria()}", start_key)
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {count} пользователей")

                        elif request == 'возраст':
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id,
                                    "введите возраст в формате '30-35'")

                        elif re.match(re.compile(age_pattern), request):
                            if user.id == event.user_id:
                                age_from, age_to = re.match(
                                    re.compile(age_pattern), request).groups()
                                user.change_age(age_from, age_to)
                                crud.update_age(user)
                                clear_current_search_data(user, 1)
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"возраст изменен\n{user.display_criteria()}",
                                    start_key)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {count} пользователей")

                        elif request == 'город':
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id,
                                    "введите город в формате 'г Москва'")

                        elif re.match(re.compile(city_pattern), request):
                            if user.id == event.user_id:
                                city_query = re.match(re.compile(city_pattern),
                                                      request).groups()[0]
                                city_dict, city_key = vk.get_cities(
                                    city_query, user.criteria['country_id'])
                                if len(city_key) > 0:
                                    city_key = vk_bot.get_keyboard(
                                        {'buttons': city_key})
                                    vk_bot.send_message(
                                        event.user_id, "подтвердите выбор:",
                                        city_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id, "город не найден",
                                        change_criteria_key)

                        elif re.match(re.compile(id_city_pattern), request):
                            if user.id == event.user_id:
                                city_id = re.match(re.compile(id_city_pattern),
                                                   request).groups()[0]
                                user.change_city(city_id, city_dict[city_id])
                                crud.update_city(user)
                                clear_current_search_data(user, 1)
                                user.count_to_load, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"город изменен\n{user.display_criteria()}",
                                    start_key)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {user.count_to_load} пользователей"
                                )

                        elif request == 'статус':
                            if user.id == event.user_id:
                                vk_bot.send_message(event.user_id,
                                                    user.STATUS_LABEL)

                        elif re.match(re.compile(status_pattern), request):
                            if user.id == event.user_id:
                                status = int(
                                    re.match(re.compile(status_pattern),
                                             request).groups()[0])
                                user.change_status(status)
                                crud.update_status(user)
                                clear_current_search_data(user, 1)
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"статус изменен\n{user.display_criteria()}",
                                    start_key)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {count} пользователей")

                        elif request == '+':
                            if user.id == event.user_id:
                                reply_message = vk_bot.get_reply_message(
                                    event.peer_id, event.user_id)
                                if re.match(re.compile(id_reply_pattern),
                                            reply_message):
                                    favorite_user_id = int(
                                        re.match(re.compile(id_reply_pattern),
                                                 reply_message).groups()[0])
                                    if favorite_user_id not in user.favorite_list:
                                        crud.insert_favorite(
                                            user, favorite_user_id)
                                        user.favorite_list.append(
                                            favorite_user_id)
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"пользователь добавлен в избранное",
                                            continue_key)
                                    else:
                                        vk_bot.send_message(
                                            event.user_id,
                                            'пользователь уже в списке',
                                            continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id,
                                        "чтобы добавить в избранное, отправь '+' "
                                        "\nв ответе на сообщение со ссылкой "
                                        "на пользователя")

                        elif request == '-':
                            if user.id == event.user_id:
                                reply_message = vk_bot.get_reply_message(
                                    event.peer_id, event.user_id)
                                if re.match(re.compile(id_reply_pattern),
                                            reply_message):
                                    black_list_user_id = int(
                                        re.match(re.compile(id_reply_pattern),
                                                 reply_message).groups()[0])
                                    if black_list_user_id not in user.black_list:
                                        crud.insert_black_user(
                                            user, black_list_user_id)
                                        user.black_list.append(
                                            black_list_user_id)
                                        user.clear_black_list_info(
                                            black_list_user_id)
                                        user.count_to_load, target_users = vk.search_users(
                                            user.criteria, [], user.black_list)
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"пользователь добавлен в черный список",
                                            continue_key)
                                    else:
                                        vk_bot.send_message(
                                            event.user_id,
                                            'пользователь уже в списке',
                                            continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id,
                                        "чтобы добавить в черный список, отправь '-' "
                                        "\nв ответе на сообщение со ссылкой "
                                        "на пользователя")

                        elif request == 'черный список':
                            if user.id == event.user_id:
                                if user.black_list:
                                    for black_user in user.black_list:
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"https://vk.com/id{str(black_user)}"
                                        )
                                    vk_bot.send_message(
                                        event.user_id, 'сделай выбор',
                                        continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id, 'список пуст',
                                        continue_key)

                        elif request == 'избранное':
                            if user.id == event.user_id:
                                if user.favorite_list:
                                    for favorite_user in user.favorite_list:
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"https://vk.com/id{str(favorite_user)}"
                                        )
                                    vk_bot.send_message(
                                        event.user_id, 'сделай выбор',
                                        continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id, 'список пуст',
                                        continue_key)

                        else:
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id, "не понял вашего ответа...")
Esempio n. 18
0
                'user_id': user_id,
                'message': message,
                'random_id': random.randint(1, 2000)
            })


# API-ключ созданный ранее
token = "7464579169b4bee1f62854d7fd8644c0ce385989d24dd07858ac5fea75fc0e27c8a5e17515851ef141440"

# Авторизуемся как сообщество
vk = vk_api.VkApi(token=token)

# Работа с сообщениями
longpoll = VkLongPoll(vk)

print("Server started")
autorized = set()

for event in longpoll.listen():
    print(event)
    if event.type == VkEventType.MESSAGE_NEW:

        if event.to_me:

            print('New message:')
            print(f'For me by: {event.user_id}', end='')

            bot = VkBot(event.user_id, autorized)
            write_msg(event.user_id, bot.new_message(event.text))
            print('Text: ', event.text)
Esempio n. 19
0
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_bot import VkBot

token = "/your vk group token/"

bot = VkBot(token)
bot.start_bot()
Esempio n. 20
0
 def setUp(cls):
     cls.vk_bot = VkBot()
Esempio n. 21
0
import vk_api
from random import randrange
from vk_bot import VkBot
from vk_DB import DbWorker, DB_path
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.longpoll import VkLongPoll, VkEventType

# Токен Вк-группы, от лица которой будет писать бот.
group_token = input('Group token: ')
# Токен любого пользователя Вк, он нужен для поиска людей, так как по токену группы этого сделать нельзя.
bot_token = input('Bot token: ')

vk_session = vk_api.VkApi(token=group_token)
longpoll = VkLongPoll(vk_session)
vk_bot = VkBot(bot_token)
db_worker = DbWorker(DB_path)


def write_message(user_id, message, attachment=None, keyboard=None):
    vk_session.method(
        'messages.send',
        {
            'user_id': user_id,
            'message': message,
            'random_id': randrange(10 ** 7),
            'attachment': attachment,
            'keyboard': keyboard
        }
    )

Esempio n. 22
0
import sys
import os.path

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

DEBUG = False
if __name__ == '__main__':
    from vk_bot import VkBot
    import subprocess
    bot = VkBot()
    migrations = subprocess.Popen([sys.executable, "models.py"])
    sender = subprocess.Popen([sys.executable, "sender.py"])
    bot.run()
    sender.kill()
])

model = DogNet(out_classes=120)
model.to(DEVICE)

load_weights(model, './weights/DogNet_epoch7.pth', DEVICE)
model.eval()

for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        if event.to_me:
            print(f'New message from {event.user_id}')

            if len(event.attachments
                   ) != 0 and event.attachments['attach1_type'] == 'photo':
                bot = VkBot(event.user_id, model)
                items = vk_sess.messages.getById(message_ids=event.message_id)
                item_url = items["items"][0]["attachments"][0]["photo"][
                    "sizes"][4]["url"]
                response = requests.get(item_url, stream=True)
                local_file = open('./local.jpg', 'wb')
                response.raw.decode_content = True
                shutil.copyfileobj(response.raw, local_file)
                image = Image.open('./local.jpg')
                image.load()
                output = model(torch.Tensor(transform(image)).unsqueeze_(0))
                label = encoder.inverse_transform(
                    [torch.argmax(torch.softmax(output[0],
                                                dim=-1)).item()]).item()
                write_msg(event.user_id, f'{label}')
            else:
Esempio n. 24
0
def main():
    bot = VkBot(config.token, config.group_id)
    bot.start()
Esempio n. 25
0

# API-ключ созданный ранее
token = "5d1d08c4b4b739b6718b5a9a09aa71332ba4f687aa58321344f706b4351c2a470d3a9011ad64e312dad30"

# Авторизуемся как сообщество
vk = vk_api.VkApi(token=token)

# Работа с сообщениями
longpoll = VkLongPoll(vk)

commander = Commander()
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.user_id}', end='')

            bot = VkBot(event.user_id)

            if event.text[0] == "/":
                write_msg(event.user_id, commander.do(event.text[1::]))
            else:
                write_msg(event.user_id, bot.new_message(event.text))

            print('Text: ', event.text)
Esempio n. 26
0
 def get_bot(user_id):
     if user_id not in active_bots:
         active_bots[user_id] = VkBot(user_id, vk, db_session)
     return active_bots[user_id]