Answer the question
In order to leave comments, you need to log in
How to get messages from a VK conversation using Longpoll Python?
If you remove "Bot" from everywhere, then the code will work successfully in private messages, but initially it was necessary to make it work in a conversation. How to organize it? On startup, there will be similar type of errors about VkBotMessageEvent
that can't process anything.
How to fix this and add a working message handler from the conversation? (When you enter "kbd" a keyboard from json will appear, which successfully appears in a dialog with a bot, etc.)
import vk_api
from vk_api import VkApi
import random, vk_api.bot_longpoll
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import time
vk_session = vk_api.VkApi(token = "tokenhere" )
longpoll = VkBotLongPoll (vk_session, groupid)
vk = vk_session.get_api()
global Random
def random_id():
Random = 0
Random += random.randint(0, 90000000000)
return Random
while True:
for event in longpoll.listen():
if event.type == VkBotEventType.MESSAGE_NEW and event.to_me and event.text:
if event.text.lower() == "ping":
vk.messages.send(
user_id = event.user_id,
message = "pong",
random_id = random_id()
)
elif event.text.lower () == "kbd":
vk.messages.send(
user_id = event.user_id,
message = "Added",
keyboard = open("jsonvk.json", "r", encoding="utf-8"). read(),
random_id = random_id()
)
elif event.text.lower () == "kbdr":
vk.messages.send(
user_id = event.user_id,
message = "Removed",
keyboard = open("jsovkr.json", "r", encoding="utf-8"). read(),
random_id = random_id()
)
elif event.from_chat:
if event.text == "1":
vk.messages.send(
chat_id = event.chat_id,
messages = "here",
random_id = random_id()
)
Answer the question
In order to leave comments, you need to log in
import vk_api, random, time
from vk_api.longpoll import VkLongPoll, VkEventType
vk = vk_api.VkApi(token='token')
longpoll = VkLongPoll(vk)
def send(message):
if event.from_user: # Для ЛС
vk.method('messages.send', {'user_id': event.user_id, 'message': message, 'random_id': random.getrandbits(64)})
elif event.from_chat: # Для бесед
vk.method('messages.send', {'chat_id': event.chat_id, 'message': message, 'random_id': random.getrandbits(64)})
while True:
for event in longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW and event.to_me:
text = event.text.lower()
u_id = event.user_id # (Если будет нужно)
if text == 'ping': # Пример
send('pong')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question