Class: SlackSmartBot

Inherits:
Object
  • Object
show all
Defined in:
lib/slack-smart-bot.rb

Constant Summary collapse

VERSION =
Gem.loaded_specs.values.select { |x| x.name == "slack-smart-bot" }[0].version.to_s

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ SlackSmartBot


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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/slack-smart-bot.rb', line 35

def initialize(config)
  Dir.mkdir("./logs") unless Dir.exist?("./logs")
  Dir.mkdir("./shortcuts") unless Dir.exist?("./shortcuts")
  logfile = File.basename(RULES_FILE.gsub("_rules_", "_logs_"), ".rb") + ".log"
  @logger = Logger.new("./logs/#{logfile}")
  config_log = config.dup
  config_log.delete(:token)
  config[:silent] = false unless config.key?(:silent)
  @logger.info "Initializing bot: #{config_log.inspect}"

  config[:channel] = CHANNEL
  self.config = config

  Slack.configure do |conf|
    conf.token = config[:token]
  end
  self.client = Slack::RealTime::Client.new(start_method: :rtm_connect)

  @listening = Array.new

  @bots_created = Hash.new()
  @shortcuts = Hash.new()
  @shortcuts[:all] = Hash.new()
  @rules_imported = Hash.new()

  if File.exist?("./shortcuts/#{SHORTCUTS_FILE}")
    file_sc = IO.readlines("./shortcuts/#{SHORTCUTS_FILE}").join
    unless file_sc.to_s() == ""
      @shortcuts = eval(file_sc)
    end
  end

  if ON_MASTER_BOT and File.exist?($0.gsub(".rb", "_bots.rb"))
    get_bots_created()
    if @bots_created.kind_of?(Hash)
      @bots_created.each { |key, value|
        if !value.key?(:cloud) or (value.key?(:cloud) and value[:cloud] == false)
          @logger.info "ruby #{$0} \"#{value[:channel_name]}\" \"#{value[:admins]}\" \"#{value[:rules_file]}\" #{value[:status].to_sym}"
          t = Thread.new do
            `ruby #{$0} \"#{value[:channel_name]}\" \"#{value[:admins]}\" \"#{value[:rules_file]}\" #{value[:status].to_sym}`
          end
          value[:thread] = t
        end
      }
    end
  end

  # rules imported only for DM
  if ON_MASTER_BOT and File.exist?("./rules/rules_imported.rb")
    file_conf = IO.readlines("./rules/rules_imported.rb").join
    unless file_conf.to_s() == ""
      @rules_imported = eval(file_conf)
    end
  end

  begin
     = client.web_client.users_info(user: "#{"@" if config[:nick][0] != "@"}#{config[:nick]}")
    config[:nick_id] = .user.id
  rescue Exception => stack
    @logger.fatal stack
    abort("The bot user specified on settings: #{config[:nick]}, doesn't exist on Slack. Execution aborted")
  end

  client.on :hello do
    m = "Successfully connected, welcome '#{client.self.name}' to the '#{client.team.name}' team at https://#{client.team.domain}.slack.com."
    puts m
    @logger.info m
    gems_remote = `gem list slack-smart-bot --remote`
    version_remote = gems_remote.to_s().scan(/slack-smart-bot \((\d+\.\d+\.\d+)/).join
    version_message = ""
    if version_remote != VERSION
      version_message = ". There is a new available version: #{version_remote}."
    end
    unless config[:silent]
      respond "Smart Bot started v#{VERSION}#{version_message}\nIf you want to know what I can do for you: `bot help`.\n`bot rules` if you want to display just the specific rules of this channel.\nYou can talk to me privately if you prefer it."
    end
  end

  @status = STATUS_INIT
  @questions = Hash.new()
  @channels_id = Hash.new()
  @channels_name = Hash.new()
  get_channels_name_and_id()
  @channel_id = @channels_id[CHANNEL].dup
  @master_bot_id = @channels_id[MASTER_CHANNEL].dup

  client.on :close do |_data|
    m = "Connection closing, exiting. #{Time.now}"
    @logger.info m
    @logger.info _data
  end

  client.on :closed do |_data|
    m = "Connection has been disconnected. #{Time.now}"
    @logger.info m
    @logger.info _data
  end

  self
end

Instance Attribute Details

#channel_idObject (readonly)

Returns the value of attribute channel_id


32
33
34
# File 'lib/slack-smart-bot.rb', line 32

def channel_id
  @channel_id
end

#clientObject

Returns the value of attribute client


31
32
33
# File 'lib/slack-smart-bot.rb', line 31

def client
  @client
end

#configObject

Returns the value of attribute config


31
32
33
# File 'lib/slack-smart-bot.rb', line 31

def config
  @config
end

#master_bot_idObject (readonly)

Returns the value of attribute master_bot_id


32
33
34
# File 'lib/slack-smart-bot.rb', line 32

def master_bot_id
  @master_bot_id
end

Instance Method Details

#ask(question, context, to, dest = nil) ⇒ Object

context: previous message to: user that should answer


1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
# File 'lib/slack-smart-bot.rb', line 1321

def ask(question, context, to, dest = nil)
  if dest.nil?
    client.message(channel: @channel_id, text: "#{to}: #{question}", as_user: true)
  elsif dest[0] == "C" or dest[0] == "G" # channel
    client.message(channel: dest, text: "#{to}: #{question}", as_user: true)
  elsif dest[0] == "D" #private message
    send_msg_user(dest, "#{to}: #{question}")
  end
  @questions[to] = context
end

#listenObject

help: =================================== help: help: Commands from Channels without a bot: help: help: ---------------------------------------------- help: help: @BOT_NAME on #CHANNEL_NAME COMMAND help: @BOT_NAME #CHANNEL_NAME COMMAND help: It will run the supplied command using the rules on the channel supplied. help: You need to join the specified channel to be able to use those rules. help: Also you can use this command to call another bot from a channel with a running bot.


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/slack-smart-bot.rb', line 201

def listen
  @salutations = [config[:nick], config[:nick_id], "bot", "smart"]
  get_bots_created()
  client.on :message do |data|
    if data.channel[0] == "D" or data.channel[0] == "C" or data.channel[0] == "G" #Direct message or Channel or Private Channel
      dest = data.channel
    else # not treated
      dest = nil
    end
    #todo: sometimes data.user is nil, check the problem.
    @logger.warn "!dest is nil. user: #{data.user}, channel: #{data.channel}, message: #{data.text}" if dest.nil?
    
    typem = :dont_treat
    if !dest.nil? and !data.text.nil? and !data.text.to_s.match?(/^\s*$/)
      if data.text.match(/^<@#{config[:nick_id]}>\s(on\s)?<#(\w+)\|(.+)>\s*:?\s*(.*)/im)
        channel_rules = $2
        channel_rules_name = $3
        # to be treated only on the bot of the requested channel
        if @channel_id == channel_rules 
          data.text = $4
          typem = :on_call
        end

      elsif dest == @master_bot_id
        if ON_MASTER_BOT #only to be treated on master mot channel
          typem = :on_master
        end
      elsif @bots_created.key?(dest)
        if @channel_id == dest #only to be treated by the bot on the channel
          typem = :on_bot
        end
      elsif dest[0]=="D" #Direct message
        if ON_MASTER_BOT #only to be treated by master bot
          typem = :on_dm
        end
      elsif dest[0]=="G" #private group
        if ON_MASTER_BOT #only to be treated by master bot
          typem = :on_pg
        end
      elsif dest[0]=='C' 
        #only to be treated on the channel of the bot. excluding running ruby
        if !ON_MASTER_BOT and @bots_created[@channel_id][:extended].include?(@channels_name[dest]) and
          !data.text.match?(/^!?\s*(ruby|code)\s+/)
          typem = :on_extended
        elsif ON_MASTER_BOT and data.text.match?(/^!?\s*(ruby|code)\s+/) #or in case of running ruby, the master bot
          @bots_created.each do |k,v|
            if v.key?(:extended) and v[:extended].include?(@channels_name[dest])
              typem = :on_extended
              break
            end
          end
        end
      end
    end
    
    unless typem == :dont_treat
      begin
        command = data.text

        #todo: when changed @questions user_id then move user_info inside the ifs to avoid calling it when not necessary
         = client.web_client.users_info(user: data.user)
        
        #when added special characters on the message
        if command.size >= 2 and
           ((command[0] == "`" and command[-1] == "`") or (command[0] == "*" and command[-1] == "*") or (command[0] == "_" and command[-1] == "_"))
          command = command[1..-2]
        end

        #ruby file attached
        if !data.files.nil? and data.files.size == 1 and
           (command.match?(/^(ruby|code)\s*$/) or (command.match?(/^\s*$/) and data.files[0].filetype == "ruby") or
            (typem==:on_call and data.files[0].filetype == "ruby"))
          res = Faraday.new("https://files.slack.com", headers: { "Authorization" => "Bearer #{config[:token]}" }).get(data.files[0].url_private)
          command = "#{command} ruby #{res.body.to_s.force_encoding("UTF-8")}"
        end

        if typem == :on_call
          command = "!" + command unless command[0] == "!" or command.match?(/^\s*$/)
          
          #todo: add pagination for case more than 1000 channels on the workspace
          channels = client.web_client.conversations_list(
            types: 'private_channel,public_channel', 
            limit: '1000',
            exclude_archived: 'true').channels
          channel_found = channels.detect { |c| c.name == channel_rules_name }
          members = client.web_client.conversations_members(channel: @channels_id[channel_rules_name]).members unless channel_found.nil?
          if channel_found.nil?
            @logger.fatal "Not possible to find the channel #{channel_rules_name}"
          elsif channel_found.name == MASTER_CHANNEL
            respond "You cannot use the rules from Master Channel on any other channel.", dest
          elsif @status != :on
            respond "The bot in that channel is not :on", dest
          elsif data.user == channel_found.creator or members.include?(data.user)
            res = process_first(.user, command, dest, channel_rules, typem)
          else
            respond "You need to join the channel <##{channel_found.id}> to be able to use the rules.", dest
          end

        elsif @questions.keys.include?(.user.name)
          #todo: @questions key should be the id not the name. change it everywhere
          dest = data.channel
          res = process_first(.user, command, dest, @channel_id, typem)

        elsif ON_MASTER_BOT and typem ==:on_extended and
          command.size > 0 and command[0] != "-"
          # to run ruby only from the master bot for the case more than one extended
          res = process_first(.user, command, dest, @channel_id, typem)

        elsif !ON_MASTER_BOT and @bots_created[@channel_id].key?(:extended) and 
          @bots_created[@channel_id][:extended].include?(@channels_name[data.channel]) and
          command.size > 0 and command[0] != "-"
          res = process_first(.user, command, dest, @channel_id, typem)
        elsif (dest[0] == "D" or @channel_id == data.channel or data.user == config[:nick_id]) and
              command.size > 0 and command[0] != "-"
          res = process_first(.user, command, dest, data.channel, typem)
          # if @botname on #channel_rules: do something
        end
      rescue Exception => stack
        @logger.fatal stack
      end
    end
  end

  @logger.info "Bot listening"
  client.start!
end

#process(user, command, dest, dchannel, rules_file, typem) ⇒ Object

help: =================================== help: help: General commands: help:


520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
# File 'lib/slack-smart-bot.rb', line 520

def process(user, command, dest, dchannel, rules_file, typem)
  from = user.name
  display_name = user.profile.display_name
  processed = true

  if typem == :on_master or typem == :on_bot or typem ==:on_pg or typem == :on_dm
    case command

    #help: ----------------------------------------------
    #help: `Hello Bot`
    #help: `Hello Smart`
    #help: `Hello THE_NAME_OF_THE_BOT`
    #help:    Also apart of Hello you can use _Hallo, Hi, Hola, What's up, Hey, Hæ_
    #help:    Bot starts listening to you
    #help:    If you want to avoid a single message to be treated by the smart bot, start the message by -
    #help:
    when /^(Hello|Hallo|Hi|Hola|What's\sup|Hey|Hæ)\s(#{@salutations.join("|")})\s*$/i
      if @status == :on
        greetings = ["Hello", "Hallo", "Hi", "Hola", "What's up", "Hey", ""].sample
        respond "#{greetings} #{display_name}", dest
        if @rules_imported.key?(user.id) and @rules_imported[user.id].key?(user.id) and dest[0] == "D"
          respond "You are using specific rules for channel: <##{@rules_imported[user.id][user.id]}>", dest
        elsif @rules_imported.key?(user.id) and @rules_imported[user.id].key?(dchannel) and (dest[0] == "C" or dest[0] == "G")
          respond "You are using specific rules for channel: <##{@rules_imported[user.id][dchannel]}>", dest
        end
        @listening << from unless @listening.include?(from)
      end

      #help: ----------------------------------------------
      #help: `Bye Bot`
      #help: `Bye Smart`
      #help: `Bye NAME_OF_THE_BOT`
      #help:    Also apart of Bye you can use _Bæ, Good Bye, Adiós, Ciao, Bless, Bless Bless, Adeu_
      #help:    Bot stops listening to you
      #help:
    when /^(Bye|Bæ|Good\sBye|Adiós|Ciao|Bless|Bless\sBless|Adeu)\s(#{@salutations.join("|")})\s*$/i
      if @status == :on
        bye = ["Bye", "", "Good Bye", "Adiós", "Ciao", "Bless", "Bless bless", "Adeu"].sample
        respond "#{bye} #{display_name}", dest
        @listening.delete(from)
      end

      #help: ----------------------------------------------
      #help: `bot help`
      #help: `bot what can I do?`
      #help: `bot rules`
      #help:    it will display this help
      #help:    `bot rules` will show only the specific rules for this channel.
    when /^bot\s+(rules|help)/i, /^bot,? what can I do/i
      if $1.to_s.match?(/rules/i)
        specific = true
      else
        specific = false
      end
      help_message_rules = ''
      if !specific
        help_message = IO.readlines(__FILE__).join
        if ADMIN_USERS.include?(from) #admin user
          respond "*Commands for administrators:*\n#{help_message.scan(/#\s*help\s*admin:(.*)/).join("\n")}", dest
        end
        if ON_MASTER_BOT and (dest[0] == "C" or dest[0] == "G")
          respond "*Commands only on Master Channel <##{@master_bot_id}>:*\n#{help_message.scan(/#\s*help\s*master:(.*)/).join("\n")}", dest
        end
        respond help_message.scan(/#\s*help\s*:(.*)/).join("\n"), dest
      end
      if dest[0] == "C" or dest[0] == "G" # on a channel
        if @rules_imported.key?(user.id) and @rules_imported[user.id].key?(dchannel)
          if @bots_created.key?(@rules_imported[user.id][dchannel])
            respond "*You are using rules from another channel: <##{@rules_imported[user.id][dchannel]}>. These are the specific commands for that channel:*", dest
          end
        end
        help_message_rules = IO.readlines(rules_file).join
        respond help_message_rules.scan(/#\s*help\s*:(.*)/).join("\n"), dest
      elsif dest[0] == "D" and @rules_imported.key?(user.id) and @rules_imported[user.id].key?(user.id) #direct message
        if @bots_created.key?(@rules_imported[user.id][user.id])
          respond "*You are using rules from channel: <##{@rules_imported[user.id][user.id]}>. These are the specific commands for that channel:*", dest
          help_message_rules = IO.readlines(rules_file).join
          respond help_message_rules.scan(/#\s*help\s*:(.*)/).join("\n"), dest
        end
      end
      if specific
        unless rules_file.empty?
          begin
            eval(File.new(rules_file).read) if File.exist?(rules_file)
          end
        end
        if defined?(git_project) and git_project.to_s!='' and help_message_rules != ''
          respond "Git project: #{git_project}", dest
        else
          def git_project() '' end
          def project_folder() '' end
        end
        
      else
        respond "Slack Smart Bot Github project: https://github.com/MarioRuiz/slack-smart-bot", dest
      end

      #help: ===================================
      #help:
      #help: *These commands will run only when on a private conversation with the bot:*
      #help:
      #help: ----------------------------------------------
      #help: `use rules from CHANNEL`
      #help:    it will use the rules from the specified channel.
      #help:    you need to be part of that channel to be able to use the rules.
      #help:
    when /^use rules (from\s+)<#C\w+\|(.+)>/i, /^use rules (from\s+)(.+)/i
      channel = $2
      #todo: add pagination for case more than 1000 channels on the workspace
      channels = client.web_client.conversations_list(
        types: 'private_channel,public_channel', 
        limit: '1000',
        exclude_archived: 'true').channels

      channel_found = channels.detect { |c| c.name == channel }
      members = client.web_client.conversations_members(channel: @channels_id[channel]).members unless channel_found.nil?

      if channel_found.nil?
        respond "The channel you are trying to use doesn't exist", dest
      elsif channel_found.name == MASTER_CHANNEL
        respond "You cannot use the rules from Master Channel on any other channel.", dest
      elsif !@bots_created.key?(@channels_id[channel])
        respond "There is no bot running on that channel.", dest
      elsif @bots_created.key?(@channels_id[channel]) and @bots_created[@channels_id[channel]][:status] != :on
        respond "The bot in that channel is not :on", dest
      else
        if user.id == channel_found.creator or members.include?(user.id)
          @rules_imported[user.id] = {} unless @rules_imported.key?(user.id)
          if dest[0] == "C" or dest[0] == "G" #todo: take in consideration bots that are not master
            @rules_imported[user.id][dchannel] = channel_found.id
          else
            @rules_imported[user.id][user.id] = channel_found.id
          end
          update_rules_imported() if ON_MASTER_BOT
          respond "I'm using now the rules from <##{channel_found.id}>", dest
          def git_project() "" end
          def project_folder() "" end
        else
          respond "You need to join the channel <##{channel_found.id}> to be able to use the rules.", dest
        end
      end

      #help: ----------------------------------------------
      #help: `stop using rules from CHANNEL`
      #help:    it will stop using the rules from the specified channel.
      #help:
    when /^stop using rules (from\s+)<#\w+\|(.+)>/i, /^stop using rules (from\s+)(.+)/i
      channel = $2
      if @channels_id.key?(channel)
        channel_id = @channels_id[channel]
      else
        channel_id = channel
      end
      if dest[0] == "C" or dest[0] == "G" #channel
        if @rules_imported.key?(user.id) and @rules_imported[user.id].key?(dchannel)
          if @rules_imported[user.id][dchannel] != channel_id
            respond "You are not using those rules.", dest
          else
            @rules_imported[user.id].delete(dchannel)
            update_rules_imported() if ON_MASTER_BOT
            respond "You won't be using those rules from now on.", dest
            def git_project() "" end
            def project_folder() "" end
          end
        else
          respond "You were not using those rules.", dest
        end
      else #direct message
        if @rules_imported.key?(user.id) and @rules_imported[user.id].key?(user.id)
          if @rules_imported[user.id][user.id] != channel_id
            respond "You are not using those rules.", dest
          else
            @rules_imported[user.id].delete(user.id)
            update_rules_imported() if ON_MASTER_BOT
            respond "You won't be using those rules from now on.", dest
            def git_project() "" end
            def project_folder() "" end
          end
        else
          respond "You were not using those rules.", dest
        end
      end

      #helpadmin: ----------------------------------------------
      #helpadmin: `exit bot`
      #helpadmin: `quit bot`
      #helpadmin: `close bot`
      #helpadmin:    The bot stops running and also stops all the bots created from this master channel
      #helpadmin:    You can use this command only if you are an admin user and you are on the master channel
      #helpadmin:
    when /^exit\sbot\s*$/i, /^quit\sbot\s*$/i, /^close\sbot\s*$/i
      if ON_MASTER_BOT
        if ADMIN_USERS.include?(from) #admin user
          unless @questions.keys.include?(from)
            ask("are you sure?", command, from, dest)
          else
            case @questions[from]
            when /yes/i, /yep/i, /sure/i
              respond "Game over!", dest
              respond "Ciao #{display_name}!", dest
              @bots_created.each { |key, value|
                value[:thread] = ""
                send_msg_channel(key, "Bot has been closed by #{from}")
                sleep 0.5
              }
              update_bots_file()
              sleep 0.5
              exit!
            when /no/i, /nope/i, /cancel/i
              @questions.delete(from)
              respond "Thanks, I'm happy to be alive", dest
            else
              respond "I don't understand", dest
              ask("are you sure do you want me to close? (yes or no)", "quit bot", from, dest)
            end
          end
        else
          respond "Only admin users can kill me", dest
        end
      else
        respond "To do this you need to be an admin user in the master channel: <##{@master_bot_id}>", dest
      end

      #helpadmin: ----------------------------------------------
      #helpadmin: `start bot`
      #helpadmin: `start this bot`
      #helpadmin:    the bot will start to listen
      #helpadmin:    You can use this command only if you are an admin user
      #helpadmin:
    when /^start\s(this\s)?bot$/i
      if ADMIN_USERS.include?(from) #admin user
        respond "This bot is running and listening from now on. You can pause again: pause this bot", dest
        @status = :on
        unless ON_MASTER_BOT
          send_msg_channel MASTER_CHANNEL, "Changed status on #{CHANNEL} to :on"
        end
      else
        respond "Only admin users can change my status", dest
      end

      #helpadmin: ----------------------------------------------
      #helpadmin: `pause bot`
      #helpadmin: `pause this bot`
      #helpadmin:    the bot will pause so it will listen only to admin commands
      #helpadmin:    You can use this command only if you are an admin user
      #helpadmin:
    when /^pause\s(this\s)?bot$/i
      if ADMIN_USERS.include?(from) #admin user
        respond "This bot is paused from now on. You can start it again: start this bot", dest
        respond "zZzzzzZzzzzZZZZZZzzzzzzzz", dest
        @status = :paused
        unless ON_MASTER_BOT
          send_msg_channel MASTER_CHANNEL, "Changed status on #{CHANNEL} to :paused"
        end
      else
        respond "Only admin users can put me on pause", dest
      end

      #helpadmin: ----------------------------------------------
      #helpadmin: `bot status`
      #helpadmin:    Displays the status of the bot
      #helpadmin:    If on master channel and admin user also it will display info about bots created
      #helpadmin:
    when /^bot\sstatus/i
      get_bots_created()
      gems_remote = `gem list slack-smart-bot --remote`
      version_remote = gems_remote.to_s().scan(/slack-smart-bot \((\d+\.\d+\.\d+)/).join
      version_message = ""
      if version_remote != VERSION
        version_message = " There is a new available version: #{version_remote}."
      end
      require 'socket'
      ip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address
      respond "*#{Socket.gethostname} (#{ip_address})*\n\tStatus: #{@status}.\n\tVersion: #{VERSION}.#{version_message}\n\tRules file: #{File.basename RULES_FILE} ", dest
      if @status == :on
        respond "I'm listening to [#{@listening.join(", ")}]", dest
        if ON_MASTER_BOT and ADMIN_USERS.include?(from)
          
          @bots_created.each do |k,v|
              msg = []
              msg << "`#{v[:channel_name]}` (#{k}):"
              msg << "\tcreator: #{v[:creator_name]}"
              msg << "\tadmins: #{v[:admins]}"
              msg << "\tstatus: #{v[:status]}"
              msg << "\tcreated: #{v[:created]}"
              msg << "\trules: #{v[:rules_file]}"
              msg << "\textended: #{v[:extended]}"
              msg << "\tcloud: #{v[:cloud]}"
              if  ON_MASTER_BOT and v.key?(:cloud) and v[:cloud]
                  msg << "\trunner: `ruby #{$0} \"#{v[:channel_name]}\" \"#{v[:admins]}\" \"#{v[:rules_file]}\" on&`"
              end
              respond msg.join("\n"), dest
          end
        end
      end

      #helpmaster: ----------------------------------------------
      #helpmaster: `notify MESSAGE`
      #helpmaster: `notify all MESSAGE`
      #helpmaster:    It will send a notificaiton message to all bot channels
      #helpmaster:    It will send a notification message to all channels the bot joined and private conversations with the bot
      #helpmaster:    Only works if you are on Master channel and you are an admin user
      #helpmaster:
    when /^notify\s+(all)?\s*(.+)\s*$/i
      if ON_MASTER_BOT
        if ADMIN_USERS.include?(from) #admin user
          all = $1
          message = $2
          if all.nil?
            @bots_created.each do |k, v|
              respond message, k
            end
            respond "Bot channels have been notified", dest
          else
            myconv = client.web_client.users_conversations(exclude_archived: true, limit: 100, types: "im, public_channel").channels
            myconv.each do |c|
              respond message, c.id unless c.name == MASTER_CHANNEL
            end
            respond "Channels and users have been notified", dest
          end
        end
      end

      #helpmaster: ----------------------------------------------
      #helpmaster: `create bot on CHANNEL_NAME`
      #helpmaster: `create cloud bot on CHANNEL_NAME`
      #helpmaster:    creates a new bot on the channel specified
      #helpmaster:    it will work only if you are on Master channel
      #helpmaster:    the admins will be the master admins, the creator of the bot and the creator of the channel
      #helpmaster:    follow the instructions in case creating cloud bots
    when /^create\s+(cloud\s+)?bot\s+on\s+<#C\w+\|(.+)>\s*/i, /^create\s+(cloud\s+)?bot\s+on\s+(.+)\s*/i
      if ON_MASTER_BOT
        cloud = !$1.nil?
        channel = $2

        get_channels_name_and_id() unless @channels_name.keys.include?(channel) or @channels_id.keys.include?(channel)
        channel_id = nil
        if @channels_name.key?(channel) #it is an id
          channel_id = channel
          channel = @channels_name[channel_id]
        elsif @channels_id.key?(channel) #it is a channel name
          channel_id = @channels_id[channel]
        end
        #todo: add pagination for case more than 1000 channels on the workspace
        channels = client.web_client.conversations_list(
          types: 'private_channel,public_channel', 
          limit: '1000',
          exclude_archived: 'true').channels
        channel_found = channels.detect { |c| c.name == channel }
        members = client.web_client.conversations_members(channel: @channels_id[channel]).members unless channel_found.nil?

        if channel_id.nil?
          respond "There is no channel with that name: #{channel}, please be sure is written exactly the same", dest
        elsif channel == MASTER_CHANNEL
          respond "There is already a bot in this channel: #{channel}", dest
        elsif @bots_created.keys.include?(channel_id)
          respond "There is already a bot in this channel: #{channel}, kill it before", dest
        elsif config[:nick_id] != channel_found.creator and !members.include?(config[:nick_id])
          respond "You need to add first to the channel the smart bot user: #{config[:nick]}", dest
        else
          if channel_id != config[:channel]
            begin
              rules_file = "slack-smart-bot_rules_#{channel_id}_#{from.gsub(" ", "_")}.rb"
              if defined?(RULES_FOLDER)
                rules_file = RULES_FOLDER + rules_file
              else
                Dir.mkdir("rules") unless Dir.exist?("rules")
                Dir.mkdir("rules/#{channel_id}") unless Dir.exist?("rules/#{channel_id}")
                rules_file = "./rules/#{channel_id}/" + rules_file
              end
              default_rules = (__FILE__).gsub(/\.rb$/, "_rules.rb")
              File.delete(rules_file) if File.exist?(rules_file)
              FileUtils.copy_file(default_rules, rules_file) unless File.exist?(rules_file)
              admin_users = Array.new()
              creator_info = client.web_client.users_info(user: channel_found.creator)
              admin_users = [from, creator_info.user.name] + MASTER_USERS
              admin_users.uniq!
              @logger.info "ruby #{$0} \"#{channel}\" \"#{admin_users.join(",")}\" \"#{rules_file}\" on"
              if cloud
                respond "Copy the bot folder to your cloud location and run `ruby #{$0} \"#{channel}\" \"#{admin_users.join(",")}\" \"#{rules_file}\" on&`", dest
              else
                t = Thread.new do
                  `ruby #{$0} \"#{channel}\" \"#{admin_users.join(",")}\" \"#{rules_file}\" on`
                end
              end
              @bots_created[channel_id] = {
                creator_name: from,
                channel_id: channel_id,
                channel_name: @channels_name[channel_id],
                status: :on,
                created: Time.now.strftime("%Y-%m-%dT%H:%M:%S.000Z")[0..18],
                rules_file: rules_file,
                admins: admin_users.join(","),
                extended: [],
                cloud: cloud,
                thread: t,
              }
              respond "The bot has been created on channel: #{channel}. Rules file: #{File.basename rules_file}. Admins: #{admin_users.join(", ")}", dest
              update_bots_file()
            rescue Exception => stack
              @logger.fatal stack
              message = "Problem creating the bot on channel #{channel}. Error: <#{stack}>."
              @logger.error message
              respond message, dest
            end
          else
            respond "There is already a bot in this channel: #{channel}, and it is the Master Channel!", dest
          end
        end
      else
        @logger.info MASTER_CHANNEL
        @logger.info @channel_id.inspect
        respond "Sorry I cannot create bots from this channel, please visit the master channel: <##{@master_bot_id}>", dest
      end

      #helpmaster: ----------------------------------------------
      #helpmaster: `kill bot on CHANNEL_NAME`
      #helpmaster:    kills the bot on the specified channel
      #helpmaster:    Only works if you are on Master channel and you created that bot or you are an admin user
      #helpmaster:
    when /^kill\sbot\son\s<#C\w+\|(.+)>\s*$/i, /^kill\sbot\son\s(.+)\s*$/i
      if ON_MASTER_BOT
        channel = $1

        get_channels_name_and_id() unless @channels_name.keys.include?(channel) or @channels_id.keys.include?(channel)
        channel_id = nil
        if @channels_name.key?(channel) #it is an id
          channel_id = channel
          channel = @channels_name[channel_id]
        elsif @channels_id.key?(channel) #it is a channel name
          channel_id = @channels_id[channel]
        end
        if channel_id.nil?
          respond "There is no channel with that name: #{channel}, please be sure is written exactly the same", dest
        elsif @bots_created.keys.include?(channel_id)
          if @bots_created[channel_id][:admins].split(",").include?(from)
            if @bots_created[channel_id][:thread].kind_of?(Thread) and @bots_created[channel_id][:thread].alive?
              @bots_created[channel_id][:thread].kill
            end
            @bots_created.delete(channel_id)
            update_bots_file()
            respond "Bot on channel: #{channel}, has been killed and deleted.", dest
            send_msg_channel(channel, "Bot has been killed by #{from}")
          else
            respond "You need to be the creator or an admin of that bot channel", dest
          end
        else
          respond "There is no bot in this channel: #{channel}", dest
        end
      else
        respond "Sorry I cannot kill bots from this channel, please visit the master channel: <##{@master_bot_id}>", dest
      end



    else
      processed = false
    end
  else
    processed = false
  end

  on_demand = false
  if command.match(/^@?(#{config[:nick]}):*\s+(.+)/im) or
     command.match(/^()!(.+)/im) or
     command.match(/^()<@#{config[:nick_id]}>\s+(.+)/im)
    command = $2
    on_demand = true
  end

  #only when :on and (listening or on demand or direct message)
  if @status == :on and
     (@questions.keys.include?(from) or
      (@listening.include?(from) and typem!=:on_extended) or
      typem == :on_dm or typem ==:on_pg or on_demand)
    processed2 = true

    #help: ===================================
    #help:
    #help: *These commands will run only when the smart bot is listening to you or on demand or in a private conversation with the Smart Bot*. To run a command on demand:
    #help:       `!THE_COMMAND`
    #help:       `@NAME_OF_BOT THE_COMMAND`
    #help:       `NAME_OF_BOT THE_COMMAND`
    #help:
    case command

    when /^bot\s+rules$/i
      if typem == :on_extended or typem == :on_call #for the other cases above.
        help_message_rules = ''
        message = "-\n\n\n===================================\n*Rules from channel #{CHANNEL}*\n"
        if typem == :on_extended
          message += "To run the commands on this extended channel, add `!` before the command.\n"
        end
        help_message_rules = IO.readlines(rules_file).join
        message += help_message_rules.scan(/#\s*help\s*:(.*)/).join("\n")
        respond message, dest
        unless rules_file.empty?
          begin
            eval(File.new(rules_file).read) if File.exist?(rules_file)
          end
        end
        if defined?(git_project) and git_project.to_s!='' and help_message_rules != ''
          respond "Git project: #{git_project}", dest
        else
          def git_project() '' end
          def project_folder() '' end
        end
      end



    #helpadmin: ----------------------------------------------
    #helpadmin: `extend rules to CHANNEL_NAME`
    #helpadmin: `use rules on CHANNEL_NAME`
    #helpadmin:    It will allow to use the specific rules from this channel on the CHANNEL_NAME
    #helpadmin:
    when /^extend\s+rules\s+(to\s+)<#C\w+\|(.+)>/i, /^extend\s+rules\s+(to\s+)(.+)/i, 
      /^use\s+rules\s+(on\s+)<#C\w+\|(.+)>/i, /^use\s+rules\s+(on\s+)(.+)/i 
      unless typem == :on_extended
        if ON_MASTER_BOT
          respond "You cannot use the rules from Master Channel on any other channel.", dest
        elsif !ADMIN_USERS.include?(from) #not admin 
          respond "Only admins can extend the rules. Admins on this channel: #{ADMIN_USERS}", dest
        else
          channel = $2
          #todo: add pagination for case more than 1000 channels on the workspace
          channels = client.web_client.conversations_list(
            types: 'private_channel,public_channel', 
            limit: '1000',
            exclude_archived: 'true').channels

          channel_found = channels.detect { |c| c.name == channel }
          members = client.web_client.conversations_members(channel: @channels_id[channel]).members unless channel_found.nil?
          get_bots_created()
          channels_in_use = []
          @bots_created.each do |k,v| 
            if v.key?(:extended) and v[:extended].include?(channel)
              channels_in_use << v[:channel_name]
            end
          end
          
          if channel_found.nil?
            respond "The channel you specified doesn't exist", dest
          elsif @bots_created.key?(@channels_id[channel])
            respond "There is a bot already running on that channel.", dest
          elsif @bots_created[@channel_id][:extended].include?(channel)
            respond "The rules are already extended to that channel.", dest
          elsif !members.include?(config[:nick_id])
            respond "You need to add first to the channel the smart bot user: #{config[:nick]}", dest
          elsif !members.include?(user.id)
            respond "You need to join that channel first", dest
          else
            channels_in_use.each do |channel_in_use|
              respond "The rules from channel <##{@channels_id[channel_in_use]}> are already in use on that channel", dest
            end
            @bots_created[@channel_id][:extended] = [] unless @bots_created[@channel_id].key?(:extended)
            @bots_created[@channel_id][:extended] << channel
            update_bots_file()
            respond "<@#{user.id}> extended the rules from #{CHANNEL} to be used on #{channel}.", @master_bot_id
            respond "Now the rules from <##{@channel_id}> are available on <##{@channels_id[channel]}>", dest
            respond "<@#{user.id}> extended the rules from <##{@channel_id}> to this channel so now you can talk to the Smart Bot on demand using those rules.", @channels_id[channel]
            respond "Use `!` before the command you want to run", @channels_id[channel]
            respond "To see the specific rules for this bot on this channel: `!bot rules`", @channels_id[channel]
          end
        end
      end

      #helpadmin: ----------------------------------------------
      #helpadmin: `stop using rules on CHANNEL_NAME`
      #helpadmin:    it will stop using the extended rules on the specified channel.
      #helpadmin:
    when /^stop using rules (on\s+)<#\w+\|(.+)>/i, /^stop using rules (on\s+)(.+)/i
      unless typem == :on_extended
        if !ADMIN_USERS.include?(from) #not admin 
          respond "Only admins can extend or stop using the rules. Admins on this channel: #{ADMIN_USERS}", dest
        else
          channel = $2
          get_bots_created()
          if @bots_created[@channel_id][:extended].include?(channel)
            @bots_created[@channel_id][:extended].delete(channel)
            update_bots_file()
            respond "<@#{user.id}> removed the access to the rules of #{CHANNEL} from #{channel}.", @master_bot_id
            respond "The rules won't be accessible from <##{@channels_id[channel]}> from now on.", dest
            respond "<@#{user.id}> removed the access to the rules of <##{@channel_id}> from this channel.", @channels_id[channel]
          else
            respond "The rules were not accessible from #{@channels_id[channel]}", dest
          end
        end
      end

    #help: ----------------------------------------------
    #help: `add shortcut NAME: COMMAND`
    #help: `add sc NAME: COMMAND`
    #help: `add shortcut for all NAME: COMMAND`
    #help: `add sc for all NAME: COMMAND`
    #help: `shortchut NAME: COMMAND`
    #help: `shortchut for all NAME: COMMAND`
    #help:    It will add a shortcut that will execute the command we supply.
    #help:    In case we supply 'for all' then the shorcut will be available for everybody
    #help:    Example:
    #help:        _add shortcut for all Spanish account: code require 'iso/iban'; 10.times {puts ISO::IBAN.random('ES')}_
    #help:    Then to call this shortcut:
    #help:        _sc spanish account_
    #help:        _shortcut Spanish Account_
    #help:        _Spanish Account_
    #help:
    when /^(add\s)?shortcut\s(for\sall)?\s*(.+)\s*:\s*(.+)/i, /^(add\s)sc\s(for\sall)?\s*(.+)\s*:\s*(.+)/i
      unless typem == :on_extended
        for_all = $2
        shortcut_name = $3.to_s.downcase
        command_to_run = $4
        @shortcuts[from] = Hash.new() unless @shortcuts.keys.include?(from)

        if !ADMIN_USERS.include?(from) and @shortcuts[:all].include?(shortcut_name) and !@shortcuts[from].include?(shortcut_name)
          respond "Only the creator of the shortcut or an admin user can modify it", dest
        elsif !@shortcuts[from].include?(shortcut_name)
          #new shortcut
          @shortcuts[from][shortcut_name] = command_to_run
          @shortcuts[:all][shortcut_name] = command_to_run if for_all.to_s != ""
          update_shortcuts_file()
          respond "shortcut added", dest
        else

          #are you sure? to avoid overwriting existing
          unless @questions.keys.include?(from)
            ask("The shortcut already exists, are you sure you want to overwrite it?", command, from, dest)
          else
            case @questions[from]
            when /^(yes|yep)/i
              @shortcuts[from][shortcut_name] = command_to_run
              @shortcuts[:all][shortcut_name] = command_to_run if for_all.to_s != ""
              update_shortcuts_file()
              respond "shortcut added", dest
              @questions.delete(from)
            when /^no/i
              respond "ok, I won't add it", dest
              @questions.delete(from)
            else
              respond "I don't understand, yes or no?", dest
            end
          end
        end
      end

      #help: ----------------------------------------------
      #help: `delete shortcut NAME`
      #help: `delete sc NAME`
      #help:    It will delete the shortcut with the supplied name
      #help:
    when /^delete\s+shortcut\s+(.+)/i, /^delete\s+sc\s+(.+)/i
      unless typem == :on_extended
        shortcut = $1.to_s.downcase
        deleted = false

        if !ADMIN_USERS.include?(from) and @shortcuts[:all].include?(shortcut) and !@shortcuts[from].include?(shortcut)
          respond "Only the creator of the shortcut or an admin user can delete it", dest
        elsif (@shortcuts.keys.include?(from) and @shortcuts[from].keys.include?(shortcut)) or
              (ADMIN_USERS.include?(from) and @shortcuts[:all].include?(shortcut))
          #are you sure? to avoid deleting by mistake
          unless @questions.keys.include?(from)
            ask("are you sure you want to delete it?", command, from, dest)
          else
            case @questions[from]
            when /^(yes|yep)/i
              respond "shortcut deleted!", dest
              respond "#{shortcut}: #{@shortcuts[from][shortcut]}", dest
              @shortcuts[from].delete(shortcut)
              @shortcuts[:all].delete(shortcut)
              @questions.delete(from)
              update_shortcuts_file()
            when /^no/i
              respond "ok, I won't delete it", dest
              @questions.delete(from)
            else
              respond "I don't understand, yes or no?", dest
            end
          end
        else
          respond "shortcut not found", dest
        end
      end

      #help: ----------------------------------------------
      #help: `see shortcuts`
      #help: `see sc`
      #help:    It will display the shortcuts stored for the user and for :all
      #help:
    when /^see\sshortcuts/i, /^see\ssc/i
      unless typem == :on_extended
        msg = ""
        if @shortcuts[:all].keys.size > 0
          msg = "*Available shortcuts for all:*\n"
          @shortcuts[:all].each { |name, value|
            msg += "    _#{name}: #{value}_\n"
          }
          respond msg, dest
        end

        if @shortcuts.keys.include?(from) and @shortcuts[from].keys.size > 0
          new_hash = @shortcuts[from].dup
          @shortcuts[:all].keys.each { |k| new_hash.delete(k) }
          if new_hash.keys.size > 0
            msg = "*Available shortcuts for #{from}:*\n"
            new_hash.each { |name, value|
              msg += "    _#{name}: #{value}_\n"
            }
            respond msg, dest
          end
        end
        respond "No shortcuts found", dest if msg == ""
      end

      #help: ----------------------------------------------
      #help: `id channel CHANNEL_NAME`
      #help:    shows the id of a channel name
      #help:
    when /^id\schannel\s<#C\w+\|(.+)>\s*/i, /^id channel (.+)/
      unless typem == :on_extended
        channel_name = $1
        get_channels_name_and_id()
        if @channels_id.keys.include?(channel_name)
          respond "the id of #{channel_name} is #{@channels_id[channel_name]}", dest
        else
          respond "channel: #{channel_name} not found", dest
        end
      end

      #help: ----------------------------------------------
      #help: `ruby RUBY_CODE`
      #help: `code RUBY_CODE`
      #help:     runs the code supplied and returns the output. Also you can send a Ruby file instead. Examples:
      #help:       _code puts (34344/99)*(34+14)_
      #help:       _ruby require 'json'; res=[]; 20.times {res<<rand(100)}; my_json={result: res}; puts my_json.to_json_
      #help:
    when /^\s*ruby\s(.+)/im, /^\s*code\s(.+)/im
      code = $1
      code.gsub!("\\n", "\n")
      code.gsub!("\\r", "\r")
      @logger.info code
      unless code.match?(/System/i) or code.match?(/Kernel/i) or code.include?("File") or
             code.include?("`") or code.include?("exec") or code.include?("spawn") or code.include?("IO.") or
             code.match?(/open3/i) or code.match?(/bundle/i) or code.match?(/gemfile/i) or code.include?("%x") or
             code.include?("ENV") or code.match?(/=\s*IO/)
        unless rules_file.empty?
          begin
            eval(File.new(rules_file).read) if File.exist?(rules_file)
          end
        end

        respond "Running", dest if code.size > 100

        begin
          code.gsub!(/^\W*$/,'') #to remove special chars from slack when copy/pasting
          ruby = "ruby -e \"#{code.gsub('"', '\"')}\""
          if defined?(project_folder) and project_folder.to_s!='' and Dir.exist?(project_folder)
            ruby = ("cd #{project_folder} &&" + ruby)
          else
            def project_folder() '' end
          end
          stdout, stderr, status = Open3.capture3(ruby)
          if stderr == ""
            if stdout == ""
              respond "Nothing returned. Remember you need to use p or puts to print", dest
            else
              respond stdout, dest
            end
          else
            respond stderr, dest
          end
        rescue Exception => exc
          respond exc, dest
        end
      else
        respond "Sorry I cannot run this due security reasons", dest
      end


    else
      processed2 = false
    end #of case

    processed = true if processed or processed2
  end

  return processed
end

#process_first(user, text, dest, dchannel, typem) ⇒ Object


328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/slack-smart-bot.rb', line 328

def process_first(user, text, dest, dchannel, typem)
  nick = user.name
  rules_file = ""

  if typem == :on_call
    rules_file = RULES_FILE

  elsif dest[0] == "C" or dest[0] == "G" # on a channel or private channel
    rules_file = RULES_FILE

    if @rules_imported.key?(user.id) and @rules_imported[user.id].key?(dchannel)
      unless @bots_created.key?(@rules_imported[user.id][dchannel])
        get_bots_created()
      end
      if @bots_created.key?(@rules_imported[user.id][dchannel])
        rules_file = @bots_created[@rules_imported[user.id][dchannel]][:rules_file]
      end
    end
  elsif dest[0] == "D" and @rules_imported.key?(user.id) and @rules_imported[user.id].key?(user.id) #direct message
    unless @bots_created.key?(@rules_imported[user.id][user.id])
      get_bots_created()
    end
    if @bots_created.key?(@rules_imported[user.id][user.id])
      rules_file = @bots_created[@rules_imported[user.id][user.id]][:rules_file]
    end
  end

  if nick == config[:nick] #if message is coming from the bot
    begin
      case text
      when /^Bot has been (closed|killed) by/i
        if CHANNEL == @channels_name[dchannel]
          @logger.info "#{nick}: #{text}"
          exit!
        end
      when /^Changed status on (.+) to :(.+)/i
        channel_name = $1
        status = $2
        if ON_MASTER_BOT or CHANNEL == channel_name
          @bots_created[@channels_id[channel_name]][:status] = status.to_sym
          update_bots_file()
          if CHANNEL == channel_name
            @logger.info "#{nick}: #{text}"
          else #on master bot
            @logger.info "Changed status on #{channel_name} to :#{status}"
          end
        end
      when /extended the rules from (.+) to be used on (.+)\.$/i
        from_name = $1
        to_name = $2
        if ON_MASTER_BOT and @bots_created[@channels_id[from_name]][:cloud]
          @bots_created[@channels_id[from_name]][:extended] << to_name
          @bots_created[@channels_id[from_name]][:extended].uniq!
          update_bots_file()
        end

      when /removed the access to the rules of (.+) from (.+)\.$/i
        from_name = $1
        to_name = $2
        if ON_MASTER_BOT and @bots_created[@channels_id[from_name]][:cloud]
          @bots_created[@channels_id[from_name]][:extended].delete(to_name)
          update_bots_file()
        end
        
      end

      return :next #don't continue analyzing
    rescue Exception => stack
      @logger.fatal stack
      return :next
    end
  end

  #only for shortcuts
  if text.match(/^@?(#{config[:nick]}):*\s+(.+)\s*/im) or
     text.match(/^()!\s*(.+)\s*/im) or
     text.match(/^()<@#{config[:nick_id]}>\s+(.+)\s*/im)
    command = $2
    addexcl = true
  else
    addexcl = false
    command = text.downcase.lstrip.rstrip
  end
  if command.scan(/^(shortcut|sc)\s+(.+)/i).any? or
     (@shortcuts.keys.include?(:all) and @shortcuts[:all].keys.include?(command)) or
     (@shortcuts.keys.include?(nick) and @shortcuts[nick].keys.include?(command))
    command = $2.downcase unless $2.nil?
    if @shortcuts.keys.include?(nick) and @shortcuts[nick].keys.include?(command)
      text = @shortcuts[nick][command].dup
    elsif @shortcuts.keys.include?(:all) and @shortcuts[:all].keys.include?(command)
      text = @shortcuts[:all][command].dup
    else
      respond "Shortcut not found", dest unless dest[0]=="C" and dchannel != dest #on extended channel
      return :next
    end
    text = "!" + text if addexcl and text[0] != "!"
  end

  if @questions.keys.include?(nick)
    command = @questions[nick]
    @questions[nick] = text
  else
    command = text
  end
  begin
    t = Thread.new do
      begin
        processed = process(user, command, dest, dchannel, rules_file, typem)
        @logger.info "command: #{nick}> #{command}" if processed
        on_demand = false
        if command.match(/^@?(#{config[:nick]}):*\s+(.+)/im) or
           command.match(/^()!(.+)/im) or
           command.match(/^()<@#{config[:nick_id]}>\s+(.+)/im)
          command = $2
          on_demand = true
        end
        if @status == :on and
           (@questions.keys.include?(nick) or
            (@listening.include?(nick) and typem!=:on_extended) or
            dest[0] == "D" or on_demand)
          @logger.info "command: #{nick}> #{command}" unless processed
          #todo: verify this

          if dest[0] == "C" or dest[0] == "G" or (dest[0]=="D" and typem==:on_call)
            if typem!=:on_call and @rules_imported.key?(user.id) and @rules_imported[user.id].key?(dchannel)
              if @bots_created.key?(@rules_imported[user.id][dchannel])
                if @bots_created[@rules_imported[user.id][dchannel]][:status] != :on
                  respond "The bot on that channel is not :on", dest
                  rules_file = ""
                end
              end
            end
            unless rules_file.empty?
              begin
                eval(File.new(rules_file).read) if File.exist?(rules_file)
              rescue Exception => stack
                @logger.fatal "ERROR ON RULES FILE: #{rules_file}"
                @logger.fatal stack
              end
              if defined?(rules)
                command[0] = "" if command[0] == "!"
                command.gsub!(/^@\w+:*\s*/, "")
                rules(user, command, processed, dest)
              else
                @logger.warn "It seems like rules method is not defined"
              end
            end
          elsif @rules_imported.key?(user.id) and @rules_imported[user.id].key?(user.id)
            if @bots_created.key?(@rules_imported[user.id][user.id])
              if @bots_created[@rules_imported[user.id][user.id]][:status] == :on
                begin
                  eval(File.new(rules_file).read) if File.exist?(rules_file)
                rescue Exception => stack
                  @logger.fatal "ERROR ON imported RULES FILE: #{rules_file}"
                  @logger.fatal stack
                end
              else
                respond "The bot on <##{@rules_imported[user.id][user.id]}|#{@bots_created[@rules_imported[user.id][user.id]][:channel_name]}> is not :on", dest
                rules_file = ""
              end
            end

            unless rules_file.empty?
              if defined?(rules)
                command[0] = "" if command[0] == "!"
                command.gsub!(/^@\w+:*\s*/, "")
                rules(user, command, processed, dest)
              else
                @logger.warn "It seems like rules method is not defined"
              end
            end
          else
            @logger.info "it is a direct message with no rules file selected so no rules file executed."
            unless processed
              resp = ["what", "huh", "sorry", "what do you mean", "I don't understand"].sample
              respond "#{resp}?", dest
            end
          end
        end
      rescue Exception => stack
        @logger.fatal stack
      end
    end
  rescue => e
    @logger.error "exception: #{e.inspect}"
  end
end

#respond(msg, dest = nil) ⇒ Object


1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
# File 'lib/slack-smart-bot.rb', line 1307

def respond(msg, dest = nil)
  if dest.nil?
    client.message(channel: @channel_id, text: msg, as_user: true)
  elsif dest[0] == "C" or dest[0] == "G" # channel
    client.message(channel: dest, text: msg, as_user: true)
  elsif dest[0] == "D" # Direct message
    send_msg_user(dest, msg)
  else
    @logger.warn("method respond not treated correctly: msg:#{msg} dest:#{dest}")
  end
end

#send_file(to, msg, file, title, format, type = "text") ⇒ Object

to send a file to an user or channel send_file(dest, 'the message', "##project_folder/temp/logs_ptBI.log", 'message to be sent', 'text/plain', "text") send_file(dest, 'the message', "##project_folder/temp/example.jpeg", 'message to be sent', 'image/jpeg', "jpg")


1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
# File 'lib/slack-smart-bot.rb', line 1363

def send_file(to, msg, file, title, format, type = "text")
  if to[0] == "U" #user
    im = client.web_client.im_open(user: to)
    channel = im["channel"]["id"]
  else
    channel = to
  end

  client.web_client.files_upload(
    channels: channel,
    as_user: true,
    file: Faraday::UploadIO.new(file, format),
    title: title,
    filename: file,
    filetype: type,
    initial_comment: msg,
  )
end

#send_msg_channel(to, msg) ⇒ Object

to: (String) Channel name or id msg: (String) message to send


1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
# File 'lib/slack-smart-bot.rb', line 1334

def send_msg_channel(to, msg)
  unless msg == ""
    get_channels_name_and_id() unless @channels_name.key?(to) or @channels_id.key?(to)
    if @channels_name.key?(to) #it is an id
      channel_id = to
    elsif @channels_id.key?(to) #it is a channel name
      channel_id = @channels_id[to]
    else
      @logger.fatal "Channel: #{to} not found. Message: #{msg}"
    end
    client.message(channel: channel_id, text: msg, as_user: true)
  end
end

#send_msg_user(id_user, msg) ⇒ Object

to send messages without listening for a response to users


1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
# File 'lib/slack-smart-bot.rb', line 1349

def send_msg_user(id_user, msg)
  unless msg == ""
    if id_user[0] == "D"
      client.message(channel: id_user, as_user: true, text: msg)
    else
      im = client.web_client.im_open(user: id_user)
      client.message(channel: im["channel"]["id"], as_user: true, text: msg)
    end
  end
end

#update_rules_importedObject


167
168
169
170
171
# File 'lib/slack-smart-bot.rb', line 167

def update_rules_imported
  file = File.open("./rules/rules_imported.rb", "w")
  file.write @rules_imported.inspect
  file.close
end