コード例 #1
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)
コード例 #2
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)
コード例 #3
0
ファイル: manage.py プロジェクト: zxy-zxy/support_bot
def run_vk_bot():
    """
    Run vk bot
    """

    logger.info('Attempt to start vk bot.')
    vk_bot = VkBot()
    vk_bot.start()
コード例 #4
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])
コード例 #5
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)
コード例 #6
0
ファイル: main.py プロジェクト: aspectie/Fanclub
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)
コード例 #7
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)
コード例 #8
0
ファイル: run.py プロジェクト: 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)
コード例 #9
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!')
コード例 #10
0
ファイル: server.py プロジェクト: JezzBz/VkBot
    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
コード例 #11
0
ファイル: test.py プロジェクト: admin-nsk/VK_Bot
    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
コード例 #12
0
ファイル: test.py プロジェクト: admin-nsk/VK_Bot
    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
コード例 #13
0
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)
コード例 #14
0
ファイル: Main.py プロジェクト: Anniegard/bot
# API-ключ
token = "eba3fbbbd3b9704498ee312a5c72002ca17dfad7fca8efe5afaee007a800a2a0c912554647b48295daa01"

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(f'New message from {event.user_id}', end='')

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

            print('Text: ', event.text)
            print("-------------------")
コード例 #15
0
 def setUp(cls):
     cls.vk_bot = VkBot()
コード例 #16
0
from vk_bot import VkBot
import threading

vk_bot = VkBot()


def vk_start():
    vk_bot.run()


thread_for_bot = threading.Thread(target=vk_start)
thread_for_bot.start()
コード例 #17
0
class VK:
    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 make_post(self):
        try:
            self.log.info("Making a post...")
            stats = api.get_stats()
            local, world = stats['today']
            local_yesterday, global_yesterday = stats['yesterday']
            self.log.info('Got stats for post')

            message = Message('Пишите в лс боту, чтобы получить последнюю статистику!\n', 'post')
            message.append(api.arrange_message(local, local_yesterday, 'в России'))
            message.append(api.arrange_message(world, global_yesterday, 'в мире'))

            self.log.info('Calling bot.wall_post()')
            self.bot.wall_post(message.get())
        except:
            self.log.exception('')


    def messages_hander(self):
        messages = {
            'ru': ['рф', "ру", "россия", 'ru', 'russia'],
            'world': ['мир', "в мире", 'world', 'worldwide'],
            'all': ['коронавирус', "covid", "все", "статистика"],
            'start': ['начать', "помощь"]
        }
        def send_message(event):
            try:
                self.log.info('Got event with type %s', event.type)
                msg = re.sub(fr'\[{self.group_id}|.*\](,|) ', '', event.message['text'].lower())
                msg = msg.encode('cp1251', 'ignore').decode('cp1251').strip(' ')
                peer_id = event.message.peer_id
                self.log.info('Event message is "%s", peer id is %s', msg, peer_id)
                out_msg = Message('', 'info')
                stats = api.get_stats()['today']
                stats_yesterday = api.get_stats()['yesterday']

                if msg in messages['ru'] or msg in messages['all']:
                    self.log.info('Getting local stats for message...')
                    self.log.info('Got local stats!')
                    out_msg.append(api.arrange_message(stats[0], stats_yesterday[0], 'в России'))

                if msg in messages['world'] or msg in messages['all']:
                    self.log.info('Getting global stats for message...')
                    self.log.info('Got global stats!')
                    out_msg.append(api.arrange_message(stats[1], stats_yesterday[1], 'в мире'))

                if msg in messages['start'] or event.from_chat and msg == '':
                    out_msg.set_type('start') # TODO статистика в разных странах
                    out_msg.change((
                        'Привет! Я бот - коронавирус. Я могу сообщать тебе последнюю статистику по коронавирусу.\n\n'
                        'Чтобы начать, просто напиши одну из трех комманд: \n'
                        'ру - Узнать статистику в России.\n'
                        'мир - Узнать о ситуации в мире.\n'
                        'все - Статистика России и мира в одном сообщении.\n'
                    ))

                if out_msg.get() != '': self.bot.send_message(peer_id, out_msg)
                else: 
                    out_msg.change('Извини, но я тебя не понимаю. Напиши "помощь", чтобы получить список команд.')
                    out_msg.set_type('empty')
                    self.bot.send_message(peer_id, out_msg)
            except TypeError:
                self.log.warning('Got TypeError in messages_handler()')
                self.bot.send_message(peer_id, 'Произошла ошибка. Повторите попытку позднее.')
            except:
                self.log.exception('')
                raise

        while True:
            try:
                event = self.bot.get_event()
                send_message(event)
            except TypeError:
                self.log.warning('Got TypeError in messages_handler()')
            except:
                self.log.exception('')
                raise
コード例 #18
0
# Авторизуемся как сообщество
vk = vk_api.VkApi(token=token)

# Работа с сообщениями
longpoll = VkLongPoll(vk)
upload = VkUpload(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.user_id}', end='')

            bot = VkBot(event.user_id)
            # определяет какого типа сообщение - если требуется ответ от пользователя то создадим новый цикл
            result = write_msg(event.user_id, bot.new_message(event.text), "Нет процесса")
            if result == "Конвертация":
                # запуск процесса Конвертации
                timing = time.time()
                for event in longpoll.listen():
                    if time.time() - timing > 100:
                        break
                    elif event.type == VkEventType.MESSAGE_NEW:
                        if event.to_me:
                            timing = time.time()
                            if not write_msg(event.user_id, event.text, "Конвертация"):
                                break
            if result == "Банкомат":
                # запуск процесса Конвертации
コード例 #19
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)
コード例 #20
0
ファイル: bot.py プロジェクト: KuzminDS/vkBot
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()
コード例 #21
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:
コード例 #22
0
ファイル: manage.py プロジェクト: delvin-fil/vk-bot
               'keyboard': key,
               'random_id': random.randint(0, 2048)})


vk = vk_api.VkApi(token=
                  "Your_token_there")


longpoll = VkLongPoll(vk)


try:
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            if event.to_me:
                bot = VkBot(event.user_id)

                if event.text.lower() == "о нас 🎯":
                    write_msg(event.user_id, "Немного о нашем проекте", about_us_keyboard)
                elif event.text.lower() == "мероприятия 🍔":
                    write_msg(event.user_id, "Что ты хочешь узнать?", events_keyboard)
                elif event.text.lower() == "приложения 🌏":
                    write_msg(event.user_id, "Посмотри, что есть здесь!", app_keyboard)
                elif event.text.lower() == "контакты 📙":
                    write_msg(event.user_id, "По любым вопросам можешь обращаться к:", contacts_keyboard)
                elif event.text.lower() == "задать вопрос руководителю проекта":
                    write_msg(event.user_id, "У тебя есть возможность написать сообщение нашему Руководителю проекта 👇",
                              go_answer)
                elif event.text.lower() == "калькулятор 💡":
                    write_msg(event.user_id, "В разработке...", calc_keyboard)
                # elif event.text == " ".join(re.findall('\d{2}', event.text)):
コード例 #23
0
def main():
    bot = VkBot(config.token, config.group_id)
    bot.start()
コード例 #24
0
ファイル: bot.py プロジェクト: CxxlMint/Infuzoria-Bashmak
                        'user_id': get_user_friend(user_id),
                        'message': message,
                        'attachment': dialog_image,
                        'random_id': random.randint(0, 2048)
                    })


print("Сервер запущен")
for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW and event.to_me:
        print(f'Новое сообщение от {event.user_id}', end='')

        if get_user(event.user_id) is None:
            register_new_user(event.user_id)

        bot = VkBot(event.user_id)

        if get_user_in_game(event.user_id)[0] == 1:
            vk_bot_adventure(event)
        elif get_user_in_chat(event.user_id) == 1:
            vk_bot_anon_chat(event)
        elif get_user_state(event.user_id)[0] is None:
            vk_bot_osnova(event)
        else:
            if get_user_state(event.user_id)[0] == "registration_over":
                if get_game_stage(get_user_room(event.user_id)) == 0:
                    print('статус комнаты: 0')
                    vk_bot_osnova(event)
                elif get_game_stage(get_user_room(event.user_id)) == 1:
                    print('статус комнаты: 1')
                    vk_bot_in_killer(event)
コード例 #25
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()
コード例 #26
0
])

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:
コード例 #27
0
import random
import vk_api
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType

from settings import vk_group_token, vk_group_id
from vk_bot import VkBot
import requests

token = vk_group_token
vk_session = vk_api.VkApi(token=token)

print("Server started")
bot = VkBot()
while True:
    longpoll = VkBotLongPoll(vk_session, vk_group_id)
    vk = vk_session.get_api()
    try:
        for event in longpoll.listen():
            if event.type == VkBotEventType.MESSAGE_NEW:
                message = bot.new_message(event.object.message['text'],
                                          event.object.message['from_id'],
                                          event.object.message['peer_id'])
                if message != "no":
                    vk.messages.send(peer_id=event.object.message['peer_id'],
                                     message=message,
                                     random_id=random.randint(0, 2048))
    except requests.exceptions.ReadTimeout as timeout:
        continue
コード例 #28
0
ファイル: main.py プロジェクト: zPlumbum/Diploma_PythonAD
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
        }
    )

コード例 #29
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)
コード例 #30
0
ファイル: bot.py プロジェクト: MannCoMan/BotMafia
keyboard = VkKeyboard()
keyboard.add_button('Привет', color=VkKeyboardColor.DEFAULT)
keyboard.add_button('Погода', color=VkKeyboardColor.POSITIVE)
keyboard.add_line()
keyboard.add_button('Время', color=VkKeyboardColor.NEGATIVE)
keyboard.add_button('Пока', color=VkKeyboardColor.PRIMARY)

# Основной цикл бота
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}')

            # Ответы в зависимости от сообщения пользователя
            bot = VkBot(event.user_id)
            vk.messages.send(
                user_id=event.user_id,
                message=bot.new_message(event.text),
                random_id=get_random_id(),
                keyboard=keyboard.get_keyboard()
            )
            print('Text: ', event.text)