-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
304 lines (244 loc) · 5.84 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
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
var Duplex = require('stream').Duplex
var inherits = require('inherits')
var Telegram = require('telegram-bot-api')
var WebhookPost = require('webhook-post')
/**
* Send data as messages to a Telegram chat
*
* @class
*
* @param {string} token
* @param {string} chat_id
* @param {Object} [options]
* @param {string|Object|80|88|443|8443} [options.webhook={}]
* @param {string} [options.webhook.hostname='0.0.0.0']
* @param {80|88|443|8443} [options.webhook.port]
* @param {string} [options.webhook.certificate='']
* @param {string} [options.certificate='']
*
* @emits TelegramLog#data
* @emits TelegramLog#error
* @emits Readable#end
*/
function TelegramLog(token, chat_id, options)
{
if(!(this instanceof TelegramLog))
return new TelegramLog(token, chat_id, options)
var self = this
if(token.constructor.name === 'Object')
{
chat_id = token.chat_id
options = token.options
token = token.token
}
options = options || {}
options.objectMode = true
TelegramLog.super_.call(this, options)
if(!token) throw 'Missing token'
if(!chat_id) throw 'Missing chat_id'
var _updatesOffset = 0
var api = new Telegram({token: token})
//
// Private functions
//
/**
* @param {string} message
* @param {*} data
*/
function emitError(message, data)
{
var error = new Error(message)
error.data = data
self.emit('error', error)
}
/**
* Process a single received Telegram `Update` object
*
* @param {Object} update
*
* @return Boolean - more `Update` objects can be fetch
*/
function processUpdate(update)
{
// Account update_id as next offset
// to avoid dublicated updates
var update_id = update.update_id
if(update_id >= _updatesOffset)
_updatesOffset = update_id + 1
// Check the update is from a text message from our chat
var message = update.message
if(message == null)
return emitError('Inline queries are not supported', update)
if(message.chat.id !== chat_id)
return emitError('Received message for not-listening chat', message)
var text = message.text
if(text == null)
return emitError('Only text messages are supported', message)
// Everything is allright, push the data
return self.push(message.text)
}
var end = this.push.bind(this, null)
//
// Webhook
//
var webhook = options.webhook
if(webhook)
{
/**
* Close the webhook and set it as finished
*/
function closeWebhook()
{
webhook.close()
webhook = null
}
if(typeof webhook !== 'string')
{
// Telegram only support ports 80, 88, 443 and 8443
var port = webhook.port || webhook
if(port !== 80 && port !== 88 && port !== 443 && port !== 8443)
{
var error = new RangeError('Port must be one of 80, 88, 443 or 8443')
error.port = port
throw error
}
}
var certificate = webhook.certificate || options.certificate || ''
// Create webhook
webhook = WebhookPost(webhook, options)
.on('open', function(url)
{
api
.setWebhook({url: url, certificate: certificate})
.catch(function(error)
{
self.emit('error', error)
webhook = null
end()
})
})
.on('data', function(data)
{
var update = JSON.parse(data)
// Ignore duplicated updates
if(update.update_id >= _updatesOffset) processUpdate(update)
})
.on('error', this.emit.bind(this, 'error'))
.on('end', function()
{
if(!webhook) return end()
webhook = null
api.setWebhook({certificate: certificate}).then(end, end)
})
}
//
// Polling
//
var polling
var inFlight
/**
* Process a Telegram `Update` object and check if it should do more requests
*
* @param {Boolean} fetchMoreDate
* @param {Object} update
*
* @return Boolean - more `Update` objects can be fetch
*/
function processUpdate_reduce(fetchMoreDate, update)
{
return processUpdate(update) && fetchMoreDate
}
/**
* Process received Telegram `Update` objects and queue a new polling request
*
* @param {Array} data
*/
function gotUpdates(data)
{
inFlight = false
if(data.reduce(processUpdate_reduce, true)) setTimeout(self._read, 1000)
}
/**
* Emit an error when requesting updates and free `inFlight` flag
*
* @param {Error} error
*/
function onError(error)
{
inFlight = false
self.emit('error', error)
}
/**
* Request new updates. This will not work when using a webhook
*
* @private
*/
this._read = function()
{
var state = self._readableState
var limit = state.highWaterMark - state.length
if(inFlight || state.ended || !limit
|| polling === null || webhook !== undefined)
return
inFlight = true
polling = api.getUpdates({
offset: _updatesOffset,
limit: limit,
timeout: 0
})
.then(gotUpdates)
.catch(onError)
}
//
// Duplex API
//
/**
* Write a data message
*
* @param {Object} chunk
* @param {*} _ - ignored
* @param {Function} done
*
* @private
*/
this._write = function(chunk, _, done)
{
if(chunk == null || chunk == '') return done()
api.sendMessage(
{
chat_id: chat_id,
text: JSON.stringify(chunk)
})
.then(done.bind(null, null), done)
}
//
// Public API
//
/**
* Close the connection and stop emitting more data updates
*/
this.close = function()
{
if(webhook === null) return
if(webhook)
return api.setWebhook({certificate: certificate})
.then(closeWebhook, closeWebhook)
if(polling)
{
polling.then(end, end)
polling = null
}
}
}
inherits(TelegramLog, Duplex)
/**
* @event TelegramLog#data
*
* @type {string}
*/
/**
* @event TelegramLog#error
*
* @type {Error}
*/
module.exports = TelegramLog