hostname = 'http://localhost:5050' docs_info = { "ru": ''' Как подключить callback

Введение и написание кода

Наш модуль написан для работы с callback событиями серверов vk.com и создания ботов на принципе callback. Этот метод подходит для нагруженных проектов, которые соединяют в себе несколько ботов, образуя сеть ботов.

Итак, наш модуль имеет следующие классы: server, group, vk_event, vk_callbackException. Чтобы вы могли написать бота, вам нужны только два из них: server и group. Перейдём непосрдественно к коду:

Для начала, мы должны создать класс, который наследуется от класса server и создадим там метод event со следующими аргументами:

import vk_callback


class bot(vk_callback.server):
    def event(self, group_obj, Event):
        pass  # Сюда будем писать код

group_obj отвечает за объект группы, Event - это объект события.

У group_obj есть следующие параметры: id, return_str, secret_key. Для разработки бота нам достаточно только id, где id это id группы.

У Event есть следующие параметры: type, object, group_id, event_id, secret (всё тоже самое, что и в объекте события вк). Для object это словарь с параметрами объекта события.

Проверять секретный ключ нет необходимости, за это отвечает метод класса confirmation_secret. Перейдём же к самому интересному... Давайте подключим двух ботов и сделаем для них разные ответы, чтобы отчётливее продемонстрировать возможности ботов:

К нашему методу event мы добавим код, который мы хотим реализовать. Далее, мы ниже создаём объект класса bot и добавляем туда объекты класса group, которые будут являться объектами групп, к которым мы подключили callback. Затем, запускаем нашего бота

import vk_callback
import vk_api
import random


class bot(vk_callback.server):
    def event(self, group_obj, Event):
        bot_1 = vk_api.VkApi(token='***').get_api()
        bot_2 = vk_api.VkApi(token='***').get_api()
        if Event.type == 'message_new':
            if group_obj.id == 12345678:
                bot_1.messages.send(peer_id=Event.object['peer_id'], random_id=random.randint(0, 999999), message='hello')
            else:
                bot_2.messages.send(peer_id=Event.object['peer_id'], random_id=random.randint(0, 999999), message='hi')


bot = bot(host='website.ru', groups=[
    vk_callback.group(12345678, return_str="11693324", secret_key="secret_key_here"),
    vk_callback.group(87654321, return_str="1af47ed9", secret_key="secret_key_here")
], port=8080)

bot.start()

Как подключить callback

Подключить callback сервер к вашей группе очень просто! Для начала, заходим в настройки группы в раздел "работа с API", затем заходим в раздел callback

Затем, нам нужно выбрать в настройках события, которые мы будем обрабатывать

Отлично! Теперь мы можем приступить к подключению нашего сервера. Для начала, скопируем что должен вернуть при подтверждении бот и его секретный ключ и вставим в код нашей программы, также скинем в объект айди нашей группы.

Запускаем сервер, в графе адреса заполняем адрес нашего сервера в формате crthst::rpl/айди_группы

Жмём подтвердить. Поздравляем, бот подключен!

''', "en": ''' Как подключить callback

Introduction and code writing

Our module is designed to work with server callback events vk.com and creating bots based on the callback principle. This method is suitable for loaded projects that combine several bots to form a network of bots.

So, our module has the following classes: server, group, vk_event, vk_callbackException. In order for you to write a bot, you only need two of them: server & group. Let's go straight to the code:

First, we need to create a class that inherits from the server class and create the event method there with the following arguments:

import vk_callback


class bot(vk_callback.server):
    def event(self, group_obj, Event):
        pass  # Here we will write the code

group_obj is responsible for the group object, Event is the event object.

group_obj has the following parameters: id, return_str, secret_key. To develop a bot, we only need an id, where id is the group id.

Event has the following parameters: type, object, group_id, event_id, secret (all the same as in the vk event object). For object, this is a dictionary with parameters for the event object.

There is no need to check the secret key.The method of the confirmation_secret class is responsible for this. Let's move on to the most interesting part... Let's connect two bots and make different responses for them to better demonstrate the capabilities of bots:

To our event method, we will add the code that we want to implement. Next, we create an object of the bot class below and add objects of the groupclassthere, which will be objects of the groups to which we connected the callback. Then, we launch our bot

import vk_callback
import vk_api
import random


class bot(vk_callback.server):
    def event(self, group_obj, Event):
        bot_1 = vk_api.VkApi(token='***').get_api()
        bot_2 = vk_api.VkApi(token='***').get_api()
        if Event.type == 'message_new':
            if group_obj.id == 12345678:
                bot_1.messages.send(peer_id=Event.object['peer_id'], random_id=random.randint(0, 999999), message='hello')
            else:
                bot_2.messages.send(peer_id=Event.object['peer_id'], random_id=random.randint(0, 999999), message='hi')


bot = bot(host='website.ru', groups=[
    vk_callback.group(12345678, return_str="11693324", secret_key="secret_key_here"),
    vk_callback.group(87654321, return_str="1af47ed9", secret_key="secret_key_here")
], port=8080)

bot.start()

How to connect callback

Connecting a callback server to your group is very simple! First, go to the group settings in the "API usage", section, then go to the callback section

Then, we need to select the events that we will process in the settings

Great! Now we can start connecting our server. To begin with, we will copy what the bot should return when confirming and its secret key and paste it into the code of our program, as well as throw it into the ID object of our group.

Starting the server, in the address column, fill in the address of our server in the format crthst::rpl/group_id

Click confirm. Congratulations, the bot is connected!

''' } for lang in docs_info: docs_info[lang] = docs_info[lang].replace('crthst::rpl', hostname)