aboutsummaryrefslogtreecommitdiff
path: root/src/lib/core.js
blob: 976f4580771f7e4ab7323b35ddf433b1f6bfd59d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/**
 * @project iii-for-vk
 * @author Valentin Popov <info@valentineus.link>
 * @license See LICENSE.md file included in this distribution.
 */
import urlParseLax from 'url-parse-lax';
import queryString from 'querystring';
import iiiClient from 'iii-client';
import EventEmitter from 'events';
import inherits from 'inherits';
import https from 'https';
import SDK from 'vksdk';

inherits(Bot, EventEmitter);
module.exports = Bot;

/**
 * Class representing a Bot.
 * @class
 */
function Bot(opts) {
    opts = opts || {};
    var self = this;

    self.uuid = opts.uuid;
    self.token = opts.token;
    self.appID = opts.appID;
    self.appSecret = opts.appSecret;
}

/**
 * Initial initialization of all systems and services.
 * @param {requestCallback} callback - The callback that handles the response.
 */
Bot.prototype.init = function(callback) {
    var self = this;

    // Initialize the connection to the social network
    self._vk = new SDK({
        appId: self.appID,
        appSecret: self.appSecret,
        https: true,
        secure: true
    });

    // Setting the user's token
    self._vk.setToken(self.token);

    // Starting services
    self._eventLoop();
    // Connecting filters
    self._filterMessages();

    // Connecting to the bot server
    iiiClient.connect(self.uuid, (raw) => callback(raw.cuid));
};

/**
 * Receive a message by its ID.
 * @param {Number} id - The message ID.
 * @param {requestCallback} callback - The callback that handles the response.
 */
Bot.prototype.getMessageByID = function(id, callback) {
    id = id || false;
    var self = this;

    self._vk.request('messages.getById', {
        message_ids: id,
        preview_length: 0
    }, (raw) => {
        if (raw.error) throw new Error(raw.error.error_msg);
        callback(raw.response.items.shift());
    });
};

/**
 * Simplifies the sending of a message to the user.
 * The social network API is used.
 * More information: https://vk.com/dev/messages.send
 * @param {Object} options - Object with parameters.
 * @param {Object} options.user_id - User ID.
 * @param {Object} options.message - Message text.
 * @param {requestCallback} callback - The callback that handles the response.
 */
Bot.prototype.sendMessageToVK = function(options) {
    options = options || {};
    var self = this;
    self._vk.request('messages.send', options, () => {});
};

/**
 * Simplifies sending a message to the bot.
 * @param {Object} options - Object with parameters.
 * @param {Object} options.cuid - Session identifier.
 * @param {Object} options.text - Message text.
 * @param {requestCallback} callback - The callback that handles the response.
 */
Bot.prototype.sendMessageToBot = function(options, callback) {
    options = options || {};
    iiiClient.send(options, (answer) => callback(answer));
};

/**
 * The event startup service.
 */
Bot.prototype._eventLoop = function() {
    var self = this;

    self._getEvents();
    self.on('events', (data) => {
        self._getEvents(data.ts);
    });
};

/**
 * Filter events for incoming messages.
 * @fires: Bot#messages
 */
Bot.prototype._filterMessages = function() {
    var self = this;

    self.on('events', function(data) {
        data.updates.filter(function(item) {
            if (item[0] == 4) self.emit('messages', item);
        });
    });
};

/**
 * Obtaining the Long Poll server address.
 * @param {requestCallback} callback - The callback that handles the response.
 */
Bot.prototype._getLongPollServer = function(callback) {
    var self = this;

    self._vk.request('messages.getLongPollServer', {
        need_pts: false
    }, (raw) => {
        if (raw.error) throw new Error(raw.error.error_msg);
        callback(raw.response);
    });
};

/**
 * Waiting and returning the event.
 * @fires: Bot#events
 * @param {String=} [ts] - The ID of the last event.
 */
Bot.prototype._getEvents = function(ts) {
    var self = this;

    // Server address request
    self._getLongPollServer(function(raw) {
        ts = ts || raw.ts;

        // Analysis of the connection address
        var url = urlParseLax(raw.server);

        // Details: https://vk.com/dev/using_longpoll
        var options = queryString.stringify({
            act: 'a_check',
            key: raw.key,
            ts: ts,
            wait: 25,
            mode: 2,
            version: 1
        });

        // Configuring the connection
        var query = {
            hostname: url.hostname,
            path: url.pathname + '?' + options
        };

        https.get(query, function(response) {
            var answer = {};
            response.setEncoding('utf8');
            response.on('data', (data) => answer = data);
            response.on('end', () => {
                answer = JSON.parse(answer);
                self.emit('events', answer);
            });
        }).on('error', (error) => Error(error));
    });
};