-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
230 lines (195 loc) · 5.68 KB
/
index.js
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
/**
* The useful library to simplify your work with Telegram Bot API
*
* @module telekit
* @author Denis Maslennikov <[email protected]> (nofach.co)
* @license MIT
*/
/** Dependencies */
const FormData = require('form-data');
const FileType = require('file-type');
const stream = require('stream');
const debug = require('debug');
const got = require('got');
/** Debug */
debug.error = debug('teleapi:error');
debug.error.color = 1;
debug.http = debug('teleapi:api');
debug.http.color = 2;
debug.api = debug('teleapi:api');
debug.api.color = 3;
/**
* Variables
* @private
*/
const API_FILE = 'https://api.telegram.org/file/bot';
const API_URL = 'https://api.telegram.org/bot';
/**
* Available API Methods
* @private
*/
const API_DEFAULT = require('./api.json');
/**
* Methods
* @private
*/
/**
* Checks whether an object is multipart/form-data
* @private
*
* @param {Object} obj - An object with form-data
* @return {Boolean}
*/
function isFormData(obj) {
return Object.keys(obj).some((key) => {
if (obj[key] instanceof stream.Stream) return true;
if (Buffer.isBuffer(obj[key])) return true;
return false;
});
}
/**
* Normalizes an object to sending into body of the request
* @private
*
* @param {Object} obj - An object with data for sending
* @return {Object|form-data}
*/
function normalize(obj) {
const isMultipart = isFormData(obj);
const content = { filename: '', value: '', mime: '' };
const result = ((isMultipart) ? new FormData() : {});
let file = null;
Object.keys(obj).forEach((item) => {
if (isMultipart) {
if (obj[item].value) content.value = obj[item].value;
else content.value = obj[item];
content.filename = obj[item].filename || null;
content.mime = obj[item].mime || null;
if (content.value instanceof stream.Stream) {
result.append(item, content.value, {
contentType: content.mime,
filename: content.filename,
});
return;
}
if (Buffer.isBuffer(content.value)) {
file = FileType(content.value);
result.append(item, content.value, {
contentType: content.mime || file.mime || 'application/octet-stream',
filename: content.filename || `data-${Date.now()}.${file.ext || ''}`,
});
return;
}
if (typeof content.value === 'object') {
result.append(item, JSON.stringify(content.value), {
contentType: 'application/json',
});
return;
}
result.append(item, content.value);
} else {
if (typeof obj[item] === 'object') {
result[item] = JSON.stringify(obj[item]);
return;
}
result[item] = obj[item];
}
});
return result;
}
/**
* Custom Errors
* @public
*/
class APIError extends Error {
constructor(method, params, response) {
super();
this.name = 'APIError';
this.method = method;
this.params = params;
this.message = response.description;
this.timeout = response.retry_after || null;
this.migrate = response.migrate_to_chat_id || null;
this.code = response.error_code;
}
}
/**
* Implementation
* @public
*/
class API {
/**
* Create an instance of the teleapi
* @public
*
* @param {String} token - Token of the bot
* @param {Object} custom - An object with Custom API
*/
constructor(token = '', api = API_DEFAULT) {
this.methods = api.methods;
this.version = api.version;
this.token = token;
debug.api('version: %s', this.version);
this.generator(api.methods);
}
/**
* Send the request to Telegram Bot API
* @private
*
* @param {String} name - Name of the method
* @param {Object} params - Body of the request
* @return {Promise}
*/
method(name, params = {}) {
const options = { json: true };
const form = normalize(params);
const url = `${API_URL}${this.token}/${name}`;
if (form.getHeaders) {
options.headers = form.getHeaders();
}
options.body = form;
debug.http('use %s with params: %O', name, params);
return got(url, options).then((response) => {
debug.http('%s is it responded: %O', name, response.body.result);
return response.body.result;
}).catch((error) => {
let buffer = error;
// hook
if (buffer.name === 'HTTPError' && buffer.response.body) {
buffer = new APIError(name, params, buffer.response.body);
debug.error('%s(%s) %s', buffer.name, buffer.method, buffer.message);
}
throw buffer;
});
}
/**
* Generates a wrapped methods from an Array of String
*
* @param {Array} list - An Array of String with method names
* @private
*/
generator(list) {
list.forEach((item) => {
debug.api('%s is added', item);
this[item] = params => this.method(item, params);
});
}
/**
* Get file from the Telegram Bot API
* @public
*
* @param {String} id - File ID
* @return {Stream}
*/
getFile(id) {
return got.stream(`${API_FILE + this.token}/${id}`);
}
}
/** Exports */
module.exports = Object.assign((token, custom) => {
if (token) return new API(token, custom);
return API;
}, {
version: API_DEFAULT.version,
methods: API_DEFAULT.methods,
});