N
N
Nekrasova Elizabeth2020-03-07 11:52:33
Python
Nekrasova Elizabeth, 2020-03-07 11:52:33

How to make the bot work in asynchronous mode?

Hello!

I recently started learning how to build bots in Python.
I learned what and how to write so that the bot works.
I write by the way using the vk_api library.
Everything seemed to be fine. But ..
I noticed that if the bot does something other than "wiretapping" the server (in my case, generating a picture), then the wiretapping is frozen and the bot responds only later, when the picture is generated and sent to the user. So it's not good ....
I looked through some libraries with multithreading, etc. But something didn’t work out
And I would like to ask you about this, what and how can I do.
Here is the code of my project (the necessary minimum is left):

import vk_api
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.utils import get_random_id

token = 'ТОКЕН'
vk_session = vk_api.VkApi(token=token)

vk = vk_session.get_api()
longpool = VkBotLongPoll(vk_session, ID группы)

def create_img():
    """
код для генерации и сохранения картинки
"""

while True:
    for event in longpool.check():
        user_id = event.obj.from_id
        if event.type == VkBotEventType.MESSAGE_NEW:
            if not check_reg(event.obj.from_id):
                register_new_user(event.obj.from_id)
            response = str(event.obj.text).lower()
            if response == 'привет':
                create_img() #генерируем картинку
                upload = vk_api.Upload(vk_session)
                photo = upload.photo_messages(
                    'путь до фотографии, которую сгенерировала функция выше',
                    user_id
                )  # сохранение картинки на сервер || хранится вся информация, которую вернул сервер
                attachment = 'photo{}_{}_{}'.format(photo[0]['owner_id'], photo[0]['id'],
                                                    photo[0]['access_key'])  # создается полное название вложения
                vk.messages.send(
                    user_id=user_id,
                    message='Привет!!!',
                    attachment=attachment,
                    keyboard=create_keyboard(response, user_id),
                    random_id=get_random_id()
                )


I would be very grateful if you help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2020-03-07
@deliro

Google ThreadPoolExecutor / ProcessPoolExecutor, after accepting the event, throw the event into the pool

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question