Class: SlackRubyBot::Commands::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/slack-ruby-bot/commands/base.rb

Direct Known Subclasses

Default, Help, Hi, Unknown

Class Method Summary collapse

Class Method Details

.command(*values, &block) ⇒ Object



42
43
44
45
46
47
# File 'lib/slack-ruby-bot/commands/base.rb', line 42

def self.command(*values, &block)
  values.each do |value|
    match Regexp.new("^(?<bot>[\\w[:punct:]@<>]*)[\\s]+(?<command>#{value})$", Regexp::IGNORECASE), &block
    match Regexp.new("^(?<bot>[\\w[:punct:]@<>]*)[\\s]+(?<command>#{value})[\\s]+(?<expression>.*)$", Regexp::IGNORECASE), &block
  end
end

.default_command_nameObject



32
33
34
# File 'lib/slack-ruby-bot/commands/base.rb', line 32

def self.default_command_name
  name && name.split(':').last.downcase
end

.invoke(client, data) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/slack-ruby-bot/commands/base.rb', line 49

def self.invoke(client, data)
  self.finalize_routes!
  expression = data.text
  called = false
  routes.each_pair do |route, method|
    match = route.match(expression)
    next unless match
    next if match.names.include?('bot') && !SlackRubyBot.config.name?(match['bot'])
    called = true
    if method
      method.call(client, data, match)
    elsif self.respond_to?(:call)
      send(:call, client, data, match)
    else
      fail NotImplementedError, data.text
    end
    break
  end
  called
end

.loggerObject



25
26
27
28
29
30
# File 'lib/slack-ruby-bot/commands/base.rb', line 25

def self.logger
  @logger ||= begin
    $stdout.sync = true
    Logger.new(STDOUT)
  end
end

.match(match, &block) ⇒ Object



70
71
72
73
# File 'lib/slack-ruby-bot/commands/base.rb', line 70

def self.match(match, &block)
  self.routes ||= {}
  self.routes[match] = block
end

.operator(*values, &block) ⇒ Object



36
37
38
39
40
# File 'lib/slack-ruby-bot/commands/base.rb', line 36

def self.operator(*values, &block)
  values.each do |value|
    match Regexp.new("^(?<operator>\\#{value})(?<expression>.*)$", Regexp::IGNORECASE), &block
  end
end

.send_message(client, channel, text, options = {}) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/slack-ruby-bot/commands/base.rb', line 6

def self.send_message(client, channel, text, options = {})
  if text && text.length > 0
    send_client_message(client, { channel: channel, text: text }.merge(options))
  else
    send_message_with_gif client, channel, 'Nothing to see here.', 'nothing', options
  end
end

.send_message_with_gif(client, channel, text, keywords, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/slack-ruby-bot/commands/base.rb', line 14

def self.send_message_with_gif(client, channel, text, keywords, options = {})
  gif = begin
    Giphy.random(keywords)
  rescue StandardError => e
    logger.warn "Giphy.random: #{e.message}"
    nil
  end
  text = text + "\n" + gif.image_url.to_s if gif
  send_message client, channel, text, options
end