Class: RailsConsoleAi::SlackBot

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_console_ai/slack_bot.rb

Constant Summary collapse

PING_INTERVAL =

seconds — send ping if no data received

30
PONG_TIMEOUT =

seconds — reconnect if no pong after ping

60
GREETINGS =
%w[hi hey hello howdy yo sup hola].to_set.freeze

Instance Method Summary collapse

Constructor Details

#initializeSlackBot

Returns a new instance of SlackBot.

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rails_console_ai/slack_bot.rb', line 18

def initialize
  @bot_token = RailsConsoleAi.configuration.slack_bot_token || ENV['SLACK_BOT_TOKEN']
  @app_token = RailsConsoleAi.configuration.slack_app_token || ENV['SLACK_APP_TOKEN']
  @channel_ids = resolve_channel_ids

  raise ConfigurationError, "SLACK_BOT_TOKEN is required" unless @bot_token
  raise ConfigurationError, "SLACK_APP_TOKEN is required (Socket Mode)" unless @app_token
  unless RailsConsoleAi.configuration.channel_setting('slack', 'allowed_usernames')
    raise ConfigurationError, "slack allowed_usernames must be configured — either channels['slack']['allowed_usernames'] or slack_allowed_usernames (e.g. ['alice'] or 'ALL')"
  end

  @bot_user_id = nil
  @sessions = {}       # thread_ts → { channel:, engine:, thread:, owner_user_id: }
  @user_cache = {}     # slack user_id → display_name
  @channel_cache = {}  # channel_id → channel name
  @processed_ts = {}   # ts → Time — dedup app_mention vs message events
  @mutex = Mutex.new
end

Instance Method Details

#startObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rails_console_ai/slack_bot.rb', line 37

def start
  $stdout.sync = true
  $stderr.sync = true
  $stdout = RailsConsoleAi::PrefixedIO.new($stdout) unless $stdout.is_a?(RailsConsoleAi::PrefixedIO)
  $stderr = RailsConsoleAi::PrefixedIO.new($stderr) unless $stderr.is_a?(RailsConsoleAi::PrefixedIO)

  # Eager load the Rails app so class-level initializers (e.g. Secret.get)
  # run before safety guards are active during user code execution.
  if defined?(Rails) && Rails.application.respond_to?(:eager_load!)
    puts "Eager loading application..."
    Rails.application.eager_load!
  end

  @bot_user_id = slack_api("auth.test", token: @bot_token).dig("user_id")
  log_startup

  loop do
    run_socket_mode
    puts "Reconnecting in 5s..."
    sleep 5
  end
rescue Interrupt
  puts "\nSlackBot shutting down."
end