Spaces:
Sleeping
Sleeping
hari-huynh
commited on
Commit
·
1db8c9e
1
Parent(s):
667871e
Commit Markdown Slack messages
Browse files- test_logfire.py +29 -11
- tool.py +65 -18
test_logfire.py
CHANGED
|
@@ -60,19 +60,37 @@ load_dotenv()
|
|
| 60 |
# # Test async tracing
|
| 61 |
# asyncio.run(test_logfire_tracing())
|
| 62 |
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
with logfire.span('counting size of {cwd=}', cwd=cwd):
|
| 72 |
-
for path in cwd.iterdir():
|
| 73 |
-
if path.is_file():
|
| 74 |
-
with logfire.span('reading {path}', path=path.relative_to(cwd)):
|
| 75 |
-
total_size += len(path.read_bytes())
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
|
|
|
| 60 |
# # Test async tracing
|
| 61 |
# asyncio.run(test_logfire_tracing())
|
| 62 |
|
| 63 |
+
from tool import send_slack_message
|
| 64 |
+
from dotenv import load_dotenv
|
| 65 |
+
|
| 66 |
+
load_dotenv()
|
| 67 |
+
|
| 68 |
+
report = f"""# [] PR #1: Change something PR
|
| 69 |
+
Hello World
|
| 70 |
|
| 71 |
+
**🌿 Branch Information:**
|
| 72 |
+
- **Source Branch:** → **Target Branch:**
|
| 73 |
|
| 74 |
+
**👤 Người tạo:** Hải Huỳnh @Hai Huynh
|
| 75 |
+
|
| 76 |
+
**📅 Thời gian tạo:** 2024-08-20 14:30:00 +07:00
|
| 77 |
+
|
| 78 |
+
**👥 Reviewers:**
|
| 79 |
+
|
| 80 |
+
**🔗 Link Pull Request:** [PR #1: Implement user authentication system](https://google.com.vn)
|
| 81 |
+
"""
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
send_slack_message(
|
| 85 |
+
message_text = "Hello, *World*",
|
| 86 |
+
webhook_url = os.getenv("SLACK_WEBHOOK_URL"),
|
| 87 |
+
bot_token = os.getenv("SLACK_BOT_TOKEN"),
|
| 88 |
+
channel = "pull-request",
|
| 89 |
+
blocks = [
|
| 90 |
+
{
|
| 91 |
+
"type": "markdown",
|
| 92 |
+
"text": report
|
| 93 |
+
}
|
| 94 |
+
]
|
| 95 |
+
)
|
| 96 |
|
tool.py
CHANGED
|
@@ -34,6 +34,7 @@ def create_session(username: Optional[str] = None, app_password: Optional[str] =
|
|
| 34 |
session = requests.Session()
|
| 35 |
session.auth = (resolved_username, resolved_app_password)
|
| 36 |
session.headers.update({"Accept": "application/json"})
|
|
|
|
| 37 |
return session
|
| 38 |
|
| 39 |
|
|
@@ -126,24 +127,70 @@ def send_slack_message(
|
|
| 126 |
resolved_bot_token = bot_token or SLACK_BOT_TOKEN
|
| 127 |
resolved_channel = channel or SLACK_CHANNEL
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
# Ưu tiên gửi qua Incoming Webhook nếu có
|
| 130 |
if resolved_webhook_url:
|
| 131 |
-
payload: Dict[str, Any] = {"text": message_text
|
| 132 |
-
if
|
| 133 |
-
payload["blocks"] =
|
| 134 |
-
|
| 135 |
-
response = requests.post(resolved_webhook_url, json=payload
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
# Fallback: dùng Slack Web API nếu có token + channel
|
| 149 |
if resolved_bot_token and resolved_channel:
|
|
@@ -156,8 +203,8 @@ def send_slack_message(
|
|
| 156 |
"channel": resolved_channel,
|
| 157 |
"text": message_text,
|
| 158 |
}
|
| 159 |
-
if
|
| 160 |
-
payload["blocks"] =
|
| 161 |
if thread_ts is not None:
|
| 162 |
payload["thread_ts"] = thread_ts
|
| 163 |
|
|
|
|
| 34 |
session = requests.Session()
|
| 35 |
session.auth = (resolved_username, resolved_app_password)
|
| 36 |
session.headers.update({"Accept": "application/json"})
|
| 37 |
+
session.headers.update({"Content-Type": "application/json"})
|
| 38 |
return session
|
| 39 |
|
| 40 |
|
|
|
|
| 127 |
resolved_bot_token = bot_token or SLACK_BOT_TOKEN
|
| 128 |
resolved_channel = channel or SLACK_CHANNEL
|
| 129 |
|
| 130 |
+
# Chuẩn hoá blocks nếu user truyền dạng đơn giản {"type": "markdown", "text": "..."}
|
| 131 |
+
normalized_blocks: Optional[List[Dict[str, Any]]] = None
|
| 132 |
+
if blocks is not None:
|
| 133 |
+
normalized_blocks = blocks
|
| 134 |
+
|
| 135 |
# Ưu tiên gửi qua Incoming Webhook nếu có
|
| 136 |
if resolved_webhook_url:
|
| 137 |
+
payload: Dict[str, Any] = {"text": message_text}
|
| 138 |
+
if normalized_blocks is not None:
|
| 139 |
+
payload["blocks"] = normalized_blocks
|
| 140 |
+
|
| 141 |
+
response = requests.post(resolved_webhook_url, json=json.dumps(payload))
|
| 142 |
+
if 200 <= response.status_code < 300 and response.text.strip().lower() in ("ok", ""):
|
| 143 |
+
return {
|
| 144 |
+
"ok": True,
|
| 145 |
+
"method": "webhook",
|
| 146 |
+
"status_code": response.status_code,
|
| 147 |
+
"response": response.text,
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
# Nếu webhook trả lỗi, thử fallback sang Web API nếu có cấu hình
|
| 151 |
+
if resolved_bot_token and resolved_channel:
|
| 152 |
+
api_url = "https://slack.com/api/chat.postMessage"
|
| 153 |
+
headers = {
|
| 154 |
+
"Authorization": f"Bearer {resolved_bot_token}",
|
| 155 |
+
"Content-Type": "application/json",
|
| 156 |
+
}
|
| 157 |
+
payload_api: Dict[str, Any] = {
|
| 158 |
+
"channel": resolved_channel,
|
| 159 |
+
"text": message_text,
|
| 160 |
+
}
|
| 161 |
+
if normalized_blocks is not None:
|
| 162 |
+
payload_api["blocks"] = normalized_blocks
|
| 163 |
+
if thread_ts is not None:
|
| 164 |
+
payload_api["thread_ts"] = thread_ts
|
| 165 |
+
|
| 166 |
+
api_resp = requests.post(api_url, headers=headers, json=payload_api, timeout=15)
|
| 167 |
+
try:
|
| 168 |
+
api_resp.raise_for_status()
|
| 169 |
+
except Exception as exc:
|
| 170 |
+
raise ValueError(
|
| 171 |
+
f"Slack webhook failed (status {response.status_code}, body={response.text!r}); "
|
| 172 |
+
f"fallback Web API also failed: {exc}"
|
| 173 |
+
) from exc
|
| 174 |
+
|
| 175 |
+
data = api_resp.json()
|
| 176 |
+
if not data.get("ok", False):
|
| 177 |
+
error_detail = data.get("error", "unknown_error")
|
| 178 |
+
raise ValueError(
|
| 179 |
+
f"Slack webhook failed (status {response.status_code}, body={response.text!r}); "
|
| 180 |
+
f"fallback Web API responded with error: {error_detail}"
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
return {
|
| 184 |
+
"ok": True,
|
| 185 |
+
"method": "webhook_fallback_web_api",
|
| 186 |
+
"status_code": api_resp.status_code,
|
| 187 |
+
"response": data,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
# Không có fallback khả dụng, báo lỗi chi tiết
|
| 191 |
+
raise ValueError(
|
| 192 |
+
f"Slack webhook request failed with status {response.status_code}: {response.text}"
|
| 193 |
+
)
|
| 194 |
|
| 195 |
# Fallback: dùng Slack Web API nếu có token + channel
|
| 196 |
if resolved_bot_token and resolved_channel:
|
|
|
|
| 203 |
"channel": resolved_channel,
|
| 204 |
"text": message_text,
|
| 205 |
}
|
| 206 |
+
if normalized_blocks is not None:
|
| 207 |
+
payload["blocks"] = normalized_blocks
|
| 208 |
if thread_ts is not None:
|
| 209 |
payload["thread_ts"] = thread_ts
|
| 210 |
|