L
L
loadi2017-08-12 19:26:38
Python
loadi, 2017-08-12 19:26:38

How to force bot to read messages from conf?

This code sends messages to conf number 9, but if someone else (outside conf number 9) writes "/hello", then the bot will respond to his command. How to make the bot listen to commands only inside the chat?

import time
import vk_api
vk = vk_api.VkApi(login = 'login', password = 'password')
vk.auth()
values = {'out': 0,'count': 100,'time_offset': 60}

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

while True:
    response = vk.method('messages.get', values)
    if response['items']:
        values['last_message_id'] = response['items'][0]['id']
    for item in response['items']:
            if response['items'][0]['body'] == '/hello': 
                write_msg(9,'Привет')
    time.sleep(1)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Sazhenov, 2017-08-22
@loadi

I use libu vk (recently my own)

import vk, time

session = vk.AuthSession(user_login='<user login>', user_password='<user password>', app_id='<app id>') # может не сработать, сразу пихай в vk.Session token, чтобы не заморачиваться, а лучше юзай либу vkAPI(позже залью в PyPI)
api = vk.API(session, v='5.68')
values = {'out': 0,'count': 100,'time_offset': 60}

def write_msg(chat_id, s):
    api.messages.send(**{'chat_id':chat_id,'message':s}))

while True:
    response = api.messages.get(**values)
    if response['items']:
        values['last_message_id'] = response['items'][0]['id']
    for item in response['items']:
            if (item['body'] == '/hello') and (int(item['chat_id']) == 9): 
                write_msg(9,'Привет')
    time.sleep(1)

U
userfordownload, 2017-08-12
@userfordownload

At you it is implemented through Callback API?
All events are heard there.
We listen to the message_new event - a new incoming message
Scan the parameter chat_id (integer) - the identifier of the conversation (YOUR CONVERSATION).
If it matches - we answer) no - we do nothing)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question