-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
1310 lines (1150 loc) · 60.9 KB
/
bot.py
File metadata and controls
1310 lines (1150 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
327
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
515
516
517
518
519
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
import os
import base64
import binascii
import re
import sys
import collections
import asyncio
import json
import aiofiles
import datetime
import aiohttp # Added for making HTTP requests
from unidecode import unidecode
from slack_bolt.async_app import AsyncApp
from slack_bolt.adapter.socket_mode.aiohttp import AsyncSocketModeHandler
from slack_sdk.errors import SlackApiError
ScheduledReply = collections.namedtuple('ScheduledReply', ['task', 'user_id'])
User = collections.namedtuple('User', ['id', 'name', 'real_name', 'team'])
Usergroup = collections.namedtuple('Usergroup', ['id', 'handle', 'name'])
Channel = collections.namedtuple('Channel', ['id', 'name', 'configs'])
DEFAULT_CONFIG_NAME = 'default'
DEFAULT_CONFIG = {
"wait_time": 30 * 60,
"reply_message": "Anybody?",
"opsgenie": False,
"debug": False,
"include_bots": False,
"excluded_teams": [],
"included_teams": [],
"only_work_days": False,
"hours": [],
"pattern": None,
"pattern_case_sensitive": False
}
EMPLOYEE_CACHE_FILE_NAME = os.environ.get('HUTBOT_EMPLOYEE_CACHE_FILE', 'employees.json')
CONFIG_FILE_NAME = os.environ.get('HUTBOT_CONFIG_FILE', 'bot.json')
TEAM_UNKNOWN = '<unknown>'
IGNORED_MESSAGE_SUBTYPES = set(['channel_join',
'channel_leave',
'channel_archived',
'channel_unarchived',
'channel_convert_to_private',
'channel_convert_to_public',
'channel_name',
'channel_posting_permissions',
'channel_purpose',
'channel_topic' ])
channel_config = {}
scheduled_messages = {}
user_id_cache = {}
id_user_cache = {}
usergroup_id_cache = {}
id_usergroup_cache = {}
team_cache = set()
bot_user_id = None
opsgenie_configured = False
MENTION_PATTERN = re.compile(r'(?<![|<])@([a-z0-9-_.]+)(?!>)')
ID_PATTERN = re.compile(r'<([#@!][a-zA-Z0-9^]+)([|]([^>]*))?>')
TIME_HOUR_PATTERN = re.compile(r"^[0-9]{1,2}$")
CONFIG_NAME_PATTERN = re.compile(r"^[A-Za-z0-9-_\.:/]+$")
TEMPLATE_VARIABLE_PATTERN = re.compile(r'{{\s*([a-z_][a-z0-9_]*)\s*}}')
SUPPORTED_TEMPLATE_VARIABLES = {
"channel",
"channel_name",
"config",
"message",
"message_link",
"team",
"timestamp",
"user",
"user_name",
"wait_minutes",
}
# Regex patterns for command parsing
def create_command_pattern(command_regex: str) -> re.Pattern:
return re.compile(f'^{command_regex}', re.IGNORECASE)
HELP_PATTERN = re.compile(r'help', re.IGNORECASE)
WHATSNEW_PATTERN = re.compile(r'news', re.IGNORECASE)
SET_WAIT_TIME_PATTERN = create_command_pattern(r'(set\s+)?wait([_ -]?time)?\s+(?P<wait_time>.+)')
SET_REPLY_MESSAGE_PATTERN = create_command_pattern(r'(set\s+)?(message|reply)\s+(?P<message>.+)')
SET_PATTERN_PATTERN = create_command_pattern(r'set\s+pattern\s+(?P<pattern>"[^"]*"|\'[^\']*\'|[^\r\n\t\f\v\s"\']+)(?:\s+(?P<case_sensitive>true|false|1|0))?')
ADD_EXCLUDED_TEAM_PATTERN = create_command_pattern(r'(add\s+)?excluded?([_ -]?teams?)?\s+(?P<team>.+)')
CLEAR_EXCLUDED_TEAM_PATTERN = create_command_pattern(r'clear\s+excluded?([_ -]?teams?)?')
ADD_INCLUDED_TEAM_PATTERN = create_command_pattern(r'(add\s+)?included?([_ -]?teams?)?\s+(?P<team>.+)')
CLEAR_INCLUDED_TEAM_PATTERN = create_command_pattern(r'clear\s+included?([_ -]?teams?)?')
LIST_TEAMS_PATTERN = re.compile(r'^(list\s+)?teams?$', re.IGNORECASE)
EMPLOYEE_TEAM_PATTERN = re.compile(r'^team(\s+of)?\s+(?P<user>.+)$', re.IGNORECASE)
ENABLE_OPSGENIE_PATTERN = create_command_pattern(r'enable\s+(opsgenie|alerts?)')
DISABLE_OPSGENIE_PATTERN = create_command_pattern(r'disable\s+(opsgenie|alerts?)')
ENABLE_BOTS_PATTERN = create_command_pattern(r'(enable|include|set)?\s+bots?')
DISABLE_BOTS_PATTERN = create_command_pattern(r'(disable|exclude)\s+bots?')
SET_WORK_HOURS_PATTERN = create_command_pattern(r'(set\s+)?(work[_ -]?)?hours\s+(?P<start>.+)\s+(?P<end>.+)')
ENABLE_ONLY_WORK_DAYS_PATTERN = create_command_pattern(r'enable\s+(only[_ -]?)?work[_ -]?days')
DISABLE_ONLY_WORK_DAYS_PATTERN = create_command_pattern(r'disable\s+(only[_ -]?)?work[_ -]?days')
SHOW_CONFIG_PATTERN = re.compile(r'^(show\s+)?config(uration)?$', re.IGNORECASE)
DELETE_CONFIG_PATTERN = create_command_pattern(r'delete\s+config\s+(?P<name>.+)')
def load_env_file() -> None:
env_file_path = os.path.join(os.path.dirname(__file__), '.env')
if not os.path.exists(env_file_path):
return
with open(env_file_path) as file:
for line in file:
line = line.strip()
if not line or line.startswith('#'):
continue
# remove "export " from the start of the line
if line.startswith('export '):
line = line[7:]
# Split key-value pairs
key, sep, value = line.partition('=')
if sep != '=':
continue # Skip malformed lines
# Remove surrounding quotes from the value if present
key = key.strip()
value = value.strip().strip('\'"')
# Set the environment variable
os.environ[key] = value
def _decode_env_value(value: str) -> str:
try:
decoded = base64.b64decode(value, validate=True).decode('utf-8')
return decoded
except (binascii.Error, UnicodeDecodeError):
return value
def get_env_var(name: str, default: str = "") -> str:
raw = os.environ.get(name, default)
if raw is None:
return default
return _decode_env_value(raw)
def log(*args: object) -> None:
__log(sys.stdout, 'INFO', *args)
def log_warning(*args: object) -> None:
__log(sys.stderr, 'WARN', *args)
def log_error(*args: object) -> None:
__log(sys.stderr, 'ERROR', *args)
def log_debug(channel: Channel | None, *args: object) -> None:
if channel and any(c.get('debug') for c in channel.configs.values()):
__log(sys.stderr, 'DEBUG', *args)
def __log(file, prefix, *args: object) -> None:
parts = []
for arg in args:
part = str(arg)
if isinstance(arg, BaseException):
error_type = type(arg).__name__
error_message = str(arg)
part = f"{error_type}{': ' + error_message if error_message else ''}"
parts.append(part)
message = ' '.join(parts)
prefix = f"{datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')} {prefix}:"
print(prefix, message, flush=True, file=file)
def strip_quotes(text: str) -> str:
if text and ((text.startswith('"') and text.endswith('"')) or (text.startswith("'") and text.endswith("'"))):
text = text[1:-1]
return text
def normalize_id(id: str) -> str: return id.lower().strip()
def normalize_user_name(user_name: str) -> str: return user_name.lower().strip().replace('.', '')
def normalize_real_name(real_name: str) -> str:
normalized = real_name.lower().strip().replace(' ', '_').replace('.', '_')
# replace non latin characters
normalized = unidecode(normalized)
return normalized
def normalize_real_name_with_diagraphs(real_name: str) -> str:
# don't ask, you wouldn't be able to grasp the extend...
return normalize_real_name(real_name.lower().replace('ae', 'ä').replace('oe', 'ö').replace('ue', 'ü'))
async def migrate_and_apply_defaults(app: AsyncApp, config: dict) -> dict:
for channel_id, channel_data in config.items():
# Migration for old format
# old format: "C1234": { "wait_time": 60, ... }
# new format: "C1234": { "default": { "wait_time": 60, ... } }
is_flat_config = any(k in DEFAULT_CONFIG for k in channel_data.keys())
if is_flat_config:
# This looks like an old, flat config. Let's wrap it.
log(f"Migrating old configuration for channel {channel_id}")
channel_data = {DEFAULT_CONFIG_NAME: channel_data}
config[channel_id] = channel_data
for config_name, single_config in channel_data.items():
for key, value in DEFAULT_CONFIG.items():
if key not in single_config:
single_config[key] = value
return config
async def load_configuration(app: AsyncApp) -> None:
global channel_config
try:
async with aiofiles.open(CONFIG_FILE_NAME, 'r') as f:
content = await f.read()
loaded_config = json.loads(content)
channel_config = await migrate_and_apply_defaults(app, loaded_config)
log("Configuration loaded from disk.")
except FileNotFoundError:
log_warning("No configuration file found. Using default settings.")
channel_config = {}
except json.JSONDecodeError as e:
log_error(f"Failed to decode JSON configuration:", e)
channel_config = {}
async def save_configuration() -> None:
try:
async with aiofiles.open(CONFIG_FILE_NAME, 'w') as f:
content = json.dumps(channel_config, indent=2)
await f.write(content)
except Exception as e:
log_error("Failed to save configuration:", e)
def generate_employee_list(users: list) -> dict:
employees = {}
for user in users:
id = normalize_id(user.get('ad_name', ''))
is_deleted = user.get('is_deleted', False)
if not is_deleted and len(id) > 0:
employees[id] = user
return employees
def load_employee_mappings() -> dict:
result = {}
employee_mappings = get_env_var("EMPLOYEE_LIST_MAPPINGS", "").strip()
if employee_mappings:
log(f"Attempting to load employee mappings from environment variable.")
mappings = employee_mappings.split(',')
for mapping in mappings:
items = mapping.split('=')
if items and len(items) == 2 and len(items[0]) > 0 and len(items[1]) > 0:
key = normalize_id(items[0])
value = normalize_id(items[1])
if key in result:
log_warning(f"Failed to parse employee mapping '{key}' is already mapped, skipping")
else:
result[key] = value
else:
log_warning(f"Failed to parse employee mapping '{mapping}', skipping")
log(f"{len(result)} employee mappings loaded from environment variable.")
return result
async def load_employees_from_disk() -> dict:
log(f"Attempting to load employees from disk.")
try:
async with aiofiles.open(EMPLOYEE_CACHE_FILE_NAME, 'r') as f:
content = await f.read()
users = json.loads(content)
employees = generate_employee_list(users)
log(f"{len(employees)} employees loaded from disk.")
return employees
except FileNotFoundError:
log_error("No employee file found. Will not be able to do team mapping.")
except json.JSONDecodeError as e:
log_error(f"Failed to decode employee JSON:", e, "Will not be able to do team mapping.")
return {}
async def save_employees_to_disk(users: list) -> None:
try:
async with aiofiles.open(EMPLOYEE_CACHE_FILE_NAME, 'w') as f:
await f.write(json.dumps(users, indent=2))
except Exception as e:
log_error("Failed to save employees to disk:", e)
async def load_employees() -> dict:
username = get_env_var("EMPLOYEE_LIST_USERNAME")
password = get_env_var("EMPLOYEE_LIST_PASSWORD")
if not username or not password:
return await load_employees_from_disk()
employee_auth_url = 'https://identity.prod.mittwald.systems/authenticate'
employee_url = 'https://lb.mittwald.it/api/users'
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session:
auth_payload = {
"username": username,
"password": password,
"providers": ["service"]
}
async with session.post(employee_auth_url, json=auth_payload) as auth_response:
if auth_response.status != 200:
log_error(f"Failed to authenticate to retrieve employees: {await auth_response.text()}")
return await load_employees_from_disk()
token = (await auth_response.text()).strip()
if not token:
log_error(f"Failed to authenticate to retrieve employees, no token received: {token!r}")
return await load_employees_from_disk()
headers = {"jwt": token}
async with session.get(employee_url, headers=headers) as users_response:
if users_response.status != 200:
log_error(f"Failed to fetch employees: {await users_response.text()}")
return await load_employees_from_disk()
users = await users_response.json()
employees = generate_employee_list(users)
log(f"{len(employees)} employees retrieved from {employee_url}.")
await save_employees_to_disk(users)
return employees
except Exception as e:
log_error(f"Failed to retrieve employees from {employee_url}:", e)
return await load_employees_from_disk()
async def get_channel_by_id(app: AsyncApp, channel_id: str) -> Channel:
global channel_config
if channel_id not in channel_config:
channel_config[channel_id] = {}
name = await get_channel_name(app, channel_id)
configs = channel_config[channel_id]
return Channel(id=channel_id, name=name, configs=configs)
async def get_channel_name(app: AsyncApp, channel_id: str) -> str:
try:
response = await app.client.conversations_info(channel=channel_id)
channel_name = response.get('channel', {}).get('name', '')
if channel_name:
return channel_name
except SlackApiError as e:
log_error(f"Failed to get channel name for {channel_id}", e)
return channel_id
async def get_message_permalink(app: AsyncApp, channel: Channel, ts: str) -> str:
permalink = ""
try:
response = await app.client.chat_getPermalink(
channel=channel.id,
message_ts=ts
)
permalink = response.get('permalink', '')
except SlackApiError as e:
log_error(f"Failed to get permalink for message {ts} in channel #{channel.name}:", e)
return permalink
async def update_usergroup_cache(app: AsyncApp) -> None:
global usergroup_id_cache, id_usergroup_cache
if not usergroup_id_cache or not id_usergroup_cache:
try:
response = await app.client.usergroups_list()
usergroups = response['usergroups']
for usergroup in usergroups:
if usergroup.get('date_deleted', 0) == 0:
usergroup_id = usergroup.get('id', '')
usergroup_handle = usergroup.get('handle', '')
usergroup_name = usergroup.get('name', '')
usergroup_id_cache[usergroup_handle] = Usergroup(id=usergroup_id, handle=usergroup_handle, name=usergroup_name)
id_usergroup_cache[usergroup_id] = Usergroup(id=usergroup_id, handle=usergroup_handle, name=usergroup_name)
except SlackApiError as e:
log_error(f"Failed to fetch usergroup list:", e)
async def update_user_cache(app: AsyncApp) -> None:
global user_id_cache, id_user_cache
if not user_id_cache or not id_user_cache:
employees = await load_employees()
mappings = load_employee_mappings()
try:
response = await app.client.users_list()
users = response['members']
for user in users:
if not user.get('deleted') and \
not user.get('is_bot', False) and \
not user.get('is_restricted', False) and \
user.get('id', '') != 'USLACKBOT':
user_id = user.get('id', '')
user_name = normalize_id(user.get('name', ''))
if user_name in mappings:
log(f"Applying employee mapping: {user_name} -> {mappings[user_name]}")
user_name = mappings[user_name]
user_name_normalized = normalize_user_name(user_name)
user_email = normalize_id(user.get('profile', {}).get('email', ''))
user_email_alias = normalize_id(user_email.split('@')[0])
user_email_alias_normalized = normalize_user_name(user_email_alias)
user_real_name = user.get('real_name', '').strip()
user_real_name_normalized = normalize_real_name(user_real_name)
user_team = TEAM_UNKNOWN
if len(employees) > 0:
# Try different variations of the username to find a match in employees
user_key_candidates = [
user_name,
user_name_normalized,
user_email_alias,
user_email_alias_normalized
]
user_key = next((k for k in user_key_candidates if k in employees), None)
if not user_key:
# loop through all employees and try to match some form of the real name
for employee_key, employee in employees.items():
employee_real_name = employee.get('fullname', '').strip()
employee_real_name_normalized = normalize_real_name(employee_real_name)
employee_real_name_super_normalized = normalize_real_name_with_diagraphs(employee_real_name)
user_real_name_super_normalized = normalize_real_name_with_diagraphs(user_real_name)
if employee_real_name_normalized == user_real_name_normalized or \
employee_real_name_super_normalized == user_real_name_normalized or \
employee_real_name_super_normalized == user_real_name_super_normalized:
user_key = employee_key
# finally!
break
if not user_key:
user_json = json.dumps(user)
if len(user_json) > 100:
user_json = user_json[:97] + '...'
log_warning(f"Failed to map user @{user_name} to a employee: {user_json}")
if user_key:
user_team = employees[user_key].get('group', '').strip()
user_id_cache[user_name] = User(id=user_id, name=user_name, team=user_team, real_name=user_real_name)
id_user_cache[user_id] = User(id=user_id, name=user_name, team=user_team, real_name=user_real_name)
if user_team not in team_cache:
team_cache.add(user_team)
except SlackApiError as e:
log_error(f"Failed to fetch user list:", e)
async def get_user_by_id(app: AsyncApp, id: str) -> User:
await update_user_cache(app)
user = id_user_cache.get(id, None)
if not user:
user = User(id=id, name=id, team=TEAM_UNKNOWN, real_name='')
return user
async def get_user_by_name(app: AsyncApp, name: str) -> User:
await update_user_cache(app)
user = user_id_cache.get(name, None)
if not user:
user = User(id=None, name=name, team=TEAM_UNKNOWN, real_name='')
return user
async def get_usergroup_by_id(app: AsyncApp, id: str) -> Usergroup:
await update_usergroup_cache(app)
usergroup = id_usergroup_cache.get(id, None)
if not usergroup:
usergroup = Usergroup(id=id, handle=id, name=id)
return usergroup
async def get_usergroup_by_handle(app: AsyncApp, handle: str) -> Usergroup:
await update_usergroup_cache(app)
usergroup = usergroup_id_cache.get(handle, None)
if not usergroup:
usergroup = Usergroup(id=None, handle=handle, name=handle)
return usergroup
def is_work_day() -> bool:
today = datetime.date.today()
# TODO: add holidays
return today.weekday() < 5
def is_work_time(start_time_str: str, end_time_str: str) -> bool:
now = datetime.datetime.now()
start = parse_time(start_time_str)
end = parse_time(end_time_str)
if not start or not end:
log_error(f"Invalid time format {start_time_str} - {end_time_str}")
return True
start_today = datetime.datetime.combine(now.date(), start)
end_today = datetime.datetime.combine(now.date(), end)
return start_today < now < end_today
def is_command(text: str) -> bool:
return f"<@{bot_user_id}>" in text
async def parse_and_execute_command(app: AsyncApp, command_text: str, channel: Channel, config_name: str, user: User, thread_ts: str = "") -> bool:
"""Parses and executes a command, returns True if a command was matched."""
if (match := SET_WAIT_TIME_PATTERN.match(command_text)):
wait_time_minutes = int(strip_quotes(match.group("wait_time")))
await set_wait_time(app, channel, config_name, wait_time_minutes, user, thread_ts)
elif (match := SET_REPLY_MESSAGE_PATTERN.match(command_text)):
message = strip_quotes(match.group("message"))
await set_reply_message(app, channel, config_name, message, user, thread_ts)
elif (match := SET_PATTERN_PATTERN.match(command_text)):
pattern = match.group("pattern")
case_sensitive = match.group("case_sensitive")
await set_pattern(app, channel, config_name, pattern, case_sensitive, user, thread_ts)
elif (match := ENABLE_OPSGENIE_PATTERN.match(command_text)):
await set_opsgenie(app, channel, config_name, True, user, thread_ts)
elif (match := DISABLE_OPSGENIE_PATTERN.match(command_text)):
await set_opsgenie(app, channel, config_name, False, user, thread_ts)
elif (match := ENABLE_BOTS_PATTERN.match(command_text)):
await set_bots(app, channel, config_name, True, user, thread_ts)
elif (match := DISABLE_BOTS_PATTERN.match(command_text)):
await set_bots(app, channel, config_name, False, user, thread_ts)
elif (match := ENABLE_ONLY_WORK_DAYS_PATTERN.match(command_text)):
await set_only_work_days(app, channel, config_name, True, user, thread_ts)
elif (match := DISABLE_ONLY_WORK_DAYS_PATTERN.match(command_text)):
await set_only_work_days(app, channel, config_name, False, user, thread_ts)
elif (match := SET_WORK_HOURS_PATTERN.match(command_text)):
start = strip_quotes(match.group("start"))
end = strip_quotes(match.group("end"))
await set_work_hours(app, channel, config_name, start, end, user, thread_ts)
elif LIST_TEAMS_PATTERN.match(command_text):
await list_teams(app, channel, user, thread_ts)
elif (match := EMPLOYEE_TEAM_PATTERN.match(command_text)):
username = strip_quotes(match.group("user"))
await get_team_of(app, channel, username, user, thread_ts)
elif (match := ADD_EXCLUDED_TEAM_PATTERN.match(command_text)):
team = strip_quotes(match.group("team"))
await add_excluded_team(app, channel, config_name, team, user, thread_ts)
elif (match := CLEAR_EXCLUDED_TEAM_PATTERN.match(command_text)):
await clear_excluded_team(app, channel, config_name, user, thread_ts)
elif (match := ADD_INCLUDED_TEAM_PATTERN.match(command_text)):
team = strip_quotes(match.group("team"))
await add_included_team(app, channel, config_name, team, user, thread_ts)
elif (match := CLEAR_INCLUDED_TEAM_PATTERN.match(command_text)):
await clear_included_team(app, channel, config_name, user, thread_ts)
elif (match := DELETE_CONFIG_PATTERN.match(command_text)):
name = strip_quotes(match.group("name"))
await delete_config(app, channel, name, user, thread_ts)
elif SHOW_CONFIG_PATTERN.match(command_text):
await show_config(app, channel, user, thread_ts)
elif HELP_PATTERN.match(command_text):
await send_help_message(app, channel, user, thread_ts)
elif WHATSNEW_PATTERN.match(command_text):
await send_news_message(app, channel, user, thread_ts)
else:
return False
return True
async def process_command(app: AsyncApp, text: str, channel: Channel, user: User, thread_ts: str = "") -> None:
text = text.replace(f"<@{bot_user_id}>", "").strip()
log_debug(channel, f"Received command for channel #{channel.name}: {text}")
# First, try to parse the command with the default config.
if await parse_and_execute_command(app, text, channel, DEFAULT_CONFIG_NAME, user, thread_ts):
return
# If that fails, assume the first part is a config name.
parts = text.split()
if len(parts) > 1:
config_name = parts[0]
command_text = " ".join(parts[1:])
if not CONFIG_NAME_PATTERN.match(config_name):
await send_message(app, channel, user, f"Invalid config name: `{config_name}`. Only characters `A-Z`, `a-z`, `0-9`, `.`, `:`, `/`, `-`, `_` are allowed.", thread_ts)
return
if await parse_and_execute_command(app, command_text, channel, config_name, user, thread_ts):
return
await send_message(app, channel, user, "Huh? :thinking_face: Maybe type `/hutbot help` for a list of commands.", thread_ts)
async def set_bots(app: AsyncApp, channel: Channel, config_name: str, enabled: bool, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
channel.configs[config_name]['include_bots'] = enabled
await save_configuration()
await send_message(app, channel, user, f"*Bot messages* will {'also be *handled*' if enabled else 'be *ignored*'} in configuration `{config_name}`.", thread_ts)
async def set_only_work_days(app: AsyncApp, channel: Channel, config_name: str, enabled: bool, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
channel.configs[config_name]['only_work_days'] = enabled
await save_configuration()
await send_message(app, channel, user, f"Messages will be handled {'*only on work days*' if enabled else '*on all days*'} in configuration `{config_name}`.", thread_ts)
def parse_time(time_str) -> datetime.time | None:
if TIME_HOUR_PATTERN.match(time_str):
time_str = f"{time_str}:00"
time = None
try:
time = datetime.datetime.strptime(time_str, "%H:%M").time()
except ValueError:
pass
return time
async def set_work_hours(app: AsyncApp, channel: Channel, config_name: str, start: str, end: str, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
start_time = parse_time(start)
end_time = parse_time(end)
if not start_time:
await send_message(app, channel, user, f"Invalid time format `{start}`.", thread_ts)
return
if not end_time:
await send_message(app, channel, user, f"Invalid time format `{end}`.", thread_ts)
return
hours = [start_time.strftime("%H:%M"), end_time.strftime("%H:%M")]
if hours[0] == "00:00" and hours[1] == "00:00":
hours = []
channel.configs[config_name]['hours'] = hours
await save_configuration()
await send_message(app, channel, user, f"*Work hours* set to {f'`{hours[0]}` - `{hours[1]}`' if len(hours) == 2 else 'all day'} in configuration `{config_name}`", thread_ts)
async def set_opsgenie(app: AsyncApp, channel: Channel, config_name: str, enabled: bool, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
channel.configs[config_name]['opsgenie'] = enabled
await save_configuration()
await send_message(app, channel, user, f"*OpsGenie integration* {'*enabled*' if enabled else '*disabled*'}{', but not configured' if enabled and not opsgenie_configured else ''} in configuration `{config_name}`.", thread_ts)
async def set_wait_time(app: AsyncApp, channel: Channel, config_name: str, wait_time_minutes: int, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
# check if number and in range 0-1440
if not wait_time_minutes or wait_time_minutes < 0 or wait_time_minutes > 1440:
await send_message(app, channel, user, "Invalid wait time. Must be a number between 0 and 1440.", thread_ts)
return
channel.configs[config_name]['wait_time'] = wait_time_minutes * 60 # Convert to seconds
log_debug(channel, f"Wait time for #{channel.name} set to {wait_time_minutes} minutes for configuration `{config_name}`")
await save_configuration()
await send_message(app, channel, user, f"*Wait time* set to `{wait_time_minutes}` minutes in configuration `{config_name}`.", thread_ts)
def find_unknown_template_variables(message: str) -> list[str]:
variables = {match.group(1) for match in TEMPLATE_VARIABLE_PATTERN.finditer(message)}
return sorted(variable for variable in variables if variable not in SUPPORTED_TEMPLATE_VARIABLES)
def render_reply_message_template(message: str, variables: dict[str, str]) -> str:
def replace_variable(match: re.Match) -> str:
variable = match.group(1)
return variables.get(variable, match.group(0))
return TEMPLATE_VARIABLE_PATTERN.sub(replace_variable, message)
async def set_reply_message(app: AsyncApp, channel: Channel, config_name: str, message: str, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
# check message
if not message or message.strip() == "":
await send_message(app, channel, user, "Invalid *reply message*. Must be non-empty.", thread_ts)
return
ok, error, message = await process_mentions(app, message)
if not ok:
await send_message(app, channel, user, "Invalid *reply message*: " + error + ".", thread_ts)
return
unknown_variables = find_unknown_template_variables(message)
if unknown_variables:
await send_message(
app,
channel,
user,
"Invalid *reply message*: unsupported template variable(s) "
+ ", ".join(f"`{{{{{variable}}}}}`" for variable in unknown_variables)
+ ". Supported variables: "
+ ", ".join(f"`{{{{{variable}}}}}`" for variable in sorted(SUPPORTED_TEMPLATE_VARIABLES))
+ ".",
thread_ts
)
return
channel.configs[config_name]['reply_message'] = message
await save_configuration()
await send_message(app, channel, user, f"*Reply message* set to: {message} in configuration `{config_name}`.", thread_ts)
async def set_pattern(app: AsyncApp, channel: Channel, config_name: str, pattern_str: str, case_sensitive_str: str | None, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
pattern_str = strip_quotes(pattern_str)
# Validate the regex pattern
try:
re.compile(pattern_str)
except re.error as e:
await send_message(app, channel, user, f"Invalid pattern: `{e}`", thread_ts)
return
case_sensitive = case_sensitive_str is not None and case_sensitive_str.lower() in ['true', '1']
channel.configs[config_name]['pattern'] = pattern_str
channel.configs[config_name]['pattern_case_sensitive'] = case_sensitive
await save_configuration()
message = f"Pattern set to `{pattern_str}` for configuration `{config_name}`."
if case_sensitive:
message += " (case-sensitive)"
else:
message += " (case-insensitive)"
await send_message(app, channel, user, message, thread_ts)
async def delete_config(app: AsyncApp, channel: Channel, config_name: str, user: User, thread_ts: str = "") -> None:
if config_name == DEFAULT_CONFIG_NAME:
await send_message(app, channel, user, f"The `{DEFAULT_CONFIG_NAME}` configuration cannot be deleted.", thread_ts)
return
if config_name not in channel.configs:
await send_message(app, channel, user, f"Configuration `{config_name}` not found.", thread_ts)
return
del channel.configs[config_name]
await save_configuration()
await send_message(app, channel, user, f"Configuration `{config_name}` has been deleted.", thread_ts)
async def process_mentions(app: AsyncApp, message: str) -> tuple[bool, str, str]:
# Regular expression to find @username patterns
matches = MENTION_PATTERN.findall(message)
if matches:
for user_match in matches:
user = await get_user_by_name(app, user_match)
if user.id:
message = message.replace(f"@{user_match}", f"<@{user.id}>")
else:
log_error(f"Invalid *reply message*: username `{user_match}` not found")
return False, f"{user_match} not found", ""
return True, "", message
async def add_excluded_team(app: AsyncApp, channel: Channel, config_name: str, team: str, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
config = channel.configs[config_name]
await update_user_cache(app)
if team not in team_cache:
await send_message(app, channel, user, f"Unknown team: `{team}`.", thread_ts)
return
if team in config['excluded_teams']:
await send_message(app, channel, user, f"`{team}` is already excluded in configuration `{config_name}`.", thread_ts)
return
if len(config['included_teams']) > 0:
await send_message(app, channel, user, f"Either set *included teams* or *excluded teams*, not both, in configuration `{config_name}`.", thread_ts)
return
config['excluded_teams'].append(team)
await save_configuration()
await send_message(app, channel, user, f"Added `{team}` to *excluded teams* in configuration `{config_name}`.", thread_ts)
async def clear_excluded_team(app: AsyncApp, channel: Channel, config_name: str, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
channel.configs[config_name]['excluded_teams'] = []
await save_configuration()
await send_message(app, channel, user, f"Cleared *excluded teams* in configuration `{config_name}`.", thread_ts)
async def add_included_team(app: AsyncApp, channel: Channel, config_name: str, team: str, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
config = channel.configs[config_name]
await update_user_cache(app)
if team not in team_cache:
await send_message(app, channel, user, f"Unknown team: `{team}`.", thread_ts)
return
if team in config['included_teams']:
await send_message(app, channel, user, f"`{team}` is already included in configuration `{config_name}`.", thread_ts)
return
if len(config['excluded_teams']) > 0:
await send_message(app, channel, user, f"Either set *included teams* or *excluded teams*, not both, in configuration `{config_name}`.", thread_ts)
return
config['included_teams'].append(team)
await save_configuration()
await send_message(app, channel, user, f"Added `{team}` to *included teams* in configuration `{config_name}`.", thread_ts)
async def clear_included_team(app: AsyncApp, channel: Channel, config_name: str, user: User, thread_ts: str = "") -> None:
if config_name not in channel.configs:
channel.configs[config_name] = DEFAULT_CONFIG.copy()
channel.configs[config_name]['included_teams'] = []
await save_configuration()
await send_message(app, channel, user, f"Cleared *included teams* in configuration `{config_name}`.", thread_ts)
async def list_teams(app: AsyncApp, channel: Channel, user: User, thread_ts: str = "") -> None:
await update_user_cache(app)
message = f"*Available teams*:\n{'\n'.join(sorted(team_cache, key=lambda v: v.upper()))}"
await send_message(app, channel, user, message, thread_ts)
async def get_team_of(app: AsyncApp, channel: Channel, username: str, user: User, thread_ts: str = "") -> None:
message = None
log_debug(channel, f"Looking up users from message `{username}`...")
for match in ID_PATTERN.finditer(username):
full_match = match.group(0)
log_debug(channel, f"Found ID match: {full_match}...")
id = match.group(1)
if id and id[0] == '@':
user_id = id[1:]
log_debug(channel, f"Looking up user with ID {user_id}...")
u = await get_user_by_id(app, user_id)
if u.id:
log_debug(channel, f"Found user {u}")
msg = f"*{u.real_name}* (<@{u.id}>): `{u.team}`"
if message is None:
message = msg
else:
message += f"\n{msg}"
else:
log_error(f"Invalid request: username `{full_match}` not found")
if message:
await send_message(app, channel, user, message, thread_ts)
else:
await send_message(app, channel, user, f"Unknown user: `{username}`.", thread_ts)
async def show_config(app: AsyncApp, channel: Channel, user: User, thread_ts: str = "") -> None:
if not channel.configs:
message = f"There is no configuration for #{channel.name}."
await send_message(app, channel, user, message, thread_ts)
return
message = f"This is the configuration for #{channel.name}:"
for config_name, config in sorted(channel.configs.items()):
opsgenie_enabled = config.get('opsgenie')
wait_time_minutes = config.get('wait_time') // 60
included_teams = config.get('included_teams')
excluded_teams = config.get('excluded_teams')
include_bots = config.get('include_bots')
only_work_days = config.get('only_work_days')
hours = config.get('hours')
pattern = config.get('pattern')
pattern_case_sensitive = config.get('pattern_case_sensitive')
reply_message = config.get('reply_message')
message += (
f"\n\n---\n*Configuration*: `{config_name}`\n\n"
f"*OpsGenie integration*: {'enabled' if opsgenie_enabled else 'disabled'}"
f"{'' if opsgenie_configured else ' (not configured)'}\n\n"
f"*Wait time*: `{wait_time_minutes}` minutes\n\n"
f"*Included teams*: {' '.join(f'`{team}`' for team in included_teams) if included_teams else '<None>'}\n\n"
f"*Excluded teams*: {' '.join(f'`{team}`' for team in excluded_teams) if excluded_teams else '<None>'}\n\n"
f"*Include bots*: {'enabled' if include_bots else 'disabled'}\n\n"
f"*Only work days*: {'enabled' if only_work_days else 'disabled'}\n\n"
f"*Work hours*: {f'`{hours[0]}` - `{hours[1]}`' if len(hours) == 2 else 'all day'}\n\n"
f"*Pattern*: {f'`{pattern}` (case-sensitive)' if pattern_case_sensitive else f'`{pattern}` (case-insensitive)' if pattern else '<None>'}\n\n"
f"*Reply message*:\n{reply_message}"
)
await send_message(app, channel, user, message, thread_ts)
async def send_message(app: AsyncApp, channel: Channel, user: User, text: str, thread_ts: str = "") -> None:
log_debug(channel, f"Attempting to send message to #{channel.name}, user @{user.name}: {text.replace('\n', '\\n')}")
retries = 3
delay = 1
for attempt in range(retries):
try:
if thread_ts:
await app.client.chat_postMessage(
channel=channel.id,
thread_ts=thread_ts,
text=text,
mrkdwn=True
)
else:
await app.client.chat_postEphemeral(
channel=channel.id,
user=user.id,
text=text,
mrkdwn=True
)
log_debug(channel, f"Successfully sent message to #{channel.name}, user @{user.name}")
return # Exit if successful
except SlackApiError as e:
if attempt < retries - 1:
log_warning(f"Failed to send message in channel #{channel.name}, user @{user.name}, retrying in {delay} seconds ({attempt + 1}/{retries})...", e)
await asyncio.sleep(delay)
delay *= 2 # Exponential backoff
else:
log_error(f"Failed to send message in channel #{channel.name}, user @{user.name} after {retries} attempts:", e)
async def send_news_message(app: AsyncApp, channel: Channel, user: User, thread_ts: str = "") -> None:
update_text = (
"Hi! :wave: I am *Hutbot* :palm_up_hand::tophat: Here's what's :new::\n\n"
"> * :sparkles: Now I can also handle multiple configurations per channel* :partying_face:\n>\n"
"> Now you can *optionally specify a config name* for commands to edit a specific configuration.\n"
"> There can be an *unlimited number of configurations per channel*. :rocket:\n>\n"
f"> All channels have a `{DEFAULT_CONFIG_NAME}` config, which also holds the previous configuration.\n>\n"
f"> *Commands work like before.* By omitting the config name, you'll edit `{DEFAULT_CONFIG_NAME}`.\n>\n"
"> :thinking_face: *Why?* :bulb: One use case would be to configure reply messages for *bi-directional communication*.\n>\n"
"> *1.* Team A sends a message without a response :arrow_right: B is notified.\n"
"> *2.* Team B sends a message without a response :arrow_right: A is notified.\n>\n"
"> Also, you could specify a *regex pattern to only respond to certain messages* :new:.\n"
"> *1.* When a message contains `.*sales.*` :arrow_right: sales team is notified.\n"
"> *2.* When a message contains `.*customer.*` :arrow_right: customer service team is notified.\n>\n"
"> You want to get rid of a config? :trash: Use `/hutbot delete config <config>`.\n>\n"
"> Maybe I could also do some AI magic here in the future? :sparkles:\n"
)
await send_message(app, channel, user, update_text, thread_ts)
async def send_help_message(app: AsyncApp, channel: Channel, user: User, thread_ts: str = "") -> None:
help_text = (
"Hi! :wave: I am *Hutbot* :palm_up_hand::tophat: Here's how you can configure me via /command or @mention:\n\n"
"*Show All Configurations:*\n"
"> Either use the command `/hutbot` or just @Hutbot me.\n"
"```/hutbot show config\n"
"@Hutbot show config```\n"
f"Displays all configurations for #{channel.name}.\n\n"
"*Enable OpsGenie Integration:*\n"
"```/hutbot [config] enable opsgenie```\n"
"Enables the OpsGenie integration.\n\n"
"*Disable OpsGenie Integration:*\n"
"```/hutbot [config] disable opsgenie```\n"
"Disables the OpsGenie integration.\n\n"
"*Set Wait Time:*\n"
"```/hutbot [config] set wait-time <minutes>```\n"
"Sets the wait time before I send a reminder. Replace `<minutes>` with the number of minutes you want.\n\n"
"*List Available Teams:*\n"
"```/hutbot list teams```\n"
"Lists the available teams.\n\n"
"*Team of User:*\n"
"```/hutbot team of <user>```\n"
"Lists the team of a user. Replace `<user>` with @<user>.\n\n"
"*Add Excluded Team:*\n"
"```/hutbot [config] add excluded-team <team>```\n"
"Adds a team whose members I will not respond to. Replace `<team>` with the name of the team.\n\n"
"*Clear Excluded Teams:*\n"
"```/hutbot [config] clear excluded-teams```\n"
"Clears the list of excluded teams.\n\n"
"*Add Included Team:*\n"
"```/hutbot [config] add included-team <team>```\n"
"Adds a team whose members I will respond to *only*. Replace `<team>` with the name of the team.\n\n"
"*Clear Included Teams:*\n"
"```/hutbot [config] clear included-teams```\n"
"Clears the list of included teams.\n\n"
"*Include Bot Messages:*\n"
"```/hutbot [config] enable bots```\n"
"Also responds to messages from bots.\n\n"
"*Exclude Bot Messages:*\n"
"```/hutbot [config] disable bots```\n"
"Don't respond to messages from bots.\n\n"
"*Only Work Days:*\n"
"```/hutbot [config] enable only-work-days```\n"
"Only respond to messages on work days.\n\n"
"*All Days:*\n"
"```/hutbot [config] disable only-work-days```\n"
"Respond to messages on all days.\n\n"
"*Set Work Hours:*\n"
"```/hutbot [config] set work-hours <start-time> <end-time>```\n"
"Respond to messages during these hours. Set `0:00` `0:00` for all day.\n\n"
":sparkles: *Set Message Pattern:* :new:\n"
"```/hutbot [config] set pattern \"<regex>\" [<case-sensitive>]```\n"
"Respond to messages matching the pattern, case sensitive with `1` (default) or `0`.\n\n"
"*Set Reply Message:*\n"
"```/hutbot [config] set message \"Hi {{user}}, your message in {{channel}} is still unanswered: {{message_link}}\"```\n"
"Sets the reminder message I'll send. Supported variables: `{{user}}`, `{{user_name}}`, `{{team}}`, `{{channel}}`, `{{channel_name}}`, `{{message}}`, `{{message_link}}`, `{{config}}`, `{{wait_minutes}}`, `{{timestamp}}`.\n\n"
":sparkles: *Delete Configuration:* :new:\n"
"```/hutbot delete config <name>```\n"
"Deletes a configuration. Replace `<name>` with the name of the config.\n\n"
":sparkles: *What's New:* :new:\n"
"```/hutbot news```\n"
"Displays what's new.\n\n"
"*Help:*\n"
"```/hutbot help```\n"
"Displays this help message.\n"
)
await send_message(app, channel, user, help_text, thread_ts)
async def schedule_reply(app: AsyncApp, opsgenie_token: str, channel: Channel, config: dict, config_name: str, user: User, text: str, ts: str) -> None:
opsgenie_enabled = config.get('opsgenie')
wait_time = config.get('wait_time')
reply_message_template = config.get('reply_message')
log(f"Scheduling reply for message {ts} in channel #{channel.name} for config '{config_name}', user @{user.name}, wait time {wait_time // 60} mins, opsgenie {'enabled' if opsgenie_enabled else 'disabled'}{', but not configured' if opsgenie_enabled and not opsgenie_configured else ''}")
try:
await asyncio.sleep(wait_time)
permalink = await get_message_permalink(app, channel, ts)
reply_message = render_reply_message_template(reply_message_template, {
"channel": f"#{channel.name}",
"channel_name": channel.name,
"config": config_name,
"message": text,
"message_link": permalink,
"team": user.team if user.team else TEAM_UNKNOWN,
"timestamp": ts,
"user": f"<@{user.id}>",
"user_name": user.real_name if user.real_name else user.name,
"wait_minutes": str(wait_time // 60),
})
await send_message(app, channel, user, reply_message, ts)
if opsgenie_configured and opsgenie_enabled:
log(f"Attempting to send OpsGenie alert for message {ts} in channel #{channel.name}, user @{user.name}...")
await post_opsgenie_alert(app, opsgenie_token, channel, user, text, ts, permalink)
except asyncio.CancelledError as e:
log(f"Cancelling scheduled reply for message {ts} in channel #{channel.name} for config '{config_name}', user @{user.name}:", e)
except Exception as e:
log_error(f"Failed to send scheduled reply for message {ts} in channel #{channel.name} for config '{config_name}', user @{user.name}:", e)
async def replace_ids(app: AsyncApp, channel: Channel | None, text: str) -> str:
for match in ID_PATTERN.finditer(text):
full_match = match.group(0)
log_debug(channel, f"Found ID match: {full_match}...")
id = match.group(1)
handled = False