D
D
Dima_Demichev2018-03-25 17:12:48
In contact with
Dima_Demichev, 2018-03-25 17:12:48

How to write a vk bot in Node.js?

Hello, I ran into a few problems while writing the bot. The bot is written not for the community, but for a personal page.
1. Wrong encoding, I understand that utf-8 encoding is needed. Because in English the answer is sent.
2. setInterval costs 2 seconds, so the bot sends 2 messages at once. Because in 10 seconds it sends only 1. How can this be fixed?
The code:

var https = require('https');
    function request(method, parameters){
    https.get("https://api.vk.com/method/"+method+"?"+parameters, (request) => {
      request.on('data', (json) => {
        data = JSON.parse(json);
        chat[0] = data.response.items[0].id;
        chat[1] = data.response.items[0].body;
        chat[2] = data.response.items[0].user_id;

      });
    });
    }

    setInterval(function(){
    request("messages.getHistory", "chat_id="+chat_id+"&count=1&access_token="+access_token+"&v=5.52");
    if (chat[1] == "Привет"){
        console.log(data);
        require('https').get("https://api.vk.com/method/messages.send?chat_id="+chat_id+"&message=Здравствуй&forward_messages="+chat[0]+"&access_token="+access_token+"&v=5.68");
    }
    }, 2000);

How can this be fixed? How should a bot for vk api be written in general, how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Skibin, 2018-03-25
@Dima_Demichev

1. Yes, you need it in UTF-8
2. Your request is asynchronous - translate it through async / await or wrap it in a promise so that you can receive data from it and respond accordingly. Making the chat variable global (as far as I can tell from the code) is a bad idea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question