File: api.js

package info (click to toggle)
node-telegram-bot-api 2.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 2,964 kB
  • sloc: javascript: 1,333; makefile: 2
file content (276 lines) | stat: -rw-r--r-- 9,540 bytes parent folder | download
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
const EventEmitter = require('events')
const debug = require('debug')('telegram-bot-api:api')
const axios = require('axios')
const stream = require('stream')

class Api extends EventEmitter {

    /**
     * API parameters:
     *      token                      access token for bot
     *      baseUrl                    Base URL for telegram API
     *      http_proxy                 proxy settings (optional)
     *          host                   proxy host
     *          port                   proxy port
     *          user                   username for proxy
     *          password               password for proxy
     *          https                  true/false
     */
    constructor(parameters) {
        super()

        // Default parameters
        this._token = undefined
        this._baseUrl = 'https://api.telegram.org'
        this._messageProvider = undefined
        this._proxy = undefined

        // Apply configuration
        this._applyParameters(parameters ? parameters : {})
        this._validateParameters()

        // Default request settings
        this._request = this._fakeRequest

        // Register Api calls
        this._registerApiCall('getMe')
        this._registerApiCall('sendMessage')
        this._registerApiCall('forwardMessage')
        this._registerApiCall('sendPhoto')
        this._registerApiCall('sendAudio')
        this._registerApiCall('sendDocument')
        this._registerApiCall('sendVideo')
        this._registerApiCall('sendAnimation')
        this._registerApiCall('sendVoice')
        this._registerApiCall('sendVideoNote')
        this._registerApiCall('sendMediaGroup')
        this._registerApiCall('sendLocation')
        this._registerApiCall('editMessageLiveLocation')
        this._registerApiCall('stopMessageLiveLocation')
        this._registerApiCall('sendVenue')
        this._registerApiCall('sendContact')
        this._registerApiCall('sendPoll')
        this._registerApiCall('sendDice')
        this._registerApiCall('sendChatAction')
        this._registerApiCall('getUserProfilePhotos')
        this._registerApiCall('getFile')
        this._registerApiCall('kickChatMember')
        this._registerApiCall('unbanChatMember')
        this._registerApiCall('restrictChatMember')
        this._registerApiCall('promoteChatMember')
        this._registerApiCall('setChatAdministratorCustomTitle')
        this._registerApiCall('setChatPermissions')
        this._registerApiCall('exportChatInviteLink')
        this._registerApiCall('setChatPhoto')
        this._registerApiCall('deleteChatPhoto')
        this._registerApiCall('setChatTitle')
        this._registerApiCall('setChatDescription')
        this._registerApiCall('pinChatMessage')
        this._registerApiCall('unpinChatMessage')
        this._registerApiCall('leaveChat')
        this._registerApiCall('getChat')
        this._registerApiCall('getChatAdministrators')
        this._registerApiCall('getChatMembersCount')
        this._registerApiCall('getChatMember')
        this._registerApiCall('setChatStickerSet')
        this._registerApiCall('deleteChatStickerSet')
        this._registerApiCall('answerCallbackQuery')
        this._registerApiCall('setMyCommands')
        this._registerApiCall('getMyCommands')

        // Updating messages
        this._registerApiCall('editMessageText')
        this._registerApiCall('editMessageCaption')
        this._registerApiCall('editMessageMedia')
        this._registerApiCall('editMessageReplyMarkup')
        this._registerApiCall('stopPoll')
        this._registerApiCall('deleteMessage')

        // Stickers
        this._registerApiCall('sendSticker')
        this._registerApiCall('getStickerSet')
        this._registerApiCall('uploadStickerFile')
        this._registerApiCall('createNewStickerSet')
        this._registerApiCall('addStickerToSet')
        this._registerApiCall('setStickerPositionInSet')
        this._registerApiCall('deleteStickerFromSet')
        this._registerApiCall('setStickerSetThumb')

        // Inline mode
        this._registerApiCall('answerInlineQuery')

        // Payments
        this._registerApiCall('sendInvoice')
        this._registerApiCall('answerShippingQuery')
        this._registerApiCall('answerPreCheckoutQuery')

        // Passport
        this._registerApiCall('setPassportDataErrors')

        // Games
        this._registerApiCall('sendGame')
        this._registerApiCall('setGameScore')
        this._registerApiCall('getGameHighScores')
    }

    _fakeRequest(parameters, f) {
	if (parameters.method == "GET") {
	    axios.get(parameters.uri, {timeout: parameters.timeout})
	    .then(function (body) {
		f(null, body.request.res, JSON.stringify(body.data));
	    })
	    .catch(function(err){
		f(err, null, null);
	    })
	} else if (parameters.method == "POST") {
	    axios.post(parameters.uri, parameters.formData, {timeout: parameters.timeout})
	    .then(function (body) {
		f(null, body.request.res, JSON.stringify(body.data));
	    })
	    .catch(function(err){
		f(err, null, null);
	    })
	}
    }

    _applyParameters(parameters) {
        if (parameters.token) {
            this._token = parameters.token
            debug('set token %s', this._token)
        }

        if (parameters.baseUrl) {
            this._baseUrl = parameters.baseUrl
            debug('set baseUrl %s', this._baseUrl)
        }

        if (parameters.http_proxy) {
            if (parameters.http_proxy.https === true) {
                this._proxy = 'https://'
            } else {
                this._proxy = 'http://'
            }

            if (parameters.http_proxy.user !== undefined &&
                parameters.http_proxy.password !== undefined) {
                this._proxy += parameters.http_proxy.user + ':' + parameters.http_proxy.password + '@'
            }

            this._proxy += parameters.http_proxy.host + ':' + parameters.http_proxy.port
        }
    }

    _validateParameters() {
        if (this._token == undefined) {
            throw new Error('[telegram-bot-api]: token is mandatory')
        }
    }

    _getBaseUrl() {
        return this._baseUrl + '/bot' + this._token + '/'
    }

    _registerApiCall(name) {
        this[name] = (params) => {
            return this._call.call(this, name, params)
        }
    }

    _call(methodName, params, config) {
        return new Promise((resolve, reject) => {

            for (const key in params) {
                if (!(params[key] instanceof stream.Readable) &&
                    "string" != typeof params[key] &&
                    "boolean" != typeof params[key] &&
                    "number" != typeof params[key]) {
                    params[key] = JSON.stringify(params[key])
                }
            }

            debug('Do (%s) with params => %o', methodName, params)

            const timeout = config && config.timeout ? config.timeout : 2000
            this._request({
                method: 'POST',
                uri: this._getBaseUrl() + methodName,
                formData: params ? params : null,
                timeout: timeout
            }, (err, response, body) => {
                if (err) {
                    debug('Telegram error: %o', err)
                    return reject(err)
                }

                try {
                    const json = JSON.parse(body)

                    if (json.ok == undefined &&
                        response.statusCode != 200) {
                        debug('Telegram Api returned HTTP code = %s', response.statusCode)
                        return reject({
                            code: response.statusCode,
                            body: json
                        })
                    }

                    if (json.ok == false) {
                        debug('Telegram Api returned ok == false')
                        return reject({
                            code: json.error_code !== undefined ? json.error_code : 'Not set by API',
                            description: json.description !== undefined ? json.description : 'Not set by API',
                            body: json
                        })
                    }

                    resolve(json.result)
                }
                catch(err) {
                    debug('Failed to parse response from Telegram Api: %o')
                    return reject({
                        code: 0
                    })
                }
            })
        })
    }

    start() {
        return new Promise((resolve, reject) => {
            if (!this._messageProvider) {
                return reject(new Error('Message provider is not set'))
            }

            this._messageProvider.start(this)
            .then(resolve)
            .catch(reject)
        })
    }

    stop() {
        return new Promise((resolve, reject) => {
            if (!this._messageProvider) {
                return reject(new Error('Message provider is not set'))
            }

            this._messageProvider.stop()
            .then(resolve)
            .catch(reject)
        })
    }

    setMessageProvider(provider) {
        if (!(provider instanceof require('./providers/update')) &&
            !(provider instanceof require('./providers/webhook'))) {
            throw new Error('[telegram-bot-api]: Message provider is incorrect')
        }

        this._messageProvider = provider
    }

    _onUpdate(update) {
        this.emit('update', update)
    }
}

module.exports = Api