B
B
bodya_kireev2018-12-09 19:18:51
Python
bodya_kireev, 2018-12-09 19:18:51

How to create random_id function in vk_api?

Help implement the random_id function. I did not find a description of the function in the documentation.

import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType


def write_msg(user_id, message):
    vk.method('messages.send', {'user_id': user_id, 'message': message})


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

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

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

# Основной цикл
for event in longpoll.listen():

    # Если пришло новое сообщение
    if event.type == VkEventType.MESSAGE_NEW:

        # Если оно имеет метку для меня( то есть бота)
        if event.to_me:

            # Сообщение от пользователя
            request = event.text

            # Каменная логика ответа
            if request == "привет": write_msg(event.user_id, "Хай")
            elif request == "пока":write_msg(event.user_id, "Пока((")
            else: write_msg(event.user_id, "Не поняла вашего ответа...")

Here is the error code:
vk_api.exceptions.ApiError: [100] One of the parameters specified was missing or invalid: random_id is a required parameter

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
HemulGM, 2020-01-15
@HemulGM

For those who stumble upon the question in the future (like me).
random_id is a parameter that must also be passed when sending a new message.

random_id - a unique (in relation to API_ID and sender ID) identifier designed to prevent re-sending of the same message. Saved with the message and available in the message history.
The given random_id is used to check for uniqueness over the entire message history, so use a large range (up to int64).

Personally, I recommend using the date and time as a unique key as random_id. Namely - to translate the date and time into milliseconds.

D
Dunge, 2020-02-04
@Dunge

vk.messages.send(peer_id = event.peer_id, random_id = 0, message = 'Текст')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question