-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
435 lines (419 loc) · 16.7 KB
/
server.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
const Discord = require('discord.js');
const client = new Discord.Client();
const grpc = require('grpc');
var sys = require('util')
var exec = require('child_process').exec;
var fs = require('fs');
//var matchRecursive = require("match-recursive");
require('dotenv').config();
const {RNode, RHOCore, logged} = require('rchain-api');
let myNode;
const Tail = require('tail').Tail;
const tail = new Tail("/home/rchain/rnode.log");
const keybase = new Tail("/tmp/keybase.log");
var KEYBASETO;
keybase.on("line", function(data) {
if ( KEYBASETO ) {
let event = JSON.parse(data)
if ( event.type == 'chat' && event.msg.content.type == 'text') {
text = "keybase: "+event.msg.channel.name+': '+event.msg.sender.username+': '+event.msg.content.text.body
KEYBASETO.send(text);
}
}
});
var debug = 3;
var currentMessage;
var lastMessage;
tail.on("line", function(data) {
if ( data.match(/[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9] .*INFO/)) {return};
let hide = 0;
if ( data.match(/^[0-9]|^true|^false|^Unforgeable|^bundle|^@|^Nil$|^\(|^".*"|^[0-9.][0-9.]*$|^Set|^\[|^\{|^\(|^`|^Syntax Error/)) { // if stdout data
data = data.replace(/Unforgeable\(0x([0-9a-z]{6})[^)]*\)/g,'<$1..>');
console.log("log: "+data);
if ( data.match(/\["#define", "\$/) ) {
console.log("found a #define, name, value");
hide = 0;
let matches = data.match(/#define", "([^"]*)",(.*)\]/);
exec( "echo '#define "+matches[1]+' '+matches[2]+"' >>global.h");
}
else if ( data.match(/\["#define \$/) ) {
console.log("found a #define");
hide = 0;
let matches = data.match(/(#define[^"]*)", (.*)\]/);
exec( "echo '"+matches[1]+' '+matches[2]+"' >>global.h");
}
else if ( data.match(/^\["event:",/)) {
let match = data.match(/^\["event:", "at:", "([^"]*)", "([0-9]*)"\]/);
if ( match ) {
console.log("echo ./trigger.sh "+match[2]+"|at "+match[1]+" >/tmp/at.out 2>&1");
exec("echo ./trigger.sh "+match[2]+"|at "+match[1]+" >/tmp/at.out",
function(err, stdout, stderr) {
if ( ! err ) {
debug > 0 ? currentMessage.channel.send(stderr):0;
}
});
} else {
match = data.match(/^\["event:", "trigger:", "([0-9]*)"\]/);
exec("echo ./trigger.sh "+match[2]+" >/tmp/trigger.out",
function(err, stdout, stderr) {
if ( ! err ) {
currentMessage.channel.send("error:"+stderr);
}
});
}
} else {
}
hide = data.match(/^"locker.get\(...\)"|^\(?\["debug:|^Error: .*: Unrecognized interpreter errorError: coop.rchain.rholang.interpreter.errors$LexerError: Illegal Character <$>/) ? 2:hide;
if ( currentMessage ) {
hide<=debug ? currentMessage.channel.send(data):0;
} else if ( lastMessage ) { //TODO this sould report to a user by DB matching reportto:, useris
hide<=debug ? lastMessage.channel.send(data):0;
currentMessage = lastMessage
}
}
});
//tail.unwatch()
tail.on("error", function(error) {
console.log('ERROR: ', error);
});
function rhoformat(rho) {
if ( ! rho.match(/\n./) ) { // add new lines to code without any
rho = rho.replace(/^ */,"")
rho = rho.replace(/\{\s/g,"{\n")
rho = rho.replace(/\s\} */g,"\n}")
rho = rho.replace(/\| */g,"|\n")
}
let rholang2 = ""; let indent = ""; let last = "";
for (const c of rho) { // cpp removes whitespace so add back indenting
if ( c == "}" ) indent = indent.substring(2);
if (last.match(/\n/)) rholang2 += indent;
if ( c == '{' ) indent += " ";
rholang2 += c;
last = c;
}
return rholang2 += last;
}
// 'client.on('message')' commands are triggered when the
// specified message is read in a text channel that the bot is in.
client.on('ready', () => {
myNode = RNode(grpc, {host: "rhobot.net", port: 40401});
console.log(`Logged in as{host: "rhobot.net", port: 40401} ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
console.log(msg);
console.log(msg.attachment);
msg.reply('Pong!');
} else if (msg.content == 'keybase bridge start' ) {
keybase.watch(); // turn on reporting log output as msg.reply
KEYBASETO = msg.channel;
msg.channel.send('keybase bridge started.');
} else if (msg.content === 'keybase bridge stop') {
keybase.unwatch(); // turn on reporting log output as msg.reply
}
});
client.on('message', msg => {
if ( msg.content.includes("479702072468439050") &&
msg.author.username != "RHO-bot" &&
"shadaloopropagandadepartment" == msg.channel.name ) {
let messages = [
"ParickM does not care",
"Sorry I don't understand",
"Sorry I don't understand",
"Sorry I don't understand",
"this does not surprise me.",
"ParickM says you are fired.",
"PatrickM sometimes cares.",
"I dont understand the question but the answer is periwinkle blue.",
"PatrickM wants you boomer ass.",
"PatrickM doesn't normally roll up on that." ,
"The truth is in the DNA, as PatricM says.",
"PatrickM DOES NOT CARE SO EMOTIONALLY.",
"Do you think I am a human being?"
];
var message = messages[Math.floor(Math.random() * messages.length)];
msg.reply(message)
}
})
client.on('message', msg => {
if ( msg.content == -1 ) { console.log("ug"); /* console.log(msg)*/ } else {
console.log(msg.content);
console.log("message: "+msg.channel.name+": "+msg.author.username+": "+
new Date().toISOString()+" "+msg.content.replace(/\n/g,'\\n'));
let content = msg.content;
let repeat = true;
let retry = 0;
while (repeat && retry < 2) {
repeat = false;
if (content.match(/^```rholang.*/)) {
content = "rholang:"+content.substring(10,content.length-4)
}
if (content.match(/^```eval.*/)) {
content = "eval:"+content.substring(7,content.length-4)
}
if (content.match(/^```.*/)) {
content = content.substring(/\r|\n/.exec(content).index+1,content.length-4)
}
if (!msg.author.bot && content.match(/^rholang/i)) { // not working
let dir;
const randid = Math.random().toString().substring(2);
var auxmsg = "";
if (content.match(/^rholang:/i)) {
console.log(content);
let rholang = '@"'+ msg.channel.name+randid+'"!('+content.substring(8)+')';
console.log(rholang);
var deployData = {term: rholang,
timestamp: new Date().valueOf()};
myNode.doDeploy(deployData).then(result => {
if(!result.success) {
// msg.reply("Deploy error: "+result.message);
console.log(result);
throw(result);
}
return myNode.createBlock();
}).then(result => {
if(!result.success) {
// msg.reply("createBlock error: "+result.message);
throw(result);
}
auxmsg = result.message;
console.log(result.message);
console.log("msg.channel.name is: ", msg.channel.name+randid);
return myNode.listenForDataAtName(msg.channel.name+randid)
}).then(blockResults => {
console.log("blocks received: " + blockResults.length)
// TODO: If we got no blocks back, fail gracefully.
var lastBlock = blockResults.pop()
console.log("block results are:");
console.log(JSON.stringify(blockResults));
console.log("number of blocks received: ", blockResults.length);
var lastDatum = lastBlock.postBlockData.slice(-1).pop()
if (lastDatum) {
msg.reply(auxmsg+"\n"+RHOCore.toRholang(lastDatum))
}
else {
msg.reply(`No data on channel ${msg.channel.name+randid}`);
}
}).catch(oops => { console.log(oops);
/* if (!auxmsg) */ msg.reply(auxmsg+"\n"+oops.message + " (See the log: https://rhobot.net/rnode-log)");
});
} else {
var n = Math.floor(Math.random() * 3);
var answers = ["RHOlang is the language of RChain. Run a rholang program by typing:\neval: <your program>",
"RHOlang is the language of the mobile asyncronous communicating process calculus.",
"See the rholang tutorial at https://developer.rchain.coop/tutorial"];
msg.reply(answers[n]);
}
}
else if (content.match(/^debug: /)) {
debug = parseInt(content.substring(content.match(/ /).index));
debug ? msg.channel.send("Debug level "+debug+" on."): msg.channel.send("Debugging off.");
}
else if (content.match(/^define:/)) {
if (! content.match(/^define:\s*\$/) ) {
msg.reply("error: start macro names with a dollar sign $");
} else {
let command = "echo '#define "+content.substring(7).replace(/(?:\r\n|\r|\n)/, ' ').replace(/(?:\r\n|\r|\n)/g, '"~~"').replace("'","'\"'\"'")+"' >>global.h";
exec(command);
msg.reply("defined "+content.substring(7,(content+"\n").indexOf("\n")));
}
}
else if (content.match(/^find:/i)) {
let search = content.substring(6);
console.log("search "+search);
if (search.match(/^$/))
search = ".*";
let command = "" +
"sed -n 's/^#define *//;s/, /,/g;s/( /(/g;s/ )/)/g;s/ .*//;"+
"/locker_nonce/d;/"+search+"/Ip' global.h|sort -u";
console.log(command)
exec(command,
function(err, stdout, stderr) {
if ( ! err ) {
msg.reply(":\n"+stdout.substring(0,1900));
} else {
msg.reply("error:"+stderr);
}
})
}
else if (content.match(/^echo:/i)) {
// if a command colon, make is a function call
if (content.match(/^echo: *[a-zA-Z0-9_-]*:(\s|$)/) && !msg.author.bot) {
let match = content.match(/^echo: *([^:]*): *(.*)/);
content = "echo: $"+match[1]+'('+match[2]+")";
}
console.log(content);
let rholang = "" +
"echo '"+content.substring(5).replace("'","'\"'\"'")+"'|"+
"cat global.h end.h - |cpp 2>/tmp/cpp-error|tee cpp-out|"+
"sed -n '/^#/d;/^_end_$/,$p'|tail +2|sed 's/\"~~\" */\\\n/g;"+
"/.\\{1900,\\}/s/\\(.{1900\\}\\).*/\\1... too long for discord/'"; // TODO doesnt work
//console.log(rholang)
exec(rholang,
function(err, stdout, stderr) {
if ( ! err ) {
let rholang2 = rhoformat(stdout);
msg.reply("```scala\n"+rholang2+"\n```");
} else {
msg.reply("error:"+stderr);
}
})
}
else if (content.match(/^show:/i)) {
console.log(content);
let rholang = "" +
"grep -i '^#define[ \\$]*"+content.substring(6).replace("'","'\"'\"'")+"[ \\(]' global.h|"+
"tail -1|sed 's/\"~~\" */\\n/g'";
console.log(rholang);
exec(rholang,
function(err, stdout, stderr) {
if ( ! err ) {
let rho = stdout.substring(7);
console.log(rho);
rho= rhoformat(rho.replace(/\) *\(/,") (").replace(/^ */," "));
console.log(rho);
if ( ! rho.match(/\n./) ) { // add new lines to code without any
rho = rho.replace(/([^ ]) /g,"$1\n ")
}
msg.reply("```scala\n-> define: "+rho+"\n```");
} else {
msg.reply("error:"+stderr);
}
})
}
else if (content.match(/^eval:\s\s*|^deploy:|^explore:/i)) {
if (content.match(/^deploy: *[a-zA-Z0-9_-]*:(\s|$)/) && !msg.author.bot) {
let match = content.match(/^deploy: *([^:]*): *(.*)/);
content = "deploy: $"+match[1]+'('+match[2]+")";
}
if (content.match(/^explore: *[a-zA-Z0-9_-]*:(\s|$)/) && !msg.author.bot) {
let match = content.match(/^explore: *([^:]*): *(.*)/);
content = "explore: $"+match[1]+'('+match[2]+")";
}
currentMessage = msg;
tail.watch(); // turn on reporting log output as msg.reply
const author = msg.author.username;
let rholang = '#define $myprivkey "'+msg.author.id.substring(10)+"\"\n"+
'#define $mypubkey "dead'+msg.author.id.substring(10)+"\"\n"+
'#define $myusername "'+msg.author.username.replace(" ","_")+"\"\n"+
'#define $_messageid "'+msg.id+"\"\n"+
'#define $_authorid "'+msg.author.id+"\"\n"+
content.substring(content.indexOf(":")+1)+"\n";
console.log(rholang);
//let rholang = content.substring(5);
fs.writeFile("/tmp/"+author+".rhox", rholang, function(err) {
if(err) {
return console.log(err);
}
let doit="curl -d @/tmp/"+author+".rho http://localhost:40403/api/explore-deploy 2>&1";
if (content.match(/^deploy:/)) {
doit="set 2>&1;./deploy /tmp/"+author+".rho;sleep 5;rnode --grpc-port 40402 propose"
} else if (content.match(/^eval:/)) {
doit="rnode --grpc-port 40402 eval '/tmp/"+author+".rho' 2>&1"
}
console.log("The file was saved!");
let bash = "cat global.h '/tmp/"+author+".rhox' |cpp 2>cpperrors|"+
"sed 's/\\%\\%\"\\([^\"]*\\)\"/\\1/g;s/\"~~\"/\\n/g'|"+
"cat global.h end.h -|cpp 2>cpperrors2|sed -n '/^#/d;/^_end_$/,$p'|tee lasteval|"+
"tail +2 >'/tmp/"+author+".rho';"+
doit+"|"+
"grep -i error";
console.log(bash);
dir = exec(bash,
//dir = exec(" rnode eval /tmp/"+author+".rho|sed '2,3d;/^Storage Contents:/{x;q}'",
function(err, stdout, stderr) {
if ( ! err ) {
if ( stdout.match(/Illegal Character \<\$\> /) ) {
fs.readFile("/tmp/"+author+".rho", function(err, rholang) {
if(err) {
return console.log(err);
} else {
msg.reply((""+rholang).match(/(\$[a-zA-Z_0-9]*)/)[1]+" undefined or wrong number of args.");
}
})
}
else if ( stdout.match(/^Deployment cost: /) ) {
msg.reply(stdout);
currentMessage=null;
}
else if ( stdout.match(/^Error: /) ) {
msg.reply(stdout.match(/..........: (.*)/)[1]);
}
else if ( debug > 0 ) msg.reply(stdout.substring(0,stdout.length-0));
} else {
msg.reply(stderr);
}
//tail.unwatch();
});
});
}
else if (content.match(/^deploy:/i)) {
const author = msg.author.username;
let rholang = content.substring(8);
dir = exec(" rnode deploy --phlo-limit 10000000000 --private-key 2f0d7408d28f39defd6eb5189bb2516e8088829548ca4f04a8ef5dfae013287a --phlo-price 1 /tmp/"+author+".rho",
function(err, stdout, stderr) {
if (err) {
msg.reply(stderr);
// should have err.code here?
}
console.log(stdout);
msg.reply(stdout + " (See the log: https://rhobot.net/rnode-log)");
});
}
else if (content.match(/^propose:/i)) {
console.log(content);
dir = exec("rnode --grpc-port 40402 propose 2>&1", function(err, stdout, stderr) {
if (err) {
// should have err.code here?
}
console.log(stdout);
msg.reply(stdout + " (See the log: https://rhobot.net/rnode-log)");
});
}
else if (content.match(/^who am i\?/i)) {
//var deployData = {term: ,
// timestamp: new Date().valueOf()};
msg.reply(`HELLO ${msg.author.username} id = ${msg.author.id}`);
}
else if (content.match(/^[a-z][a-zA-Z0-9_-]*:(\s|$)/) && !msg.author.bot) {
const matches = content.match(/(^[^:]*): (.*)/);
if (matches) {
content = "eval: $"+matches[1]+'('+matches[2]+')';
} else {
content = "eval: $"+content.match(/(^[^:]*)/)[1];
}
repeat = true; retry = retry + 1;
} else {
tail.unwatch()
}
}
}});
client.on('guildMemberAdd', member => {
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(ch => ch.name === 'general');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
let messages = [
"Hello!",
"It’s nice to meet you.",
"It’s a pleasure to meet you.",
"Hi!" ,
"Welcome! How might we cooperat",
"What’s new?",
"It’s good to see you." ,
"G’day!" ,
"Howdy!" ,
"Welcome to the server"
];
var message = messages[Math.floor(Math.random() * messages.length)];
console.log(`New member ${member} ${message}`);
// Send the message, mentioning the member
channel.send(`${message}. ${member}. Welcome to the cooperation laboratory.`);
});
client.login(process.env.TOKEN);
//fs.writeFile(""+author+".rho", rholang, function(err) {
// if(err) {
// return console.log(err);
// }
// console.log("The file was saved!");
// });