forked from Perth-Artifactory/taiga_sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack_app.py
1701 lines (1443 loc) · 56.3 KB
/
slack_app.py
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 importlib
import json
import logging
import os
import re
import sys
import time
from copy import deepcopy as copy
from pprint import pprint
import requests
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from taiga import TaigaAPI
from editable_resources import forms, strings
from slack import blocks, block_formatters
from slack import misc as slack_misc
from slack import forms as slack_forms
from util import taigalink, tidyhq
def log_time(
start_time: float, end_time: float, logger: logging.Logger, cause: str | None = None
) -> None:
"""Log the time taken for a command to return to Slack. Optionally log a likely cause for the delay if provided and the time taken is over 1000ms
Sub 1000ms: Debug
1000-2000ms: Info
2000ms+: Warning
"""
time_taken = end_time - start_time
# Convert time taken to ms
time_taken *= 1000
if time_taken < 1000:
logger.debug(f"Command took {time_taken:.2f}ms to return to slack")
elif time_taken > 2000:
logger.warning(f"Command took {time_taken:.2f}ms to return to slack")
if cause:
logger.warning(f"Likely due to: {cause}")
elif time_taken > 1000:
logger.info(f"Command took {time_taken:.2f}ms to return to slack")
if cause:
logger.info(f"Likely due to: {cause}")
def extract_issue_particulars(message) -> tuple[None, None] | tuple[str, str]:
# Discard everything before the bot is mentioned, including the mention itself
try:
message = message[message.index(">") + 1 :]
except ValueError:
# This just means the bot wasn't mentioned in the message (e.g. a direct message or command)
pass
# The board name should be the first word after the bot mention
try:
board = message.split()[0].strip().lower()
except IndexError:
logger.error("No board name found in message")
return None, None
# The description should be everything after the board name
try:
description = message[len(board) + 1 :].strip()
except IndexError:
logger.error("No description found in message")
return None, None
return board, description
# Set up logging
logging.basicConfig(level=logging.INFO)
# Set urllib3 logging level to INFO to reduce noise when individual modules are set to debug
urllib3_logger = logging.getLogger("urllib3")
urllib3_logger.setLevel(logging.INFO)
# Set slack bolt logging level to INFO to reduce noise when individual modules are set to debug
slack_logger = logging.getLogger("slack")
slack_logger.setLevel(logging.WARN)
setup_logger = logging.getLogger("setup")
logger = logging.getLogger("slack_app")
response_logger = logging.getLogger("response")
# Load config
try:
with open("config.json") as f:
config: dict = json.load(f)
except FileNotFoundError:
setup_logger.error(
"config.json not found. Create it using example.config.json as a template"
)
sys.exit(1)
if not config["taiga"].get("auth_token"):
# Get auth token for Taiga
# This is used instead of python-taiga's inbuilt user/pass login method since we also need to interact with the api directly
auth_url = f"{config['taiga']['url']}/api/v1/auth"
auth_data = {
"password": config["taiga"]["password"],
"type": "normal",
"username": config["taiga"]["username"],
}
response = requests.post(
auth_url,
headers={"Content-Type": "application/json"},
data=json.dumps(auth_data),
)
if response.status_code == 200:
taiga_auth_token = response.json().get("auth_token")
else:
setup_logger.error(f"Failed to get auth token: {response.status_code}")
sys.exit(1)
else:
taiga_auth_token = config["taiga"]["auth_token"]
taigacon = TaigaAPI(host=config["taiga"]["url"], token=taiga_auth_token)
# Set up Taiga cache
taiga_cache = taigalink.setup_cache(
config=config, taiga_auth_token=taiga_auth_token, taigacon=taigacon
)
# Write the cache to a file
# We never actually load this back in but it's useful for debugging
with open("taiga_cache.json", "w") as f:
json.dump(taiga_cache, f)
# Set up TidyHQ cache
tidyhq_cache = tidyhq.fresh_cache(config=config)
setup_logger.info(
f"TidyHQ cache set up: {len(tidyhq_cache['contacts'])} contacts, {len(tidyhq_cache['groups'])} groups"
)
# Set up slack app
app = App(token=config["slack"]["bot_token"], logger=slack_logger)
# Get the ID for our team via the API
auth_test = app.client.auth_test()
slack_team_id: str = auth_test["team_id"]
# Join every public channel the bot is not already in
client = WebClient(token=config["slack"]["bot_token"])
channels = client.conversations_list(types="public_channel")["channels"]
for channel in channels:
# Skip archived channels
if channel["is_archived"]:
setup_logger.debug(f"Skipping archived channel {channel['name']}")
continue
# Check if the bot is already in the channel
if channel["is_member"]:
setup_logger.debug(f"Already in channel {channel['name']}")
continue
# Join the channel if not already in and not archived
try:
setup_logger.info(f"Joining channel {channel['name']}")
client.conversations_join(channel=channel["id"])
except SlackApiError as e:
logger.error(f"Failed to join channel {channel['name']}: {e.response['error']}")
# Event listener for messages that mention the bot
@app.event("app_mention")
def ignore_app_mention(ack):
"""Dummy function to acknowledge the mention"""
ack()
# Event listener for direct messages to the bot
@app.event("message")
def handle_message(event, say, client, ack):
"""Ignore messages sent to the bot"""
ack()
# Command listener for form selection
@app.shortcut("form-selector-shortcut")
@app.action("submit_form")
def handle_form_command(ack, respond, command, client, body):
"""Load the form selection modal"""
start_time = time.time()
logger.info(f"Received form selection shortcut or button")
ack()
user = body["user"]
# Reload forms from file
importlib.reload(forms)
global tidyhq_cache
artifactory_member = False
# Check if the user is registered in TidyHQ
tidyhq_id = tidyhq.map_slack_to_tidyhq(
tidyhq_cache=tidyhq_cache,
config=config,
slack_id=user["id"],
)
if tidyhq_id:
# Get the type of membership held
membership_type = tidyhq.get_membership_type(
contact_id=tidyhq_id, tidyhq_cache=tidyhq_cache
)
if membership_type in ["Concession", "Full", "Sponsor"]:
artifactory_member = True
# If they're not an AF member refresh the cache and try again
refreshed_cache = False
if not artifactory_member:
refreshed_cache = True
tidyhq_cache = tidyhq.fresh_cache(config=config, cache=tidyhq_cache)
tidyhq_id = tidyhq.map_slack_to_tidyhq(
tidyhq_cache=tidyhq_cache,
config=config,
slack_id=user["id"],
)
if tidyhq_id:
# Get the type of membership held
membership_type = tidyhq.get_membership_type(
contact_id=tidyhq_id, tidyhq_cache=tidyhq_cache
)
if membership_type in ["Concession", "Full", "Sponsor"]:
artifactory_member = True
# Render the blocks for the form selection modal
block_list = block_formatters.render_form_list(
form_list=forms.forms, member=artifactory_member
)
if refreshed_cache:
log_time(
start_time,
time.time(),
response_logger,
cause="TidyHQ cache refresh after not matching user, form selection modal generation",
)
else:
log_time(
start_time,
time.time(),
response_logger,
cause="Form selection modal generation",
)
if refreshed_cache:
log_time(
start_time,
time.time(),
response_logger,
cause="TidyHQ cache refresh after not matching user, form selection modal generation",
)
else:
log_time(
start_time,
time.time(),
response_logger,
cause="Form selection modal generation",
)
# Open the modal
try:
client.views_open(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "form_selection",
"title": {"type": "plain_text", "text": "Select a form"},
"blocks": block_list,
},
)
except SlackApiError as e:
logger.error(f"Failed to open modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
pprint(block_list)
@app.action(re.compile(r"^tlink.*"))
def ignore_link_button_presses(ack):
"""Dummy function to ignore link button presses"""
ack()
@app.action(re.compile(r"^form-open-.*"))
def handle_form_open_button(ack, body, client):
"""Open the selected form in a modal"""
start_time = time.time()
ack()
form_name = body["actions"][0]["value"]
# Reload forms from file
importlib.reload(forms)
# Get the form details
form = forms.forms[form_name]
# Convert the form questions to blocks
block_list = block_formatters.questions_to_blocks(
form["questions"],
taigacon=taigacon,
taiga_project=form.get("taiga_project"),
taiga_cache=taiga_cache,
)
# Form title can only be 25 characters long
if len(form["title"]) > 25:
if not form.get("short_title"):
form_title = form["title"][:25]
else:
form_title = form["short_title"]
else:
form_title = form["title"]
log_time(start_time, time.time(), response_logger)
# Open the modal
try:
client.views_push(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "form_submission",
"title": {"type": "plain_text", "text": form_title},
"blocks": block_list,
"close": {
"type": "plain_text",
"text": "Cancel",
},
"submit": {
"type": "plain_text",
"text": form["action_name"],
},
"private_metadata": form_name,
},
)
except SlackApiError as e:
logger.error(e)
logger.error(f"Failed to push modal: {e.response['error']}")
@app.view("form_submission")
def handle_form_submissions(ack, body, logger):
"""Process form submissions"""
start_time = time.time()
description, files = slack_forms.form_submission_to_description(
submission=body, slack_app=app
)
project_id, taiga_type_id, taiga_severity_id = (
slack_forms.form_submission_to_metadata(
submission=body, taigacon=taigacon, taiga_cache=taiga_cache
)
)
# Reload forms from file
importlib.reload(forms)
form = forms.forms[body["view"]["private_metadata"]]
if "taiga_type" in form and project_id:
if taiga_type_id:
# If the form doesn't have a type set via a question then we don't need to log that we're overriding it
logger.debug("Overriding type with form-specific type")
try:
taiga_type_id = int(form["taiga_type"])
except ValueError:
# IDs are ints, if it's not then we need map from a name
types = taiga_cache["boards"][project_id]["types"]
for current_type_id, current_type in types.items():
if current_type["name"].lower() == form["taiga_type"].lower():
taiga_type_id = current_type_id
break
else:
# If we get here then we didn't find the type
logger.error(f"Failed to resolve type {form['taiga_type']} to an ID")
logger.info(f"Resolved {form['taiga_type']} to {taiga_type_id}")
# Get the user's name from their Slack ID
user_info = app.client.users_info(user=body["user"]["id"])
slack_name = user_info["user"]["profile"].get(
"real_name_normalized", user_info["user"]["profile"]["display_name_normalized"]
)
issue_title = form["taiga_issue_title"].format(slack_name=slack_name)
issue = taigalink.base_create_issue(
taiga_auth_token=taiga_auth_token,
project_id=project_id,
config=config,
subject=issue_title,
description=description,
type_id=taiga_type_id,
severity_id=taiga_severity_id,
tags=["slack", "form"],
)
if issue:
# We only have a certain amount of time to acknowledge the submission. This way the user gets an error if the submission fails
# and we get a log of which files are missing the next part fails
ack()
else:
logger.error("Failed to create issue")
return
upload_success = True
for filelink in files:
downloaded_file = slack_misc.download_file(url=filelink, config=config)
if not downloaded_file:
logger.error(f"Failed to download file {filelink}")
# Upload the file to Taiga
upload = taigalink.attach_file(
taiga_auth_token=taiga_auth_token,
config=config,
project_id=project_id,
item_type="issue",
item_id=issue["id"],
url=filelink,
)
if not upload:
logger.error(f"Failed to upload file {filelink}")
upload_success = False
# DM the user to let them know their form was submitted successfully
message = strings.form_submission_success.format(form_name=form["title"])
if not upload_success:
message += "\n\n" + strings.file_upload_failure
slack_misc.send_dm(slack_id=body["user"]["id"], message=message, slack_app=app)
if len(files) > 0:
log_time(
start_time,
time.time(),
response_logger,
cause="File upload, issue creation",
)
else:
log_time(start_time, time.time(), response_logger, cause="Issue creation")
@app.view("form_submitted")
def ignore_form_submitted(ack):
"""Dummy function to ignore form submitted views"""
ack()
@app.action(re.compile(r"^twatch.*"))
def watch_button(ack, body, respond):
"""Watch items on Taiga via a button
Watch button values are a dict with:
* project_id: The ID of the Taiga project the item is in
* item_id: The ID of the item
* type: The type of item (e.g. userstory, issue)
* permalink: The permalink to the URL in Taiga, if available"""
start_time = time.time()
ack()
watch_target = json.loads(body["actions"][0]["value"])
global tidyhq_cache
tidyhq_cache = tidyhq.fresh_cache(config=config, cache=tidyhq_cache)
# Check if the Slack user can be mapped to a Taiga user
taiga_id = tidyhq.map_slack_to_taiga(
tidyhq_cache=tidyhq_cache,
config=config,
slack_id=body["user"]["id"],
)
# If the Slack user can't be mapped to a Taiga user the best we can do is tell them to watch it themselves
if not taiga_id:
message = """Sorry, I can't watch this item for you as I don't know who you are in Taiga\nIf you think this is an error please reach out to #it."""
if watch_target.get("permalink"):
message += f"\n\nYou can view the item yourself <{watch_target['permalink']}|here>."
client.chat_postEphemeral(
channel=body["channel"]["id"], user=body["user"]["id"], text=message
)
return
# Get the item in Taiga
# Translate the type field to an argument get_info can use
type_to_arg = {
"issue": "issue_id",
"userstory": "story_id",
"task": "task_id",
# Add other types as needed
}
item_info = taigalink.get_info(
taiga_auth_token=taiga_auth_token,
config=config,
**{type_to_arg.get(watch_target["type"], "story_id"): watch_target["item_id"]},
)
# Add a catch for get_info screwing up
if not item_info:
message = "Sorry, I'm having trouble accessing Taiga right now. Please try again later."
if watch_target.get("permalink"):
message += f"\n\nYou can view the item yourself <{watch_target['permalink']}|here>."
client.chat_postEphemeral(
channel=body["channel"]["id"], user=body["user"]["id"], text=message
)
return
# Check if the user is already watching the item
if int(taiga_id) in item_info["watchers"]:
message = f"You're already watching this {watch_target['type']} in Taiga!"
client.chat_postEphemeral(
channel=body["channel"]["id"], user=body["user"]["id"], text=message
)
return
# Add the user to the watchers list
add_watcher_response = taigalink.watch(
type_str=watch_target["type"],
item_id=watch_target["item_id"],
watchers=item_info["watchers"],
taiga_id=taiga_id,
taiga_auth_token=taiga_auth_token,
config=config,
version=item_info["version"],
)
if not add_watcher_response:
message = "Sorry, I'm having trouble accessing Taiga right now. Please try again later."
if watch_target.get("permalink"):
message += f"\n\nYou can view the item yourself <{watch_target['permalink']}|here>."
client.chat_postEphemeral(
channel=body["channel"]["id"], user=body["user"]["id"], text=message
)
return
message = f"You're now watching this {watch_target['type']} in Taiga!"
client.chat_postEphemeral(
channel=body["channel"]["id"], user=body["user"]["id"], text=message
)
log_time(
start_time,
time.time(),
response_logger,
cause="Item retrieval, watcher addition",
)
@app.event("reaction_added")
def handle_reaction_added_events(ack):
"""Dummy function to ignore emoji reactions to messages"""
ack()
@app.event("app_home_opened")
def handle_app_home_opened_events(body, client, logger):
"""Regenerate the app home when it's opened by a user"""
start_time = time.time()
user_id = body["event"]["user"]
# Get user details for more helpful console messages
user_info = client.users_info(user=user_id)
global tidyhq_cache
tidyhq_cache = tidyhq.fresh_cache(config=config, cache=tidyhq_cache)
slack_misc.push_home(
user_id=user_id,
config=config,
tidyhq_cache=tidyhq_cache,
taiga_auth_token=taiga_auth_token,
slack_app=app,
)
log_time(
start_time,
time.time(),
response_logger,
cause="TidyHQ cache refresh, app home generation",
)
@app.action(re.compile(r"^viewedit-.*"))
def handle_viewedit_actions(ack, body):
"""Listen for view in app and view/edit actions"""
start_time = time.time()
# Retrieve action details if applicable
value_string = body["actions"][0]["action_id"]
# Backwards compatibility for old some old view buttons
if "userstory" in value_string:
value_string = value_string.replace("userstory", "story")
# Sometimes we attach the view method to the action ID
modal_method = "open"
if value_string.count("-") == 4:
modal_method = value_string.split("-")[-1]
value_string = "-".join(value_string.split("-")[:-1])
project_id, item_type, item_id = value_string.split("-")[1:]
logger.info(f"Received view/edit for {item_type} {item_id} in project {project_id}")
ack()
# Attempt to map the Slack user to a Taiga user
taiga_id = tidyhq.map_slack_to_taiga(
tidyhq_cache=tidyhq_cache,
config=config,
slack_id=body["user"]["id"],
)
if not taiga_id:
logger.error(f"Failed to map Slack user {body['user']['id']} to Taiga user")
view_title = f"View {item_type}"
edit = False
else:
view_title = f"View/edit {item_type}"
edit = True
# Generate the blocks for the view/edit modal
block_list = block_formatters.viewedit_blocks(
taigacon=taigacon,
project_id=project_id,
item_type=item_type,
item_id=item_id,
taiga_cache=taiga_cache,
config=config,
taiga_auth_token=taiga_auth_token,
edit=edit,
)
if taiga_id:
log_time(
start_time, time.time(), response_logger, cause="View/edit modal generation"
)
else:
log_time(
start_time, time.time(), response_logger, cause="View modal generation"
)
if modal_method == "open":
# Open the modal
try:
client.views_open(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "finished_editing",
"title": {"type": "plain_text", "text": view_title},
"blocks": block_list,
"private_metadata": value_string,
"submit": {"type": "plain_text", "text": "Finish"},
"clear_on_close": True,
},
)
logger.info(
f"View/edit modal for {item_type} {item_id} in project {project_id} opened for {body['user']['id']} ({taiga_id})"
)
except SlackApiError as e:
logger.error(f"Failed to open modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
pprint(block_list)
elif modal_method == "update":
# Update the modal
try:
client.views_update(
view_id=body["view"]["root_view_id"],
view={
"type": "modal",
"callback_id": "finished_editing",
"title": {"type": "plain_text", "text": view_title},
"blocks": block_list,
"private_metadata": value_string,
"submit": {"type": "plain_text", "text": "Finish"},
"clear_on_close": True,
},
)
logger.info(
f"View/edit modal for {item_type} {item_id} in project {project_id} updated for {body['user']['id']}"
)
except SlackApiError as e:
logger.error(f"Failed to update modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
pprint(block_list)
elif modal_method == "push":
# Push a new modal onto the stack
try:
client.views_push(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "finished_editing",
"title": {"type": "plain_text", "text": view_title},
"blocks": block_list,
"private_metadata": value_string,
"submit": {"type": "plain_text", "text": "Finish"},
"clear_on_close": True,
},
)
logger.info(
f"View/edit modal for {item_type} {item_id} in project {project_id} pushed to {body['user']['id']}"
)
except SlackApiError as e:
logger.error(f"Failed to update modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
pprint(block_list)
# Comment
@app.action("submit_comment")
def handle_comment_addition(ack, body, logger):
"""Handle comment additions"""
start_time = time.time()
ack()
user_id = body["user"]["id"]
# Get the comment text
# We've added some junk data to the block ID to make it unique (so it doesn't get prefilled)
# Yes I know next/iter exists
comment = body["view"]["state"]["values"]["comment_field"]
comment = comment[list(comment.keys())[0]]["value"]
# Check if the comment is empty
if not comment or comment.isspace():
logger.info("Comment is empty, ignoring")
return
# Get the item details from the private metadata
project_id, item_type, item_id = body["view"]["private_metadata"].split("-")[1:]
# Post the comment to Taiga
print(f"Posting comment {comment} to {item_type} {item_id} in project {project_id}")
# Get the item direct from Taiga, this isn't cached since it changes so often
if item_type == "task":
item = taigacon.tasks.get(item_id)
elif item_type in ["story", "userstory"]:
item = taigacon.user_stories.get(item_id)
elif item_type == "issue":
item = taigacon.issues.get(item_id)
# Add who the comment is from
# Map to the appropriate Taiga user
taiga_id = tidyhq.map_slack_to_taiga(
tidyhq_cache=tidyhq_cache,
config=config,
slack_id=user_id,
)
if taiga_id:
# Get the user's name from their Taiga ID
taiga_user_info = taiga_cache["users"][taiga_id]
poster_name = taiga_user_info["name"]
else:
poster_name = slack_misc.name_mapper(slack_id=user_id, slack_app=app)
# Add byline
comment = f"Posted from Slack by {poster_name}: {comment}"
# Post the comment
commenting = item.add_comment(comment)
if not commenting:
logger.info(
f"Failed to add comment to {item_type} {item_id} in project {project_id} by {user_id}"
)
logger.info(":".join(comment.split(":")[1:]))
return
else:
logger.info(
f"Comment added to {item_type} {item_id} in project {project_id} by {user_id}"
)
logger.info(":".join(comment.split(":")[1:]))
# Regenerate the view/edit modal
block_list = block_formatters.viewedit_blocks(
taigacon=taigacon,
project_id=project_id,
item_type=item_type,
item_id=item_id,
taiga_cache=taiga_cache,
config=config,
taiga_auth_token=taiga_auth_token,
)
log_time(
start_time,
time.time(),
response_logger,
cause="Comment addition, view/edit modal regeneration",
)
# Push the modal
try:
client.views_update(
view_id=body["view"]["root_view_id"],
view={
"type": "modal",
"callback_id": "finished_editing",
"title": {"type": "plain_text", "text": f"View/edit {item_type}"},
"blocks": block_list,
"private_metadata": body["view"]["private_metadata"],
"submit": {"type": "plain_text", "text": "Finish"},
"clear_on_close": True,
},
)
logger.info(f"Updated view/edit modal for {item_type} {item_id} for {user_id}")
except SlackApiError as e:
logger.error(f"Failed to push modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
@app.action("home-attach_files")
def attach_files_modal(ack, body):
"""Open a modal to submit files for later attachment"""
ack()
block_list = []
# Create upload field
block_list = block_formatters.add_block(block_list, blocks.file_input)
block_list[-1]["block_id"] = "upload_section"
block_list[-1]["element"]["action_id"] = "upload_file"
block_list[-1]["label"]["text"] = "Upload files"
# Push a new modal
try:
client.views_push(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "submit_files",
"title": {"type": "plain_text", "text": "Upload files"},
"blocks": block_list,
"private_metadata": body["view"]["private_metadata"],
"submit": {"type": "plain_text", "text": "Attach"},
},
)
except SlackApiError as e:
logger.error(f"Failed to push modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
@app.action(re.compile(r"^view_tasks-.*"))
def view_tasks(ack, body, logger):
"""Push a modal to view tasks attached to a specific user story"""
start_time = time.time()
ack()
value_string = body["actions"][0]["action_id"]
story_id = value_string.split("-")[1]
# Get the tasks for the user story
tasks = taigalink.get_tasks(
config=config,
taiga_auth_token=taiga_auth_token,
exclude_done=False,
story_id=story_id,
)
# Attempt to identify the user
taiga_id = tidyhq.map_slack_to_taiga(
tidyhq_cache=tidyhq_cache,
config=config,
slack_id=body["user"]["id"],
)
edit = False
if taiga_id:
edit = True
block_list = block_formatters.format_tasks_modal_blocks(
task_list=tasks,
config=config,
taiga_auth_token=taiga_auth_token,
edit=edit,
taiga_cache=taiga_cache,
)
log_time(start_time, time.time(), response_logger, cause="Task retrieval")
# Push a new modal
try:
client.views_push(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "view_tasks",
"title": {"type": "plain_text", "text": "View Tasks"},
"close": {"type": "plain_text", "text": "Back"},
"blocks": block_list,
"private_metadata": body["view"]["private_metadata"],
},
)
logger.info(f"Pushed tasks modal for user story {story_id}")
logger.info(f"Task modal for story {story_id} pushed for {body['user']['id']}")
except SlackApiError as e:
logger.error(f"Failed to push modal: {e.response['error']}")
logger.error(e.response["response_metadata"]["messages"])
@app.view("submit_files")
def attach_files(ack, body):
"""Take the submitted files, uploads them to Taiga and updates the view/edit modal"""
start_time = time.time()
ack()
files = body["view"]["state"]["values"]["upload_section"]["upload_file"]["files"]
if not files:
return
# Get the item details from the private metadata
project_id, item_type, item_id = body["view"]["private_metadata"].split("-")[1:]
# Upload the files to Taiga
for file in files:
file_url = file["url_private"]
upload = taigalink.attach_file(
taiga_auth_token=taiga_auth_token,
config=config,
project_id=project_id,
item_type=item_type,
item_id=item_id,
url=file_url,
)
if not upload:
logger.error(f"Failed to upload file {file_url}")
# Unlike trigger IDs (3s expiry) we seem to be able to update the view as required
block_list = block_formatters.viewedit_blocks(
taigacon=taigacon,
project_id=project_id,
item_type=item_type,
item_id=item_id,
taiga_cache=taiga_cache,
config=config,
taiga_auth_token=taiga_auth_token,
)
log_time(
start_time,
time.time(),
response_logger,
cause=f"File upload ({len(files)} files), view/edit modal regeneration",
)
# Push the modal
logging.info("Refreshing root view modal")
try:
client.views_update(
view_id=body["view"]["root_view_id"],
view={
"type": "modal",
"callback_id": "finished_editing",
"title": {"type": "plain_text", "text": f"View/edit {item_type}"},
"blocks": block_list,
"private_metadata": body["view"]["private_metadata"],
"submit": {"type": "plain_text", "text": "Finish"},
"clear_on_close": True,
},
)
except SlackApiError as e:
logger.error(f"Failed to push modal: {e.response['error']}")
@app.action("edit_info")
def send_info_modal(ack, body, logger):
"""Open a modal to edit the details of an item"""
start_time = time.time()
ack()
# Get the item details from the private metadata
project_id, item_type, item_id = body["view"]["private_metadata"].split("-")[1:]
block_list = block_formatters.edit_info_blocks(
taigacon=taigacon,
project_id=project_id,
item_type=item_type,
item_id=item_id,
taiga_cache=taiga_cache,
)
log_time(start_time, time.time(), response_logger, cause="Edit modal generation")