/
index.js
100 lines (88 loc) · 3.14 KB
/
index.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
const fs = require('fs');
const mastodon = require('./core/mastodon');
const { execFile } = require('child_process');
const yaml = require('node-yaml');
const config = yaml.readSync('./config.yml');
const mast = new mastodon.Client(config.mastodon);
const prefix = config.prefix === undefined ? ':' : config.prefix;
const re_prefix = RegExp('^' + prefix);
const ignore_unknown_command =
config.ignore_unknown_command === undefined ? false : config.ignore_unknown_command;
// see ./bin/(executable)
process.env.PATH = `./bin:${process.env.PATH}`
config.commands = config.commands.concat(fs.readdirSync('./bin'))
function is_allow(command) {
return (config.commands.indexOf(command) != -1);
}
// before prefix-check
function trim(text) {
text = text.replace(/<[^>]*>/g, '');
text = text.replace(/[ \.]*@ampeloss[^ ]* */g, '');
text = text.replace(/#.*$/, '');
return text;
}
function parse(line) {
line = line.replace(re_prefix, '');
var words = line.split(' ').filter((x) => x != '');
return words;
}
function run(line, cont) {
var words = parse(line);
if (is_allow(words[0])) {
console.log('RUN', words[0], words.slice(1));
execFile(words[0], words.slice(1), (error, stdout, stderr) => {
if (error) {
console.log(`Error: ${error}`);
cont(`Error: ${error}`);
} else {
var text = stdout.trim();
if (stderr) {
text += '\nStderr: ' + stderr.trim();
}
cont(text);
}
});
} else {
console.log(`command not found: ${words[0]}`);
if (! ignore_unknown_command) {
cont(`command not found: ${words[0]}`);
}
}
}
function broadcast(username, id) {
return (result) => {
if (/^RT */.test(result)) {
const url_or_id = result.replace(/^RT */, '');
mast.retweet(url_or_id);
} else if (/^IMAGE */.test(result)) {
const lines = result.split('\n');
const paths = lines[0].split(' ').slice(1);
const text = lines.slice(1).join('\n');
mast.reply_with_medias(username, id, text, paths);
} else {
mast.reply(username, id, result);
}
}
}
mastodon.stream((event) => {
if (event.event_type == 'update') {
if (event.data && event.data.account && event.data.account.acct) { // mastodon
var data = event.data;
var username = data.account.acct;
var id = data.id;
var text = trim(data.content);
console.log(event.event_type, username, text);
if (re_prefix.test(text)) {
run(text, broadcast(username, id));
}
} else if (event.data && event.data.icon && event.data.screenname) { // twitter
var username = null;
var id = null;
var text = trim(event.data.text);
console.log(event.event_type, username, text);
if (re_prefix.test(text)) {
run(text, broadcast(username, id));
}
}
}
}, (config.mastodon.port ? config.mastodon.port : 8080));