This repository has been archived by the owner on Aug 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathbitcoinTrigger.js
346 lines (315 loc) · 10.7 KB
/
bitcoinTrigger.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
const BaseTrigger = require('./baseTrigger.js').BaseTrigger;
const Request = require('request');
const Coinbase = require('coinbase');
const fs = require('fs');
const util = require('util');
var BitcoinTrigger = function() {
BitcoinTrigger.super_.apply(this, arguments);
}
util.inherits(BitcoinTrigger, BaseTrigger);
const type = 'BitcoinTrigger';
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
var trigger = new BitcoinTrigger(type, name, chatBot, options);
trigger.options.dbFile = trigger.options.dbFile || chatBot.name + '/Coinbase.db';
trigger.options.clientID = trigger.options.clientID || undefined;
trigger.options.clientSecret = trigger.options.clientSecret || undefined;
trigger.options.redirectURI = trigger.options.redirectURI || undefined;
trigger.scope = 'wallet:accounts:read,wallet:sells:create,wallet:buys:create';
trigger.db = (function() { try { return JSON.parse(fs.readFileSync(trigger.options.dbFile)); } catch(e) { return {}}})();
trigger.options.clearcommand = trigger.options.clearcommand || '!clear';
trigger.options.authcommand = trigger.options.authcommand || '!auth';
trigger.options.saveTimer = trigger.options.saveTimer || 1000 * 60 * 5;
trigger.options.sellcommand = trigger.options.sellcommand || '!sell';
trigger.options.buycommand = trigger.options.buycommand || '!buy';
trigger.options.balancecommand = trigger.options.balancecommand || '!balance';
trigger.options.pricecommand = trigger.options.pricecommand || '!prices';
return trigger;
}
BitcoinTrigger.prototype._onLoad = function() {
const that = this;
const withName = this.chatBot.name + '/' + this.name + ': ';
if (this.options.saveTimer !== -1) {
setInterval(() => {
try {
fs.writeFile(that.options.dbFile, JSON.stringify(that.db), function (e) {
if (e) {
that.winston.error(withName + 'Could not write to db file ' + e);
return false;
}
else {
that.winston.debug(withName + 'Wrote to db file');
}
});
}
catch (e) {
that.winston.error(withName + 'Error: ' + e);
return false;
}
}, that.options.saveTimer);
return true;
}
if(!this.options.clientID || !this.options.clientSecret || !this.options.redirectURI || this.chatBot.options.disableWebserver === true) {
this.winston.error(withName + 'Must specify client ID and client Secret and redirect URI and webserver enabled!');
return false;
}
else {
return true;
}
}
BitcoinTrigger.prototype._respondToFriendMessage = function(userId, message) {
return this._respond(userId, userId, message);
}
BitcoinTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
return this._respond(roomId, chatterId, message);
}
BitcoinTrigger.prototype._respond = function(toId, userId, message) {
const that = this;
const withName = this.chatBot.name + '/' + this.name + ': ';
if(!this.db[userId]) {
this.db[userId] = {
steamID: userId,
accessToken: '',
refreshToken: '',
id: ''
}
}
var query = this._stripCommand(message, this.options.balancecommand);
if(query) {
this._getBalance(toId, userId);
}
query = this._stripCommand(message, this.options.authcommand);
if(query) {
this._authorize(userId, function(e, access, refresh) {
if(e) {
that.winston.error(withName + e);
}
else {
that.winston.silly(withName + 'Received accessToken and refreshToken');
that._sendMessageAfterDelay(userId, 'Your coinbase access token and refresh token have been received and written to disk.');
}
});
}
query = this._stripCommand(message, this.options.clearcommand);
if(query) {
this.db[userId] = null;
this._sendMessageAfterDelay(toId, 'Your database page has been cleared. You will need to reauthorize to use this trigger again.');
}
query = this._stripCommand(message, this.options.sellcommand);
if(query && query.params.length === 3) {
this._sell(toId, userId, query.params[1], query.params[2]);
}
query = this._stripCommand(message, this.options.buycommand);
if(query && query.params.length === 3) {
this._buy(toId, userId, query.params[1], query.params[2]);
}
query = this._stripCommand(message, this.options.pricecommand);
if(query) {
this._getPrices(toId, userId);
}
}
BitcoinTrigger.prototype._getPrices = function(toId, userId) {
const _db = this.db[userId];
const client = new Coinbase.Client({
"accessToken": _db.accessToken,
"refreshToken": _db.refreshToken
});
const withName = this.chatBot.name + '/' + this.name + ': ';
var sellPrice = '';
var buyPrice = '';
client.getBuyPrice({
"currency": "USD"
}, function(e, obj) {
buyPrice = obj.data.amount;
});
client.getSellPrice({
"currency": "USD"
}, function(e, obj) {
sellPrice = obj.data.amount;
});
setTimeout(() => {
this._sendMessageAfterDelay(toId, 'Sell price: ' + sellPrice + '. Buy price: ' + buyPrice);
}, 1000);
}
BitcoinTrigger.prototype._buy = function(toId, userId, amount, currency) {
const withName = this.chatBot.name + '/' + this.name + ': ';
const _db = this.db[userId];
const client = new Coinbase.Client({
"accessToken": _db.accessToken,
"refreshToken": _db.refreshToken
});
const account = new Coinbase.model.Account(client, {
"id": _db.id
});
const args = {
"amount": amount,
"currency": currency
};
account.buy(args, (e, xfer) => {
if(e) {
this.winston.error(withName + e.stack);
this._sendMessageAfterDelay(toId, `Error buying ${amount} ${currency} for user ${userId}: ${e.message}`);
}
else {
this._sendMessageAfterDelay(toId, `${userId} successfully bought ${amount} ${currency}!`);
this._sendMessageAfterDelay(userId, `Transfer ID is ${xfer.id}`);
}
});
}
BitcoinTrigger.prototype._sell = function(toId, userId, amount, currency) {
const that = this;
const withName = this.chatBot.name + '/' + this.name + ': ';
var _db = this.db[userId];
const client = new Coinbase.Client({
"accessToken": _db.accessToken,
"refreshToken": _db.refreshToken
});
const account = new Coinbase.model.Account(client, { "id": _db.id });
const args = {
"amount": amount,
"currency": currency
};
account.sell(args, function(e, xfer) {
if(e) {
that.winston.error(withName + e.stack);
that._sendMessageAfterDelay(toId, 'Error selling ' + amount + ' ' + currency + ' for user ' + userId + ': ' + e.message);
}
else {
that._sendMessageAfterDelay(toId, userId + ' successfully sold ' + amount + ' ' + currency + '!');
that._sendMessageAfterDelay(userId, 'Transfer ID is ' + xfer.id);
}
});
}
BitcoinTrigger.prototype._refreshToken = function(toId, userId) {
const that = this;
const withName = this.chatBot.name + '/' + this.name + ': ';
Request({
method: "POST",
uri: "https://coinbase.com/oauth/token" +
"?grant_type=refresh_token&redirect_uri=" +
that.options.redirectURI + "&client_id=" + that.options.clientID +
"&client_secret=" + that.options.clientSecret +
"&refresh_token=" + that.db[userId].refreshToken,
json: true,
followAllRedirects: true
}, function(e, response, body) {
if(e) {
that.winston.error(withName + e);
}
else {
that.db[userId].accessToken = body.access_token;
that._sendMessageAfterDelay(toId, 'Access token refreshed!');
}
});
}
BitcoinTrigger.prototype._getId = function(userId) {
var _db = this.db[userId];
const withName = this.chatBot.name + '/' + this.name + ': ';
const client = new Coinbase.Client({
"accessToken": _db.accessToken,
"refreshToken": _db.refreshToken
});
client.getAccounts({}, (e, accounts) => {
if(e) {
this.winston.error(withName + e.stack);
}
else {
accounts.forEach(account => {
_db.id = account.id;
});
}
})
}
BitcoinTrigger.prototype._authorize = function(userId, callback) {
const withName = this.chatBot.name + '/' + this.name + ': ';
this.express = this.chatBot.express;
var _url;
var _code;
var accessToken;
var refreshToken;
var uri = "https://coinbase.com/oauth/authorize" +
"?response_type=code&redirect_uri=" + encodeURI(this.options.redirectURI) +
"&client_id=" + this.options.clientID + '&scope=' + this.scope;
Request({
uri: uri,
json: true,
followAllRedirects: true
}, (e, response, body) => {
if(e) {
callback(e, null, null);
}
else {
this._sendMessageAfterDelay(userId, 'Please visit the following link and click "Authorize".\n\n' + uri);
var last = /^[^\/]*(?:\/[^\/]*){2}/g;
//console.log(that.options.redirectURI.match(last));
var getter = this.options.redirectURI.replace(last, '');
this.chatBot._addRouter(getter);
this.express.use(getter, (req, res, next) => {
_url = req.url;
_code = _url.match(/\?code=(.*)/i)[1];
res.send('<h1>Response received, you may close this window now.<h2>' + '<br><h4>Your code is ' + _code + '<h4><br>');
Request({
method: "POST",
uri: "https://coinbase.com/oauth/token?grant_type=authorization_code&code=" +
_code + "&client_id=" + this.options.clientID + "&client_secret=" +
this.options.clientSecret + "&redirect_uri=" + this.options.redirectURI,
json: true,
followAllRedirects: true
}, (e, response, body) => {
if(!body.access_token) {
callback(e, null, null);
}
else {
accessToken = body.access_token;
refreshToken = body.refresh_token;
this.db[userId].accessToken = accessToken;
this.db[userId].refreshToken = refreshToken;
this._getId(userId);
callback(null, accessToken, refreshToken);
}
});
});
}
});
}
BitcoinTrigger.prototype._getBalance = function(toId, userId) {
const that = this;
const withName = this.chatBot.name + '/' + this.name + ': ';
if(!that.db[userId].accessToken || !that.db[userId].refreshToken) {
this._sendMessageAfterDelay(userId, 'Please use ' + this.options.authcommand + ' to authorize before using this command.');
return false;
}
else {
var _db = that.db[userId];
var client = new Coinbase.Client({
"accessToken": _db.accessToken,
"refreshToken": _db.refreshToken
});
client.getAccount(_db.id, (e, account) => {
if(e) {
if(e.message = "[ExpiredToken: The access token expired]") {
this._refreshToken(toId, userId);
this._sendMessageAfterDelay(toId, 'Access token expired, refreshing. Please try again in a few seconds.');
this.winston.warn(withName + 'Refreshing access token');
}
else {
this.winston.error(e.stack);
this._sendMessageAfterDelay(userId, e.message);
console.log(e.message);
}
}
else {
this._sendMessageAfterDelay(toId, 'The balance for ' + this.chatBot._userString(userId) + ' is ' + account.balance.amount + ' ' + account.balance.currency);
}
})
}
}
BitcoinTrigger.prototype._stripCommand = function(message, command) {
if (command && message && message.toLowerCase().indexOf(command.toLowerCase()) === 0) {
return {
message: message,
params: message.split(" ")
};
}
return null;
}