-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTbot.js
More file actions
109 lines (91 loc) · 3.21 KB
/
Tbot.js
File metadata and controls
109 lines (91 loc) · 3.21 KB
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
var request = require('request');
function Tbot(config, parsingFunction, STRINGS){
var self = this;
this.URL = config.url;
this.TOKEN = config.token;
this.TIMEOUT = config.timeout;
this.QUIET = config.isQuiet;
this.STRINGS = STRINGS;
this._updatesOffset = 0;
this._chatId = '';
//function for parsing the message
this.parse = parsingFunction;
//state object for storing state
this.state = {};
// Request to Telegram API
//params:
//method - one of Telegram's Bot API methods
//chatIdStr - chatId as '?chat_id=' or offset as '?offset='
//param - any other params eg. '&text='
//callback - callback function
this.sendRequest = function(method, chatIdStr, param, callback){
var cb = callback || function(body){ if(!self.QUIET) console.log(body); };
var req = self.URL + self.TOKEN + '/' + method + chatIdStr + param;
request({
method: 'GET',
url: req,
json: true
}, function(err, res, body){
try{
if(!err && res.statusCode == 200){
if(body.ok){
cb(body);
}
else{
throw new Error('body not ok');
}
}
else{
if(err){
throw new Error(err.toString());
}
else{
throw new Error('response code is ' + res.statusCode);
}
}
}
catch(e){
console.log('Error: ' + e.message);
}
});
};
// Sends a message for each text message received
//params:
//body - array of Update objects
this.processUpdates = function(body){
for (var i = 0; i < body.result.length; i++) {
var update = body.result[i];
if(update.update_id >= self._updatesOffset){
self._updatesOffset = update.update_id + 1;
}
if(update.hasOwnProperty('message')){
self._chatId = update.message.chat.id;
if(update.message.hasOwnProperty('text')){
var reply = self.parse(update.message);
if(reply !== '' || typeof reply !=='undefined'){
self.sendMessage(reply);
}
else{
//no reply to send
}
}
else{
throw new Error('no text');
}
}
else{
//no message
}
}
};
}
Tbot.prototype.getMe = function(callback){
this.sendRequest('getMe', '', '', callback);
};
Tbot.prototype.getUpdates = function(){
this.sendRequest('getUpdates', '', '?offset='+this._updatesOffset, this.processUpdates);
};
Tbot.prototype.sendMessage = function(msg){
this.sendRequest('sendMessage', '?chat_id='+this._chatId, '&text='+msg);
};
module.exports = Tbot;