Class: Lita::Handlers::Cmd

Inherits:
Handler
  • Object
show all
Defined in:
lib/lita/handlers/cmd.rb

Instance Method Summary collapse

Instance Method Details

#create_routes(payload) ⇒ Object



15
16
17
18
19
# File 'lib/lita/handlers/cmd.rb', line 15

def create_routes(payload)
  self.class.route(/^\s*#{config.command_prefix}(\S+)\s*(.*)$/, :run_action, command: true, help: {
    "#{config.command_prefix}ACTION" => "run the specified ACTION. use `#{robot.name} #{config.command_prefix}list` for a list of available actions."
  })
end

#run_action(resp) ⇒ Object



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
# File 'lib/lita/handlers/cmd.rb', line 21

def run_action(resp)
  script = resp.matches[0][0]
  opts = CSV::parse_line(resp.matches[0][1], col_sep: ' ')

  # the script will be the robot name if command_prefix is empty
  return if robot_name and script =~ /^@?#{robot_name}$/i

  return show_help(resp) if script == 'list'

  unless user_is_authorized(script, resp, config)
    resp.reply_privately "Unauthorized to run '#{script}'!" unless config.command_prefix.empty? 
    return
  end

  out = String.new
  err = String.new

  script_path = "#{config.scripts_dir}/#{script}"
  env_vars    = { 'LITA_USER' => resp.user.name }

  Open3.popen3(env_vars, script_path, *opts) do |i, o, e, wait_thread|
    o.each { |line| out << "#{config.stdout_prefix}#{line}" }
    e.each { |line| err << "#{config.stderr_prefix}#{line}" }
  end

  if err != String.new
    out << "\n\n#{err}"
  end

  # Scrub Unicode to ASCII
  encoding_options = {
    :invalid           => :replace,  # Replace invalid byte sequences
    :undef             => :replace,  # Replace anything not defined in ASCII
    :replace           => ''        # Use a blank for those replacements
  }
  ascii_out = out.encode(Encoding.find('ASCII'), encoding_options)

  ascii_out.split("\n").each_slice(50) do |slice|
    resp.reply code_format(slice.join("\n"))
  end
end

#show_help(resp) ⇒ Object



63
64
65
66
67
68
# File 'lib/lita/handlers/cmd.rb', line 63

def show_help(resp)
  list = get_script_list(resp, config)

  out = list.sort.join("\n")
  resp.reply_privately code_format(out)
end