From 4f78d0a34fd03368cd1daa6d3b89abfc22d10843 Mon Sep 17 00:00:00 2001
From: Fredrik Jonsson <frjo@xdeb.org>
Date: Mon, 3 Dec 2018 12:29:50 +0100
Subject: [PATCH] Use the fund or lab channel if set, if not default to the
 channel in settings.

---
 opentech/apply/activity/messaging.py          | 31 +++++++++++++++++--
 .../apply/activity/tests/test_messaging.py    |  2 +-
 2 files changed, 29 insertions(+), 4 deletions(-)

diff --git a/opentech/apply/activity/messaging.py b/opentech/apply/activity/messaging.py
index 23b11f271..29c0ad9d8 100644
--- a/opentech/apply/activity/messaging.py
+++ b/opentech/apply/activity/messaging.py
@@ -225,19 +225,44 @@ class SlackAdapter(AdapterBase):
             return f'<{user.slack}>'
         return ''
 
+    def slack_channel(self, submission):
+        try:
+            target_room = submission.get_from_parent('slack_channel')
+        except AttributeError:
+            # If not a submission object, set room to default.
+            target_room = self.target_room
+        else:
+            if not target_room:
+                # If no custom room, set to default.
+                target_room = self.target_room
+
+        # Make sure the channel name starts with a "#".
+        if target_room and not target_room.startswith('#'):
+            target_room = f"#{target_room}"
+
+        return target_room
+
     def send_message(self, message, recipient, **kwargs):
-        if not self.destination or not self.target_room:
+        try:
+            submission = kwargs['submission']
+        except Exception:
+            # If no submission, set room to default.
+            target_room = self.target_room
+        else:
+            target_room = self.slack_channel(submission)
+
+        if not self.destination or not target_room:
             errors = list()
             if not self.destination:
                 errors.append('Destination URL')
-            if not self.target_room:
+            if not target_room:
                 errors.append('Room ID')
             return 'Missing configuration: {}'.format(', '.join(errors))
 
         message = ' '.join([recipient, message]).strip()
 
         data = {
-            "room": self.target_room,
+            "room": target_room,
             "message": message,
         }
         response = requests.post(self.destination, json=data)
diff --git a/opentech/apply/activity/tests/test_messaging.py b/opentech/apply/activity/tests/test_messaging.py
index aa07fb2da..ec782ecf9 100644
--- a/opentech/apply/activity/tests/test_messaging.py
+++ b/opentech/apply/activity/tests/test_messaging.py
@@ -225,7 +225,7 @@ class TestActivityAdapter(TestCase):
 
 class TestSlackAdapter(AdapterMixin, TestCase):
     target_url = 'https://my-slack-backend.com/incoming/my-very-secret-key'
-    target_room = '<ROOM ID>'
+    target_room = '#<ROOM ID>'
 
     @override_settings(
         SLACK_DESTINATION_URL=target_url,
-- 
GitLab