-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtelegram.js
186 lines (146 loc) · 4.98 KB
/
telegram.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
// SendError is used inside all of the required modules
// TODO: This should be fixed
exports.SendError = SendError = function (error) {
let options = {
body: {
text: error,
chat_id: '382232505',
},
json: true
}
request.post(url + sendMessageCmd, options);
}
const { TraderBirdBot } = require('./traderbird');
const { Channel } = require('./db');
const { logger } = require('./logger');
const EventEmitter = require('events');
const _ = require('underscore');
const request = require('request-promise-native');
const url = `https://api.telegram.org/bot${process.env.TELEGRAM_TOKEN}/`;
const sendMessageCmd = 'sendMessage';
const getUpdatesCmd = 'getUpdates';
let channelMap = {};
class TelegramBot extends EventEmitter {
constructor(chatid) {
super();
this.timeout = 0;
this.chatid = chatid || process.env.TELEGRAM_CHATID;
this.tbb = new TraderBirdBot(this.chatid);
this.tbb.loadData();
this.tbb.on('tweet', this.broadcastMessage.bind(this));
this.on('add', this.tbb.addAccount.bind(this.tbb));
this.on('remove', this.tbb.removeAccount.bind(this.tbb));
this.on('addfilter', this.tbb.addFilter.bind(this.tbb));
this.on('removefilter', this.tbb.removeFilter.bind(this.tbb));
this.on('following', this.tbb.getAccounts.bind(this.tbb));
this.on('filters', this.tbb.getFilters.bind(this.tbb));
this.on('size', this.tbb.setSize.bind(this.tbb));
this.on('quote', this.tbb.setQuote.bind(this.tbb));
this.on('buy', this.tbb.placeBuyOrder.bind(this.tbb));
this.on('sell', this.tbb.placeSellOrder.bind(this.tbb));
this.on('price', this.tbb.getPrice.bind(this.tbb));
this.on('addupdate', this.tbb.addUpdate.bind(this.tbb));
this.on('removeupdate', this.tbb.removeUpdate.bind(this.tbb));
this.on('stopupdates', this.tbb.stopUpdates.bind(this.tbb));
}
broadcastMessage(message) {
let text = message.text;
let keyboard = message.inline_keyboard;
let options = { body: { parse_mode: 'HTML' }};
if (keyboard) {
options.body.reply_markup = {
inline_keyboard: keyboard
}
}
this.sendMessage(text, options);
}
processCommand(command, data) {
this.emit(command, data, this.sendMessage.bind(this));
}
sendMessage(text, options={}) {
if (!options.body) {
options.body = {}
}
options.body.text = text;
options.body.chat_id = this.chatid;
options.json = true;
request.post(url + sendMessageCmd, options);
}
}
Channel.findAll({ attributes: ['chatid']})
.then((channels) => {
if (channels.length) {
channels.forEach((channel) => (channelMap[channel.chatid] = new TelegramBot(channel.chatid)))
} else {
let bot = new TelegramBot();
channels[bot.chatid] = bot
}
});
let offset = 0;
async function getUpdates() {
const options = {
body: {
offset: offset,
timeout: 10,
},
json: true
}
try {
let { result } = await request.post(url + getUpdatesCmd, options)
if (result.length) {
result.forEach((item) => {
if (item.callback_query) {
let cb = item.callback_query.data;
let match = /(buy|sell)(.*)/.exec(cb);
if (!match) {
return;
}
let [res, cmd, data] = match;
let chatid = item.callback_query.message.chat.id;
channelMap[chatid].processCommand(cmd, data);
}
if (!item.message) {
return
}
let chatid = item.message.chat.id;
if (!channelMap[chatid]) {
channelMap[chatid] = new TelegramBot(chatid)
Channel.findOrCreate({ chatid: chatid, defaults: { chatid: chatid }})
}
let match = /\/(addupdate|removeupdate|stopupdates|addfilter|add|removefilter|following|remove|filters|size|quote|price)\s*@*(.*)/.exec(item.message.text);
if (!match) {
return;
}
let [res, cmd, data] = match;
let i = data.indexOf('@TraderbirdBot');
if (i >= 0) {
data = data.slice(0, i) + data.slice(i + '@TraderbirdBot '.length, data.length);
}
channelMap[chatid].processCommand(cmd, data);
});
offset = result[result.length - 1].update_id + 1;
}
} catch(errs) {
if (!(errs instanceof Array)) {
errs = [errs]
}
for (let err of errs) {
if (err.message.includes('Bad Gateway') || err.message.includes('Timed out')) {
logger.error(`Telegram Network Error: ${err.message}`);
SendError(`Telegram Network Error: ${err.message}`)
this.timeout = 1000;
} else if (err.message.includes('Unauthorized')) {
logger.error(`Telegram Authorization Error: ${err.message}`);
SendError(`Telegram Authorization Error: ${err.message}`)
} else {
logger.error(`Unknown Telegram Error: ${err.message}`);
SendError(`Unknown Telegram Error: ${err.message}`)
}
}
} finally {
setTimeout(() => {
this.timeout = 0;
getUpdates();
}, this.timeout); }
}
getUpdates();