-
Notifications
You must be signed in to change notification settings - Fork 4
/
debug.js
executable file
·91 lines (80 loc) · 2.4 KB
/
debug.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
#!/usr/bin/env node
/**
* Debug REPL for slacker. Allows you to execute slacker actions in real
* time for immediate testing feedback
*/
var rl,
readline = require("readline"),
_ = require("lodash"),
bot = require("./bot")
parse = require("./library/parse")
bot.setup(repl)
/**
* Set up the readline interface and prompt for the initial input
*/
function repl() {
rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
prompt()
}
/**
* Prompt for input in an asynchronous loop
* Interpret the commands from input and display the response
* TODO Slacker should probably be using *one* interpreter for its server
* as well as the debugger
*/
function prompt() {
rl.question("> slacker ", function (answer) {
// Keep track of how many commands have run and only prompt again after the last
var commandLength
// Pretend that the request came from Slack
answer = slackEncode(answer)
// Parse commands like the server does
commands = parse.commands(answer)
commandLength = commands.length
// No commands found, so start over
if (commandLength < 1) {
setImmediate(prompt)
}
// Cycle through commands, seek actions, and respond
_.each(commands, function (command) {
var actionFound = _.find(bot.actions, {name: command.name})
if (!actionFound) {
console.error("Action " + command.name + " not found")
setImmediate(prompt)
}
else {
// Input text must be parsed separately from commands
actionFound.execute({command: command}, function (actionResponse) {
// Emit response
console.log(actionResponse)
commandLength--
// If this is the last command run, prompt again
if (!commandLength) {
setImmediate(prompt)
}
})
}
})
})
}
/**
* Attempts to encode a string like Slack.com would
* Slack.com was written in PHP and based on some string examples and my
* experience, it is running `urlencode(htmlspecialchars(string))`
*
* This is a JS approximation
*/
function slackEncode(text) {
// urlencode
text = encodeURIComponent(
text
// htmlspecialchars
.replace(/&/g, "&").replace(/</g, ">").replace(/>/, "<")
)
.replace(/!/g, "%21").replace(/'/g, "%27").replace(/\(/g, "%28")
.replace(/\)/, "%29").replace(/\*/g, "%2A").replace(/%20| /g, "+")
return text
}