Browse Source

Mejorado el manejo de timeout para comando ping en general ahora espera 5

pull/1/head
rodley82 4 years ago
parent
commit
bb6ed73b45
  1. 41
      internal/slack/handler.go

41
internal/slack/handler.go

@ -6,6 +6,7 @@ import (
"fmt"
"log"
"os"
"time"
"os/exec"
"rodleyserverbot/slack-bot/config"
"github.com/slack-go/slack"
@ -64,9 +65,11 @@ func Start() {
//fmt.Println("Value:", action.Value)
var output string
var err error
replyToAction(callback.Channel.ID, "Chi Chi Chi Chi Amo, trabajando, tenga paciencia :pray:", client)
output, err = executeAction(action.Value)
if err == nil {
finalMessage := fmt.Sprintf("Chi chi chi chi amo!\n*Output*\n```\n%s\n```", output)
finalMessage := fmt.Sprintf("Resultado*\n```\n%s\n```", output)
replyToAction(callback.Channel.ID, finalMessage, client)
}
case slack.InteractionTypeMessageAction:
@ -138,20 +141,48 @@ func handleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client)
}
func executeAction(actionName string) (string, error) {
fmt.Println("executeAction actionName:", actionName, "actions:", config.Config.Actions)
//fmt.Println("executeAction actionName:", actionName, "actions:", config.Config.Actions)
var output_str string
var err error
for _, action := range config.Config.Actions {
if action.Name == actionName {
cmd := exec.Command("/bin/bash", action.Path)
output, err := cmd.Output()
output_str, err = executeScript(action.Path)
if err != nil {
fmt.Printf("error %s", err)
return "", err
}
output_str = string(output)
}
}
return output_str, err
}
func executeScript(scriptPath string) (string, error) {
// Create a new context and add a timeout to it
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // The cancel should be deferred so resources are cleaned up
// Create the command with our context
cmd := exec.CommandContext(ctx, "/bin/bash", scriptPath)
// This time we can simply use Output() to get the result.
out, err := cmd.Output()
// We want to check the context error to see if the timeout was executed.
// The error returned by cmd.Output() will be OS specific based on what
// happens when a process is killed.
if ctx.Err() == context.DeadlineExceeded {
fmt.Println("Command timed out")
return "", context.DeadlineExceeded
}
// If there's no context error, we know the command completed (or errored).
if err != nil {
fmt.Println("Non-zero exit code:", err)
}
output_str := string(out)
// fmt.Println("Output:", output_str)
return output_str, nil
}

Loading…
Cancel
Save