11"""Module for Slack-related utilities."""
22
3- import os
43import re
54from typing import Any , List , Union
65
76import httpx
87from pydantic import BaseModel , ValidationInfo , field_validator , model_validator
9-
10- import marvin
8+ from settings import settings
119
1210
1311class EventBlockElement (BaseModel ):
@@ -78,53 +76,25 @@ def validate_event(
7876 return v
7977
8078
81- async def get_token () -> str :
82- """Get the Slack bot token from the environment."""
83- try :
84- token = (
85- marvin .settings .slack_api_token
86- ) # set `MARVIN_SLACK_API_TOKEN` in `~/.marvin/.env
87- except AttributeError :
88- if token := os .getenv ("MARVIN_SLACK_API_TOKEN" ):
89- return token
90- try : # TODO: clean this up
91- from prefect .blocks .system import Secret
92-
93- return (await Secret .load ("slack-api-token" )).get ()
94- except ImportError :
95- pass
96- raise ValueError (
97- "`MARVIN_SLACK_API_TOKEN` not found in environment."
98- " Please set it in `~/.marvin/.env` or as an environment variable."
99- )
100- return token
101-
102-
103- def convert_md_links_to_slack (text ) -> str :
79+ def convert_md_links_to_slack (text : str ) -> str :
10480 md_link_pattern = r"\[(?P<text>[^\]]+)]\((?P<url>[^\)]+)\)"
10581
10682 # converting Markdown links to Slack-style links
107- def to_slack_link (match ) :
83+ def to_slack_link (match : re . Match [ str ]) -> str :
10884 return f"<{ match .group ('url' )} |{ match .group ('text' )} >"
10985
11086 # Replace Markdown links with Slack-style links
111- slack_text = re .sub (md_link_pattern , to_slack_link , text )
112-
113- slack_text = re .sub (r"\*\*(.*?)\*\*" , r"*\1*" , slack_text )
114-
115- return slack_text
87+ return re .sub (
88+ r"\*\*(.*?)\*\*" , r"*\1*" , re .sub (md_link_pattern , to_slack_link , text )
89+ )
11690
11791
11892async def post_slack_message (
11993 message : str ,
12094 channel_id : str ,
121- attachments : Union [list [dict [str , Any ]], None ] = None ,
122- thread_ts : Union [str , None ] = None ,
123- auth_token : Union [str , None ] = None ,
95+ attachments : list [dict [str , Any ]] | None = None ,
96+ thread_ts : str | None = None ,
12497) -> httpx .Response :
125- if not auth_token :
126- auth_token = await get_token ()
127-
12898 post_data = {
12999 "channel" : channel_id ,
130100 "text" : convert_md_links_to_slack (message ),
@@ -137,7 +107,7 @@ async def post_slack_message(
137107 async with httpx .AsyncClient () as client :
138108 response = await client .post (
139109 "https://slack.com/api/chat.postMessage" ,
140- headers = {"Authorization" : f"Bearer { auth_token } " },
110+ headers = {"Authorization" : f"Bearer { settings . slack_api_token } " },
141111 json = post_data ,
142112 )
143113 response_data = response .json ()
@@ -147,12 +117,14 @@ async def post_slack_message(
147117 return response
148118
149119
150- async def get_thread_messages (channel : str , thread_ts : str ) -> list :
120+ async def get_thread_messages (
121+ channel : str , thread_ts : str , auth_token : str
122+ ) -> list [dict [str , Any ]]:
151123 """Get all messages from a slack thread."""
152124 async with httpx .AsyncClient () as client :
153125 response = await client .get (
154126 "https://slack.com/api/conversations.replies" ,
155- headers = {"Authorization" : f"Bearer { await get_token () } " },
127+ headers = {"Authorization" : f"Bearer { auth_token } " },
156128 params = {"channel" : channel , "ts" : thread_ts },
157129 )
158130 response .raise_for_status ()
@@ -161,10 +133,11 @@ async def get_thread_messages(channel: str, thread_ts: str) -> list:
161133
162134async def get_user_name (user_id : str ) -> str :
163135 async with httpx .AsyncClient () as client :
136+ auth_token = settings .slack_api_token
164137 response = await client .get (
165138 "https://slack.com/api/users.info" ,
166139 params = {"user" : user_id },
167- headers = {"Authorization" : f"Bearer { await get_token () } " }, # noqa: E501
140+ headers = {"Authorization" : f"Bearer { auth_token } " },
168141 )
169142 return (
170143 response .json ().get ("user" , {}).get ("name" , user_id )
@@ -178,7 +151,7 @@ async def get_channel_name(channel_id: str) -> str:
178151 response = await client .get (
179152 "https://slack.com/api/conversations.info" ,
180153 params = {"channel" : channel_id },
181- headers = {"Authorization" : f"Bearer { await get_token () } " }, # noqa: E501
154+ headers = {"Authorization" : f"Bearer { settings . slack_api_token } " },
182155 )
183156 return (
184157 response .json ().get ("channel" , {}).get ("name" , channel_id )
@@ -193,7 +166,7 @@ async def fetch_current_message_text(channel: str, ts: str) -> str:
193166 response = await client .get (
194167 "https://slack.com/api/conversations.replies" ,
195168 params = {"channel" : channel , "ts" : ts },
196- headers = {"Authorization" : f"Bearer { await get_token () } " }, # noqa: E501
169+ headers = {"Authorization" : f"Bearer { settings . slack_api_token } " },
197170 )
198171 response .raise_for_status ()
199172 messages = response .json ().get ("messages" , [])
@@ -233,7 +206,7 @@ async def edit_slack_message(
233206 async with httpx .AsyncClient () as client :
234207 response = await client .post (
235208 "https://slack.com/api/chat.update" ,
236- headers = {"Authorization" : f"Bearer { await get_token () } " },
209+ headers = {"Authorization" : f"Bearer { settings . slack_api_token } " },
237210 json = {"channel" : channel_id , "ts" : thread_ts , "text" : updated_text },
238211 )
239212
@@ -244,9 +217,8 @@ async def edit_slack_message(
244217async def search_slack_messages (
245218 query : str ,
246219 max_messages : int = 3 ,
247- channel : Union [str , None ] = None ,
248- user_auth_token : Union [str , None ] = None ,
249- ) -> list :
220+ channel : str | None = None ,
221+ ) -> list [dict [str , Any ]]:
250222 """
251223 Search for messages in Slack workspace based on a query.
252224
@@ -259,12 +231,9 @@ async def search_slack_messages(
259231 Returns:
260232 list: A list of message contents and permalinks matching the query.
261233 """
262- all_messages = []
234+ all_messages : list [ dict [ str , Any ]] = []
263235 next_cursor = None
264236
265- if not user_auth_token :
266- user_auth_token = await get_token ()
267-
268237 async with httpx .AsyncClient () as client :
269238 while len (all_messages ) < max_messages :
270239 params = {
@@ -278,7 +247,7 @@ async def search_slack_messages(
278247
279248 response = await client .get (
280249 "https://slack.com/api/search.messages" ,
281- headers = {"Authorization" : f"Bearer { user_auth_token } " },
250+ headers = {"Authorization" : f"Bearer { settings . slack_api_token } " },
282251 params = params ,
283252 )
284253
@@ -302,14 +271,11 @@ async def search_slack_messages(
302271 return all_messages [:max_messages ]
303272
304273
305- async def get_workspace_info (slack_bot_token : Union [str , None ] = None ) -> dict :
306- if not slack_bot_token :
307- slack_bot_token = await get_token ()
308-
274+ async def get_workspace_info () -> dict [str , Any ]:
309275 async with httpx .AsyncClient () as client :
310276 response = await client .get (
311277 "https://slack.com/api/team.info" ,
312- headers = {"Authorization" : f"Bearer { slack_bot_token } " },
278+ headers = {"Authorization" : f"Bearer { settings . slack_api_token } " },
313279 )
314280 response .raise_for_status ()
315281 return response .json ().get ("team" , {})
0 commit comments