-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.ts
319 lines (290 loc) · 9.34 KB
/
api.ts
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import crypto from 'crypto';
import request from 'request-promise';
import { log } from '../extra/log';
import Stats from '../extra/stats';
/**
* VK API version used by API.
*/
const API_VERSION = '5.95';
/**
* API quota, in requests per second
*/
const API_QUOTA = 20;
/**
* Used to call API methods.
*
* You can get the [[API]] object from a [[Context]] object:
* ```js
* // Assuming your Context object is $
* var api = $.api
* ```
*
* Or from [[Core]] (after initialization with [[bot]]:
* ```js
* var api = core.api
* ```
*/
export default class API {
/**
* VK API token.
*/
private vkToken: string;
/**
* Stats object.
*/
private stats: Stats;
/**
* Queue of scheduled API calls.
*/
private queue: {
method: string;
params: { [key: string]: string };
resolve: Function;
reject: Function;
}[] = [];
/**
* Is the queue being processed now?
*/
private isQueueProcessing = false;
/**
* Creates a new [[API]].
* @param vkToken VK API token
* @param stats [[Stats]] object
*/
public constructor(vkToken: string, stats: Stats) {
this.vkToken = vkToken;
this.stats = stats;
// Check permissions
this.checkPermissions()
.then((e): void => {
log()
.i(e)
.from('api')
.now();
})
.catch((e): void => {
log()
.w(e)
.from('api')
.now();
});
// Start the queue processing
setInterval((): void => {
if (!this.isQueueProcessing) {
this.isQueueProcessing = true;
this.processQueue()
.then((): void => {
this.isQueueProcessing = false;
})
.catch((e): void => {
log()
.w(e)
.from('api')
.now();
this.isQueueProcessing = false;
});
}
}, 1000);
}
/**
* Schedules a call to a VK API Method.
*
* After the call completes, a check will be performed to see if the call was successful or not,
* and in the latter case a warning will be logged.
*
* @param method VK API method name
* @param params parameters for the method, `access_token` and `v` will be added automatically
*
* @return promise, which resolves with `json.response` when the request is completed
* and a response is given, and rejects if an error happened
*
* @example
* ```
* core.cmd('info', async $ => {
* var uid = $.obj.from_id;
*
* // Call VK API to get information about the user
* var response = await $.api.scheduleCall('users.get', { user_ids: uid });
* var userInfo = response[0];
*
* var name = userInfo.first_name;
* var surname = userInfo.last_name;
*
* $.text(`User ID: ${uid}\nName: ${name} ${surname}`);
* });
* ```
*/
public async scheduleCall(method: string, params: { [key: string]: string }): Promise<any> { // eslint-disable-line @typescript-eslint/no-explicit-any
return new Promise((resolve, reject): void => {
this.queue.push({
method,
params,
resolve,
reject,
});
});
}
/**
* Call a VK API Method.
*
* **It is highly recommended to use [[scheduleCall]]
* instead to not exceed the API quota and to check whether the call was successful or not!**
*
* @param method VK API method name
* @param params parameters for the method, `access_token` and `v` will be added automatically
*
* @example
* ```
* core.cmd('info', async $ => {
* var uid = $.obj.from_id;
*
* // Call VK API to get information about the user
* var json = await $.api.call('users.get', { user_ids: uid });
* var userInfo = json.response[0];
*
* var name = userInfo.first_name;
* var surname = userInfo.last_name;
*
* $.text(`User ID: ${uid}\nName: ${name} ${surname}`);
* });
* ```
*/
public async call(
method: string,
params: { [key: string]: string },
): Promise<any> { // eslint-disable-line @typescript-eslint/no-explicit-any
const url = `https://api.vk.com/method/${encodeURIComponent(method)}`;
const options = {
uri: url,
json: true,
qs: {
access_token: this.vkToken, // eslint-disable-line @typescript-eslint/camelcase
v: API_VERSION,
...params,
},
};
const promise = request(options);
promise.catch((err: Error): void => {
log()
.w(`Error occured while calling API method '${method}': ${err}`)
.from('api')
.now();
});
return promise;
}
/**
* Sends a message to a user via Peer ID.
*
* **Note that it is much easier to use the [[Context]] object passed to handlers
* to compose and send messages, keyboards and attachments!**
*
* @param pid peer ID
* @param message message text **(required, if attachment is empty)**
* @param attachment list of attachments, comma-separated
* (see [VK API Docs](https://vk.com/dev/messages.send) for further information)
* **(required if message is empty)**
* @param keyboard json of keyboard
*
* @example
* ```
* await api.send(1, 'Hello!', 'photo6492_456240778')
* ```
*/
public async send(
pid: string | number,
message: string,
attachment: string,
keyboard: string,
): Promise<void> {
/* global BigInt */
const params: {
peer_id: string;
message?: string;
attachment?: string;
keyboard?: string;
random_id: string;
} = {
peer_id: pid.toString(), // eslint-disable-line @typescript-eslint/camelcase
random_id: BigInt.asIntN( // eslint-disable-line @typescript-eslint/camelcase
32,
BigInt(`0x${crypto.randomBytes(6).toString('hex')}`),
).toString(),
};
if (message) {
params.message = message;
}
if (attachment) {
params.attachment = attachment;
}
if (keyboard) {
params.keyboard = keyboard;
}
return new Promise((resolve): void => {
this.scheduleCall('messages.send', params)
.then((): void => {
this.stats.sent();
resolve();
})
.catch((e): void => {
log()
.w(e)
.from('api')
.now();
resolve();
});
});
}
/**
* Checks if the required permissions for bot to work properly are present,
* and emits a warning if that is not the case.
*/
private async checkPermissions(): Promise<string> {
// Check if the token has the required permissions
const response = await this.scheduleCall('groups.getTokenPermissions', {});
const { permissions } = response;
let ok = false;
permissions.forEach((permission: any): void => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (permission.name === 'messages') {
ok = true;
}
});
if (!ok) {
return Promise.reject(
new Error(
'Token permission `messages` is missing. Bot will be unable to send any messages',
),
);
}
return Promise.resolve('Token permission `messages` is present');
}
/**
* Move forward through the queue, processing at most [[API_QUOTA]] items
*/
private async processQueue(): Promise<void> {
if (this.queue) {
for (let i = 1; i <= API_QUOTA; i += 1) {
if (this.queue.length === 0) {
break;
}
const e = this.queue.shift();
/* eslint-disable-next-line no-await-in-loop */
const json = await this.call(e.method, e.params);
if (json.response !== undefined && json.response !== null) {
e.resolve(json.response);
} else if (json.error) {
const errorCode = json.error.error_code;
const errorMsg = json.error.error_msg;
e.reject(
`An API call to method '${e.method}' failed due to an API error #${errorCode}: ${errorMsg}`,
);
} else {
e.reject(
`An API call to method '${e.method}' failed due to an unknown API error. The API responded with: ${JSON.stringify(json)}`,
);
}
}
return Promise.resolve();
}
return Promise.reject(new Error('No queue for API calls found'));
}
}