-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
3251 lines (2665 loc) Β· 136 KB
/
lambda_function.py
File metadata and controls
3251 lines (2665 loc) Β· 136 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 json
import os
import re
import datetime
import hashlib
import requests
from google import genai
import mimetypes
from io import BytesIO
try:
from PIL import Image
except ImportError:
print("Warning: Pillow not available, image validation will be limited")
Image = None
# DynamoDB imports for distributed locking
try:
import boto3
from botocore.exceptions import ClientError
DYNAMODB_AVAILABLE = True
except ImportError:
print("Warning: boto3 not available, will use fallback coordination")
DYNAMODB_AVAILABLE = False
# --- ENVIRONMENT VARIABLES ---
SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]
# Legacy Jira credentials (for backward compatibility)
JIRA_USERNAME = os.environ.get("JIRA_USERNAME")
JIRA_API_TOKEN = os.environ.get("JIRA_API_TOKEN")
# Firebot Jira credentials (preferred)
FIREBOT_JIRA_USERNAME = os.environ.get("FIREBOT_JIRA_USERNAME", JIRA_USERNAME)
FIREBOT_JIRA_API_TOKEN = os.environ.get("FIREBOT_JIRA_API_TOKEN", JIRA_API_TOKEN)
JIRA_DOMAIN = os.environ["JIRA_DOMAIN"]
GEMINI_API_KEY = os.environ["GEMINI_API_KEY"]
# Optional: SLACK_BOT_USER_ID can be set to help prevent duplicate processing
# Use a valid model name with fallback
# Updated to use Gemini 3.x models (Gemini 2.x deprecated as of 2026)
GEMINI_MODEL = os.environ.get("GEMINI_MODEL", "gemini-3.1-flash-lite-preview")
# Map old model names to current Gemini 3.x versions
MODEL_MAPPING = {
"gemini-pro": "gemini-3.1-flash-lite-preview",
"gemini-pro-vision": "gemini-3.1-flash-lite-preview",
"gemini-1.5-flash": "gemini-3.1-flash-lite-preview",
"gemini-1.5-pro": "gemini-3.1-flash-lite-preview",
"gemini-1.5-flash-latest": "gemini-3.1-flash-lite-preview",
"gemini-1.5-pro-latest": "gemini-3.1-flash-lite-preview",
"gemini-1.0-pro": "gemini-3.1-flash-lite-preview",
"gemini-1.5-flash-002": "gemini-3.1-flash-lite-preview",
"gemini-1.5-pro-002": "gemini-3.1-flash-lite-preview",
"gemini-2.5-flash": "gemini-3.1-flash-lite-preview",
"gemini-2.5-pro": "gemini-3.1-flash-lite-preview",
"gemini-2.0-flash": "gemini-3.1-flash-lite-preview",
}
if GEMINI_MODEL in MODEL_MAPPING:
GEMINI_MODEL = MODEL_MAPPING[GEMINI_MODEL]
print(f"Mapped model to: {GEMINI_MODEL}")
# Jira custom field IDs
JIRA_HOSPITAL_FIELD = os.environ.get("JIRA_HOSPITAL_FIELD", "customfield_10297")
JIRA_SLACK_CHANNEL_FIELD = os.environ.get("JIRA_SLACK_CHANNEL_FIELD", "customfield_10250") # Field for Slack channel link
# Primary Fire Tickets channel configuration
# Bot will ONLY process tickets from this channel to prevent unwanted incident channel creation
PRIMARY_FIRE_CHANNEL_ID = os.environ.get("PRIMARY_FIRE_CHANNEL_ID", "C615MLUPP") # #allpaws-firemode
PRIMARY_FIRE_CHANNEL_NAME = os.environ.get("PRIMARY_FIRE_CHANNEL_NAME", "allpaws-firemode") # For logging/debugging
# DynamoDB configuration
DYNAMODB_TABLE_NAME = os.environ.get("DYNAMODB_TABLE_NAME", "firebot-coordination")
DYNAMODB_REGION = os.environ.get("AWS_REGION", "us-east-1")
# Initialize DynamoDB client
if DYNAMODB_AVAILABLE:
dynamodb = boto3.resource('dynamodb', region_name=DYNAMODB_REGION)
coordination_table = dynamodb.Table(DYNAMODB_TABLE_NAME)
else:
coordination_table = None
# --- SLACK PERMISSIONS REQUIRED ---
# The following Slack OAuth scopes are required for full functionality:
# - channels:read (list channels)
# - channels:write (create channels)
# - channels:manage (invite users to channels)
# - chat:write (post messages)
# - users:read.email (lookup users by email - required for creator outreach)
# - users:read (get user information)
# - files:write (upload media files from Jira attachments)
# - files:read (read file information for error handling)
# - groups:history (read channel history for firebot summary command)
# - channels:history (read channel history for firebot summary command)
# --- INVESTIGATION CHECKLIST ---
# The bot analyzes each ticket against these 7 critical investigation items:
# 1. Issue replication in customer's application
# 2. Issue replication on Demo instance
# 3. Steps to reproduce
# 4. Screenshots provided
# 5. Problem start time
# 6. Practice-wide impact
# 7. Multi-practice impact
# --- DEDUPLICATION CACHE ---
# Simple in-memory cache for deduplication (resets on each Lambda cold start)
processed_events = set()
MAX_CACHE_SIZE = 1000 # Prevent memory issues in long-running containers
def add_to_cache(event_id):
"""Add event to cache with size management"""
global processed_events
# If cache is getting too large, clear oldest half
if len(processed_events) >= MAX_CACHE_SIZE:
print(f"Cache size limit reached ({MAX_CACHE_SIZE}), clearing oldest entries")
# Convert to list, keep newest half, convert back to set
events_list = list(processed_events)
processed_events = set(events_list[len(events_list)//2:])
processed_events.add(event_id)
print(f"Added to cache: {event_id} (cache size: {len(processed_events)})")
# --- DYNAMODB COORDINATION FUNCTIONS ---
def acquire_incident_lock(issue_key, timeout_minutes=10):
"""Acquire a distributed lock for incident processing using DynamoDB"""
print(f"DEBUG: DYNAMODB_AVAILABLE = {DYNAMODB_AVAILABLE}")
print(f"DEBUG: coordination_table = {coordination_table}")
if not DYNAMODB_AVAILABLE or not coordination_table:
print("DynamoDB not available, using fallback coordination")
return True
# Check if table exists
try:
print("Attempting to access DynamoDB table...")
table_status = coordination_table.table_status
print(f"DynamoDB table exists and is accessible. Status: {table_status}")
except Exception as e:
print(f"DynamoDB table not accessible: {e}")
print("Error type:", type(e).__name__)
print("Falling back to existing coordination logic")
return True
try:
# Calculate expiration time
now = datetime.datetime.now()
expiration_time = now + datetime.timedelta(minutes=timeout_minutes)
expiration_timestamp = int(expiration_time.timestamp())
print("Attempting DynamoDB conditional write for lock acquisition...")
# Try to acquire lock with conditional write
response = coordination_table.put_item(
Item={
'incident_key': issue_key,
'lock_acquired_at': now.isoformat(),
'expiration_time': expiration_timestamp,
'lambda_instance': os.environ.get('AWS_LAMBDA_REQUEST_ID', 'unknown'),
'status': 'processing'
},
ConditionExpression='attribute_not_exists(incident_key) OR expiration_time < :current_time',
ExpressionAttributeValues={
':current_time': int(now.timestamp())
}
)
print("DynamoDB put_item successful")
print(f"Successfully acquired DynamoDB lock for {issue_key}")
return True
except ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
print(f"Failed to acquire DynamoDB lock for {issue_key} - another instance is processing")
return False
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
print(f"DynamoDB table not found: {e}")
print("Falling back to existing coordination logic")
return True # Proceed with fallback
else:
print(f"DynamoDB error: {e}")
return True # Proceed if DynamoDB fails
except Exception as e:
print(f"Error acquiring DynamoDB lock: {e}")
return True # Proceed if lock acquisition fails
def check_event_processed(event_id):
"""Check if an event has been processed using DynamoDB for persistent deduplication"""
if not DYNAMODB_AVAILABLE or not coordination_table:
return False
try:
response = coordination_table.get_item(
Key={
'incident_key': f"event-{event_id}"
}
)
if 'Item' in response:
item = response['Item']
expiration_time = item.get('expiration_time', 0)
current_time = int(datetime.datetime.now().timestamp())
# Check if event processing record is still valid (24 hours)
if expiration_time > current_time:
print(f"Event {event_id} already processed (expires at {expiration_time})")
return True
else:
print(f"Event {event_id} processing record expired, can reprocess")
return False
else:
print(f"Event {event_id} not found in DynamoDB, can process")
return False
except Exception as e:
print(f"Error checking event processing status: {e}")
return False
def mark_event_processed(event_id):
"""Mark an event as processed in DynamoDB for persistent deduplication"""
if not DYNAMODB_AVAILABLE or not coordination_table:
return
try:
# Calculate expiration time (24 hours from now)
now = datetime.datetime.now()
expiration_time = now + datetime.timedelta(hours=24)
expiration_timestamp = int(expiration_time.timestamp())
coordination_table.put_item(
Item={
'incident_key': f"event-{event_id}",
'processed_at': now.isoformat(),
'expiration_time': expiration_timestamp,
'lambda_instance': os.environ.get('AWS_LAMBDA_REQUEST_ID', 'unknown'),
'status': 'processed'
}
)
print(f"Marked event {event_id} as processed in DynamoDB")
except Exception as e:
print(f"Error marking event as processed: {e}")
def release_incident_lock(issue_key):
"""Release the distributed lock for incident processing"""
if not DYNAMODB_AVAILABLE or not coordination_table:
return
try:
# Delete the lock item
coordination_table.delete_item(
Key={
'incident_key': issue_key
}
)
print(f"Released DynamoDB lock for {issue_key}")
except Exception as e:
print(f"Error releasing DynamoDB lock: {e}")
def check_incident_processing_status(issue_key):
"""Check if an incident is currently being processed"""
if not DYNAMODB_AVAILABLE or not coordination_table:
return False
try:
response = coordination_table.get_item(
Key={
'incident_key': issue_key
}
)
if 'Item' in response:
item = response['Item']
expiration_time = item.get('expiration_time', 0)
current_time = int(datetime.datetime.now().timestamp())
# Check if lock is still valid
if expiration_time > current_time:
print(f"Incident {issue_key} is currently being processed (expires at {expiration_time})")
return True
else:
print(f"Incident {issue_key} lock has expired, can proceed")
return False
else:
print(f"No lock found for incident {issue_key}")
return False
except Exception as e:
print(f"Error checking incident status: {e}")
return False
def mark_incident_completed(issue_key):
"""Mark an incident as completed in DynamoDB"""
if not DYNAMODB_AVAILABLE or not coordination_table:
return
try:
# Update the status to completed
response = coordination_table.update_item(
Key={
'incident_key': issue_key
},
UpdateExpression='SET #status = :status, completed_at = :completed_at',
ExpressionAttributeNames={
'#status': 'status'
},
ExpressionAttributeValues={
':status': 'completed',
':completed_at': datetime.datetime.now().isoformat()
}
)
print(f"Marked incident {issue_key} as completed in DynamoDB")
except Exception as e:
print(f"Error marking incident as completed: {e}")
# --- CLIENTS AND HEADERS ---
# Configure Gemini client globally
if GEMINI_API_KEY:
print(f"β
Gemini API key configured (length: {len(GEMINI_API_KEY)})")
gemini_client = genai.Client(api_key=GEMINI_API_KEY)
else:
print("β οΈ WARNING: GEMINI_API_KEY is not set!")
gemini_client = None
SLACK_HEADERS = {
"Authorization": f"Bearer {SLACK_BOT_TOKEN}",
"Content-Type": "application/json"
}
# --- LAMBDA HANDLER ---
def lambda_handler(event, context=None):
try:
print("Incoming event:", json.dumps(event))
# Check for Slack retry headers
headers = event.get("headers", {})
retry_num = headers.get("x-slack-retry-num", "0")
retry_reason = headers.get("x-slack-retry-reason", "")
if retry_num != "0":
print(f"β οΈ Processing Slack retry event - Retry #{retry_num}, Reason: {retry_reason}")
if event.get("body"):
body = json.loads(event["body"])
if body.get("type") == "url_verification":
return {
"statusCode": 200,
"body": body.get("challenge")
}
if body.get("type") == "event_callback":
# Check for duplicate events
event_data = body.get("event", {})
event_id = create_event_id(event_data)
print(f"Current cache contents: {list(processed_events)}")
print(f"Checking if event {event_id} is already processed...")
# First check in-memory cache (fast)
if event_id in processed_events:
print(f"β Duplicate event detected in cache, skipping: {event_id}")
return {"statusCode": 200, "body": "Duplicate event skipped"}
# Then check DynamoDB for persistent deduplication
if check_event_processed(event_id):
print(f"β Duplicate event detected in DynamoDB, skipping: {event_id}")
# Add to cache to prevent future checks
add_to_cache(event_id)
return {"statusCode": 200, "body": "Duplicate event skipped"}
# Mark event as processed in DynamoDB immediately
mark_event_processed(event_id)
# Mark event as processed in memory cache
print(f"β
New event detected: {event_id}")
add_to_cache(event_id)
user_id = event_data.get("user")
# Quick response to Slack to prevent webhook timeout/retry
try:
# Check if this is our bot's response message
if is_our_command_response(event_data):
print("Skipping our bot's response message to prevent duplicate processing")
return {"statusCode": 200, "body": "Bot response skipped"}
# Check if this is a firebot command in an incident channel
if is_firebot_command(event_data):
process_firebot_command(event_data, user_id)
else:
process_fire_ticket(body, user_id)
except Exception as err:
print("Error during processing:", err)
# Remove from processed events if processing failed
processed_events.discard(event_id)
print(f"Removed failed event from cache: {event_id}")
# Still return 200 to prevent Slack retry
return {"statusCode": 200, "body": "Processing failed but acknowledged"}
return {"statusCode": 200, "body": "OK"}
return {"statusCode": 400, "body": "Bad request"}
except Exception as e:
print("Unhandled exception in lambda_handler:", e)
# Return 200 even on exceptions to prevent Slack retries
return {"statusCode": 200, "body": "Error acknowledged"}
def create_event_id(event_data):
"""Create a unique identifier for deduplication"""
# Use channel, user, timestamp, and Jira issue key for deduplication
channel = event_data.get("channel", "")
user = event_data.get("user", "")
text = event_data.get("text", "")
timestamp = event_data.get("ts", "") # Slack event timestamp
bot_id = event_data.get("bot_id", "")
app_id = event_data.get("app_id", "")
subtype = event_data.get("subtype", "")
# Extract Jira issue key from text for more targeted deduplication
issue_match = re.search(r"(ISD-\d{5})", text)
issue_key = issue_match.group(1) if issue_match else ""
# Create more specific identifier that distinguishes user messages from bot messages
is_bot = bool(bot_id or app_id)
message_type = "bot" if is_bot else "user"
# Include subtype to distinguish channel_join events
if subtype:
message_type = f"{message_type}_{subtype}"
# Create identifier based on what really matters: user + channel + issue + timestamp + message type
# Also include the Slack event_id if available for better deduplication
event_id_from_slack = event_data.get("event_id", "")
unique_string = f"{channel}_{user}_{issue_key}_{timestamp}_{message_type}_{event_id_from_slack}"
event_id = hashlib.md5(unique_string.encode()).hexdigest()[:16]
# Log for debugging with more detail
print(f"Event deduplication - Channel: {channel}, User: {user}, Issue: {issue_key}, Timestamp: {timestamp}")
print(f"Message type: {message_type}, Bot ID: {bot_id}, App ID: {app_id}, Subtype: {subtype}")
print(f"Slack event_id: {event_id_from_slack}")
print(f"Generated event ID: {event_id}")
print(f"Text preview: {text[:100]}..." if len(text) > 100 else f"Text: {text}")
print(f"Current cache size: {len(processed_events)}")
return event_id
def is_firebot_command(event_data):
"""Check if the message is a firebot command in an incident channel"""
try:
text = event_data.get("text", "").strip().lower()
channel_id = event_data.get("channel", "")
# Check if message starts with "firebot"
if not text.startswith("firebot"):
return False
# Check if we're in an incident channel
if not is_incident_channel(channel_id):
return False
print(f"Detected firebot command: {text}")
return True
except Exception as e:
print(f"Error checking firebot command: {e}")
return False
def is_incident_channel(channel_id):
"""Check if the channel is an incident channel"""
try:
response = requests.get(
"https://slack.com/api/conversations.info",
headers=SLACK_HEADERS,
params={"channel": channel_id}
).json()
if not response.get("ok"):
print(f"Could not get channel info: {response.get('error')}")
return False
channel_name = response.get("channel", {}).get("name", "")
return channel_name.startswith("incident-")
except Exception as e:
print(f"Error checking if incident channel: {e}")
return False
def is_primary_fire_channel(channel_id):
"""Check if the channel is the primary Fire Tickets channel where bot should listen for new incidents"""
try:
# Primary check: Compare channel ID (most reliable)
if channel_id == PRIMARY_FIRE_CHANNEL_ID:
print(f"β
Message from primary fire channel (ID match): {channel_id}")
return True
# Fallback: Get channel name for logging
response = requests.get(
"https://slack.com/api/conversations.info",
headers=SLACK_HEADERS,
params={"channel": channel_id}
).json()
if response.get("ok"):
channel_name = response.get("channel", {}).get("name", "")
# Secondary check: Compare by name if configured
if channel_name == PRIMARY_FIRE_CHANNEL_NAME:
print(f"β
Message from primary fire channel (name match): {channel_name}")
return True
print(f"β οΈ Channel {channel_name} ({channel_id}) is not the primary fire channel (expected: {PRIMARY_FIRE_CHANNEL_NAME}/{PRIMARY_FIRE_CHANNEL_ID})")
else:
print(f"β οΈ Channel {channel_id} is not the primary fire channel")
return False
except Exception as e:
print(f"Error checking if primary fire channel: {e}")
# On error, be conservative and reject to prevent unwanted channel creation
return False
def process_firebot_command(event_data, user_id):
"""Process firebot commands in incident channels"""
try:
text = event_data.get("text", "").strip().lower()
channel_id = event_data.get("channel", "")
event_ts = event_data.get("ts", "")
slack_event_id = event_data.get("event_id", "")
# Skip messages from bots to prevent processing our own messages
if event_data.get("bot_id") or event_data.get("app_id"):
print("Skipping bot message to prevent duplicate processing")
return
# Additional check: skip if the message is from our specific bot user
bot_user_ids = [os.environ.get("SLACK_BOT_USER_ID"), "U09584DT15X"]
if user_id in [uid for uid in bot_user_ids if uid]:
print(f"Skipping message from bot user {user_id} to prevent duplicate processing")
return
# Create a more specific lock key that includes user, timestamp, and event ID
command_hash = hashlib.md5(text.encode()).hexdigest()[:8]
lock_key = f"firebot-cmd-{channel_id}-{user_id}-{command_hash}-{event_ts}"
if slack_event_id:
lock_key += f"-{slack_event_id[:8]}"
print(f"Attempting to acquire DynamoDB lock for firebot command: {text}")
print(f"Lock key: {lock_key}")
print(f"Current cache contents: {list(processed_events)}")
# Try to acquire DynamoDB lock for this command with shorter timeout
if not acquire_incident_lock(lock_key, timeout_minutes=1):
print(f"Failed to acquire lock for firebot command: {text}")
return
print(f"Successfully acquired lock for firebot command: {text}")
# Create a unique cache key for this firebot command to prevent duplicates
command_cache_key = f"firebot_{channel_id}_{text}_{user_id}_{event_ts}"
if command_cache_key in processed_events:
print(f"Firebot command already processed: {text}")
release_incident_lock(lock_key)
return
# Mark command as processed
processed_events.add(command_cache_key)
# Parse the command
parts = text.split()
if len(parts) < 2:
print("Invalid firebot command - missing subcommand")
release_incident_lock(lock_key)
return
command = parts[1]
if command == "summary":
response = handle_firebot_summary(channel_id, user_id)
if response:
track_command_response(channel_id, user_id, text, response)
elif command == "time":
response = handle_firebot_time(channel_id, user_id)
if response:
track_command_response(channel_id, user_id, text, response)
elif command == "timeline":
response = handle_firebot_timeline(channel_id, user_id)
if response:
track_command_response(channel_id, user_id, text, response)
elif command == "resolve":
response = handle_firebot_resolve(channel_id, user_id)
if response:
track_command_response(channel_id, user_id, text, response)
else:
print(f"Unknown firebot command: {command}")
response = post_firebot_help(channel_id)
if response:
track_command_response(channel_id, user_id, text, response)
# Release the DynamoDB lock for this command
release_incident_lock(lock_key)
print(f"Released lock for firebot command: {text}")
except Exception as e:
print(f"Error processing firebot command: {e}")
# Release lock even on error
try:
release_incident_lock(lock_key)
except:
pass
def handle_firebot_summary(channel_id, user_id):
"""Generate a comprehensive summary of the incident channel"""
try:
print(f"Generating incident summary for channel {channel_id}")
# Get channel history
messages = get_channel_history(channel_id)
if not messages:
response_ts = post_message(channel_id, "Could not retrieve channel history for summary.")
return response_ts
# Generate summary using AI
summary = generate_incident_summary(messages, channel_id)
# Format the summary message with better Slack formatting
formatted_message = f"""π― Incident Summary π―
βββββββββββ π DETAILS π βββββββββββ
{summary}"""
# Post the summary
response_ts = post_message(channel_id, formatted_message)
return response_ts
except Exception as e:
print(f"Error generating incident summary: {e}")
response_ts = post_message(channel_id, "Sorry, I encountered an error while generating the summary.")
return response_ts
def handle_firebot_time(channel_id, user_id):
"""Calculate and display how long the incident has been open"""
try:
print(f"Calculating incident duration for channel {channel_id}")
# Get channel creation time
channel_info = get_channel_info(channel_id)
if not channel_info:
response_ts = post_message(channel_id, "Could not retrieve channel information.")
return response_ts
created_timestamp = channel_info.get("created", 0)
if not created_timestamp:
response_ts = post_message(channel_id, "Could not determine when this incident started.")
return response_ts
# Calculate duration
now = datetime.datetime.now()
created_time = datetime.datetime.fromtimestamp(created_timestamp)
duration = now - created_time
# Format duration
duration_text = format_duration(duration)
# Post the time information
response_ts = post_message(channel_id, f"β° **Incident Duration**\n\nThis incident has been open for: **{duration_text}**\nStarted: {created_time.strftime('%Y-%m-%d %H:%M:%S UTC')}")
return response_ts
except Exception as e:
print(f"Error calculating incident time: {e}")
response_ts = post_message(channel_id, "Sorry, I encountered an error while calculating the incident duration.")
return response_ts
def get_channel_history(channel_id, limit=100):
"""Get recent channel history"""
try:
response = requests.get(
"https://slack.com/api/conversations.history",
headers=SLACK_HEADERS,
params={
"channel": channel_id,
"limit": limit
}
).json()
if not response.get("ok"):
print(f"Could not get channel history: {response.get('error')}")
return []
return response.get("messages", [])
except Exception as e:
print(f"Error getting channel history: {e}")
return []
def get_channel_info(channel_id):
"""Get channel information including creation time"""
try:
response = requests.get(
"https://slack.com/api/conversations.info",
headers=SLACK_HEADERS,
params={"channel": channel_id}
).json()
if not response.get("ok"):
print(f"Could not get channel info: {response.get('error')}")
return None
return response.get("channel", {})
except Exception as e:
print(f"Error getting channel info: {e}")
return None
def generate_incident_summary(messages, channel_id):
"""Generate a comprehensive summary of the incident using AI"""
try:
# Get channel info to extract hospital name
channel_info = get_channel_info(channel_id)
hospital_name = "Unknown Hospital"
if channel_info:
channel_name = channel_info.get("name", "")
# Extract hospital from channel name pattern: incident-{issue_key}-{date}-{hospital_slug}
name_parts = channel_name.split("-")
if len(name_parts) >= 4 and channel_name.startswith("incident-"):
hospital_slug = name_parts[-1] # Last part should be hospital
# Convert slug back to readable format
hospital_name = hospital_slug.replace("-", " ").title()
# Format messages for AI analysis with Eastern time
formatted_messages = []
eastern_tz = datetime.timezone(datetime.timedelta(hours=-4)) # EDT, adjust for DST as needed
for msg in messages:
user_id = msg.get("user", "Unknown")
text = msg.get("text", "")
timestamp = msg.get("ts", "")
# Look up user info for proper display name
user_info = get_user_info(user_id)
display_name = user_info.get("real_name", user_id) if user_info else user_id
if timestamp:
utc_time = datetime.datetime.fromtimestamp(float(timestamp))
eastern_time = utc_time.astimezone(eastern_tz)
time_str = eastern_time.strftime("%I:%M:%S %p EDT")
formatted_messages.append(f"{time_str} - {display_name}: {text}")
# Create a prompt for the AI
prompt = f"""Please analyze these incident chat messages and generate a fun, engaging summary.
IMPORTANT: Do not use asterisks (*) or underscores (_) for formatting - use plain text only.
Format the summary with these sections:
π¨ {hospital_name} System Outage: A Thrilling Rescue Mission!
This incident report summarizes the swift resolution of a {hospital_name} system outage impacting all workstations. Let's dive into the exciting details!
π¬ Key Events and Timeline:
β’ 02:44:40 PM EDT: π¨ Incident ISD-11345 reported - All {hospital_name} workstations unable to process treatments. Nick Monticello bravely sounds the alarm!
β’ 02:45:12 PM EDT: FireBot π€ springs into action, creating tickets and gathering info
β’ 02:45:53 PM EDT: Nick discovers the culprit - a crashed job responsible for treatments! π
β’ 02:46:04 PM EDT: Victory! Nick restarts the rogue job and confirms everything's back online πͺ
π₯ The Dream Team:
β’ Nick Monticello: Our star reporter and quick-thinking troubleshooter! β
β’ FireBot: Providing real-time support and incident tracking π€
β’ Development Team: Standing by to prevent future incidents π»
π Current Status:
π Incident Resolved! The {hospital_name} system is back up and running smoothly.
π― Key Actions Taken:
β’ Immediate reporting and clear communication
β’ Quick identification of root cause (crashed treatment job)
β’ Swift resolution via restart
β’ FireBot provided excellent support and documentation
βοΈ Next Steps:
β’ Development team will investigate why the job crashed
β’ Post-incident review to enhance system resilience
β’ Celebrate our team's awesome collaborative response! β
Overall, this incident showcased excellent teamwork, rapid response, and effective incident management! A big thank you to everyone involved! π
Messages to analyze:
{formatted_messages}
"""
# Generate summary using AI
summary = generate_gemini_summary({"prompt": prompt})
return summary
except Exception as e:
print(f"Error generating incident summary: {e}")
return None
def format_duration(duration):
"""Format a duration in a human-readable way"""
total_seconds = int(duration.total_seconds())
if total_seconds < 60:
return f"{total_seconds} seconds"
elif total_seconds < 3600:
minutes = total_seconds // 60
return f"{minutes} minute{'s' if minutes != 1 else ''}"
elif total_seconds < 86400:
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
return f"{hours} hour{'s' if hours != 1 else ''} and {minutes} minute{'s' if minutes != 1 else ''}"
else:
days = total_seconds // 86400
hours = (total_seconds % 86400) // 3600
return f"{days} day{'s' if days != 1 else ''} and {hours} hour{'s' if hours != 1 else ''}"
def post_firebot_help(channel_id):
"""Post help information for firebot commands"""
help_text = """π€ **FireBot Commands** π€
ββββββββββββββββββββββββββββββββββββββββ
π― **Available Commands:**
β’ `firebot summary` π - Generate a comprehensive summary of the incident
β’ `firebot time` β° - Show how long the incident has been open
β’ `firebot timeline` π - Generate a detailed timeline of events and response metrics
β’ `firebot resolve` β
- Mark incident as resolved and post summary to Jira ticket
ββββββββββββββββββββββββββββββββββββββββ
π **Additional Useful Commands:**
β’ π₯ `/jsmops all schedules` - View the current on-call schedule
Just type one of these commands in the channel! πΎ"""
response_ts = post_message(channel_id, help_text)
return response_ts
def post_message(channel_id, text):
"""Post a message to a Slack channel"""
try:
response = requests.post(
"https://slack.com/api/chat.postMessage",
headers=SLACK_HEADERS,
json={
"channel": channel_id,
"text": text,
"unfurl_links": False,
"unfurl_media": False
}
).json()
if not response.get("ok"):
print(f"Error posting message: {response.get('error')}")
return None
# Return the timestamp of the posted message
return response.get("ts")
except Exception as e:
print(f"Error posting message: {e}")
return None
# --- CORE LOGIC ---
def process_fire_ticket(event_data, user_id):
event = event_data["event"]
text = event.get("text", "")
source_channel_id = event.get("channel", "")
print(f"Processing message from channel {source_channel_id}: {text}")
# CRITICAL FILTER #1: Ignore tickets posted in incident channels
# This prevents spawning new incident channels from within existing incident channels
if is_incident_channel(source_channel_id):
print(f"β Ignoring ticket in incident channel {source_channel_id}")
print(f" β Tickets should only be posted in #{PRIMARY_FIRE_CHANNEL_NAME}")
print(f" β Subsequent tickets in incident channels are NOT processed")
return
# CRITICAL FILTER #2: Only process tickets from the primary fire channel
# This ensures the bot only responds to tickets in #allpaws-firemode
if not is_primary_fire_channel(source_channel_id):
print(f"β Ignoring ticket from non-primary channel {source_channel_id}")
print(f" β Only monitoring #{PRIMARY_FIRE_CHANNEL_NAME} ({PRIMARY_FIRE_CHANNEL_ID})")
return
print(f"β
Ticket found in #{PRIMARY_FIRE_CHANNEL_NAME} (primary fire channel)")
print(f" β Proceeding with incident channel creation workflow")
# Skip messages from bots to prevent processing our own messages, but allow Jira bot
jira_bot_id = "B87HWGEMD" # Jira Cloud bot ID
jira_app_id = "A2RPP3NFR" # Jira Cloud app ID
bot_id = event.get("bot_id")
app_id = event.get("app_id")
# Allow messages from Jira bot, but skip other bots (including our own)
if (bot_id and bot_id != jira_bot_id) or (app_id and app_id != jira_app_id):
print(f"Skipping bot message (bot_id: {bot_id}, app_id: {app_id}) to prevent duplicate processing")
return
# Additional check: skip if the message is from our specific bot user
bot_user_ids = [os.environ.get("SLACK_BOT_USER_ID"), "U09584DT15X"] # Add known bot user ID as fallback
if user_id in [uid for uid in bot_user_ids if uid]:
print(f"Skipping message from bot user {user_id} to prevent duplicate processing")
return
issue_match = re.search(r"(ISD-\d{5})", text)
if not issue_match:
print("No Jira issue key found in text:", text)
return
issue_key = issue_match.group(1)
print(f"Found Jira issue: {issue_key}")
try:
print(f"DEBUG: Starting DynamoDB coordination for {issue_key}")
# Step 0: Acquire distributed lock using DynamoDB
if not acquire_incident_lock(issue_key):
print(f"Failed to acquire lock for {issue_key}, another instance is processing")
return
print(f"Successfully acquired lock for {issue_key}")
# Step 1: Check if incident already processed by looking for existing channels
if check_incident_already_processed(issue_key):
print(f"Incident {issue_key} already processed, skipping")
release_incident_lock(issue_key)
return
# Step 2: Fetch Jira data to get hospital name
jira_data = fetch_jira_data(issue_key)
if jira_data.status_code != 200:
release_incident_lock(issue_key)
raise Exception(f"Failed to fetch Jira ticket data: {jira_data.text}")
ticket = jira_data.json()
print(f"Successfully fetched Jira ticket: {issue_key}")
parsed_data = parse_jira_ticket(ticket)
print(f"Parsed ticket data - Summary length: {len(parsed_data['summary'])}, Description length: {len(parsed_data['description'])}")
# Extract hospital name and format for channel name
hospital_name = extract_hospital_name(ticket)
hospital_slug = format_hospital_for_channel(hospital_name)
date_str = datetime.datetime.now().strftime("%Y%m%d")
channel_slug = issue_key.lower()
base_channel_name = f"incident-{channel_slug}-{date_str}-{hospital_slug}"
# Step 3: Create the incident channel
channel_id, channel_name = create_incident_channel_with_coordination(base_channel_name, issue_key)
if not channel_id:
print(f"Failed to create channel for {issue_key}")
release_incident_lock(issue_key)
return
print(f"Successfully created channel: {channel_name} ({channel_id})")
# Update Jira ticket with Slack channel link
update_jira_with_slack_link(issue_key, channel_name, channel_id)
# Step 4: Post coordination message to claim ownership
post_coordination_message(channel_id, issue_key)
# Step 4: Invite user to channel
invite_user_to_channel(user_id, channel_id)
# Step 5: Post greeting message to incident channel (only once per incident)
greeting_cache_key = f"greeting_{issue_key}"
if greeting_cache_key not in processed_events:
processed_events.add(greeting_cache_key)
post_incident_channel_greeting(channel_id, issue_key)
print(f"Posted greeting message for {issue_key}")
else:
print(f"Greeting message for {issue_key} already posted, skipping")
# Step 6: Post welcome message to source channel (only once per incident)
welcome_cache_key = f"welcome_{issue_key}"
if welcome_cache_key not in processed_events:
processed_events.add(welcome_cache_key)
post_welcome_message(event_data["event"]["channel"], channel_name, channel_id)
print(f"Posted welcome message for {issue_key}")
else:
print(f"Welcome message for {issue_key} already posted, skipping")
# Step 7: Generate and post summary (only once per incident)
summary_cache_key = f"summary_{issue_key}"
if summary_cache_key not in processed_events:
processed_events.add(summary_cache_key)
print(f"Starting summary generation for {issue_key}")
print(f"Parsed data keys: {list(parsed_data.keys())}")
print(f"Summary length: {len(parsed_data.get('summary', ''))}, Description length: {len(parsed_data.get('description', ''))}")
try:
summary = generate_gemini_summary(parsed_data)
print(f"Generated summary length: {len(summary)}")
print(f"Summary content preview: {summary[:100]}...")
post_summary_message(channel_id, summary)
print(f"Posted summary for {issue_key}")