You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

command.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "bytes"
  4. "github.com/spf13/viper"
  5. "github.com/thoj/go-ircevent"
  6. "os/exec"
  7. "strings"
  8. )
  9. func (i *IRCCat) handleCommand(event *irc.Event) {
  10. msg := event.Message()
  11. channel := ""
  12. respond_to := event.Arguments[0]
  13. if respond_to[0] != '#' {
  14. respond_to = event.Nick
  15. } else {
  16. channel = respond_to
  17. }
  18. if event.Arguments[0][0] != '#' && !i.authorisedUser(event.Nick) {
  19. // Command not in a channel, or not from an authorised user
  20. log.Infof("Unauthorised command: %s (%s) %s", event.Nick, respond_to, msg)
  21. return
  22. }
  23. log.Infof("Authorised command: %s (%s) %s", event.Nick, respond_to, msg)
  24. parts := strings.SplitN(msg, " ", 1)
  25. var cmd *exec.Cmd
  26. if len(parts) == 1 {
  27. cmd = exec.Command(viper.GetString("commands.handler"), event.Nick, channel, respond_to, parts[0][1:])
  28. } else {
  29. cmd = exec.Command(viper.GetString("commands.handler"), event.Nick, channel, respond_to, parts[0][1:], parts[1])
  30. }
  31. i.runCommand(cmd, respond_to)
  32. }
  33. // Run a command with the output going to the nick/channel identified by respond_to
  34. func (i *IRCCat) runCommand(cmd *exec.Cmd, respond_to string) {
  35. var out bytes.Buffer
  36. cmd.Stdout = &out
  37. cmd.Stderr = &out
  38. err := cmd.Run()
  39. if err != nil {
  40. log.Errorf("Running command %s failed: %s", cmd.Args, err)
  41. i.irc.Privmsgf(respond_to, "Command failed: %s", err)
  42. }
  43. lines := strings.Split(out.String(), "\n")
  44. line_count := len(lines)
  45. if line_count > viper.GetInt("commands.max_response_lines") {
  46. line_count = viper.GetInt("commands.max_response_lines")
  47. }
  48. for _, line := range lines[0:line_count] {
  49. if line != "" {
  50. i.irc.Privmsg(respond_to, line)
  51. }
  52. }
  53. }