hari-huynh commited on
Commit
4fb5da0
·
1 Parent(s): 5ec2749

Final commit Slack message

Browse files
Files changed (3) hide show
  1. index.py +20 -1
  2. test_logfire.py +41 -16
  3. tool.py +75 -1
index.py CHANGED
@@ -88,6 +88,19 @@ def webhook():
88
  print(diff)
89
 
90
  # save_md_report("DIFF.md", data)
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  send_slack_message(
93
  message_text = pr_report,
@@ -111,7 +124,13 @@ def webhook():
111
  message_text = code_review_text,
112
  webhook_url = SLACK_WEBHOOK_URL,
113
  bot_token = SLACK_BOT_TOKEN,
114
- channel = "pull-request"
 
 
 
 
 
 
115
  )
116
  print("Sent code review")
117
 
 
88
  print(diff)
89
 
90
  # save_md_report("DIFF.md", data)
91
+
92
+ send_slack_message(
93
+ message_text = pr_report,
94
+ webhook_url = SLACK_WEBHOOK_URL,
95
+ bot_token = SLACK_BOT_TOKEN,
96
+ channel = "pull-request",
97
+ blocks = [
98
+ {
99
+ "type": "markdown",
100
+ "text": "<@U099W8UMBAQ>"
101
+ }
102
+ ]
103
+ )
104
 
105
  send_slack_message(
106
  message_text = pr_report,
 
124
  message_text = code_review_text,
125
  webhook_url = SLACK_WEBHOOK_URL,
126
  bot_token = SLACK_BOT_TOKEN,
127
+ channel = "pull-request",
128
+ blocks = [
129
+ {
130
+ "type": "markdown",
131
+ "text": code_review_text
132
+ }
133
+ ]
134
  )
135
  print("Sent code review")
136
 
test_logfire.py CHANGED
@@ -60,37 +60,62 @@ load_dotenv()
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
-
 
60
  # # Test async tracing
61
  # asyncio.run(test_logfire_tracing())
62
 
63
+ from tool import send_slack_message, list_slack_users, get_slack_usergroups
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
+
97
+ import requests
98
 
99
+ # Thay token bằng bot token Slack của bạn
100
+ SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")
101
+ SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
102
+ url = "https://slack.com/api/users.list"
103
+
104
+ users = list_slack_users()
105
+ groups = get_slack_usergroups(SLACK_BOT_TOKEN)
106
+
107
+ # print(users)
108
+ print(groups)
109
 
110
  send_slack_message(
111
+ message_text = "",
112
+ webhook_url = SLACK_WEBHOOK_URL,
113
+ bot_token = SLACK_BOT_TOKEN,
114
  channel = "pull-request",
115
  blocks = [
116
  {
117
  "type": "markdown",
118
+ "text": "<@U099W8UMBAQ>"
119
  }
120
  ]
121
+ )
 
tool.py CHANGED
@@ -34,7 +34,6 @@ 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
- session.headers.update({"Content-Type": "application/json"})
38
  return session
39
 
40
 
@@ -230,6 +229,81 @@ def send_slack_message(
230
  "Missing Slack configuration. Provide SLACK_WEBHOOK_URL or SLACK_BOT_TOKEN and SLACK_CHANNEL."
231
  )
232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  def main() -> None:
234
  # parser = argparse.ArgumentParser(description="Fetch full details of a Bitbucket Cloud pull request.")
235
  # parser.add_argument("--username", required=True, help="Bitbucket username")
 
34
  session = requests.Session()
35
  session.auth = (resolved_username, resolved_app_password)
36
  session.headers.update({"Accept": "application/json"})
 
37
  return session
38
 
39
 
 
229
  "Missing Slack configuration. Provide SLACK_WEBHOOK_URL or SLACK_BOT_TOKEN and SLACK_CHANNEL."
230
  )
231
 
232
+ def list_slack_users(*, bot_token: Optional[str] = None, include_bots: bool = True) -> List[Dict[str, Any]]:
233
+ """
234
+ Trả về danh sách user Slack sử dụng Web API users.list (có phân trang).
235
+ - bot_token: ưu tiên dùng tham số, nếu không có sẽ lấy SLACK_BOT_TOKEN từ env
236
+ - include_bots: False để lọc bỏ bot
237
+ """
238
+ token = bot_token or SLACK_BOT_TOKEN
239
+ if not token:
240
+ raise ValueError("Missing Slack bot token. Provide bot_token or set SLACK_BOT_TOKEN.")
241
+
242
+ users: List[Dict[str, Any]] = []
243
+ cursor: Optional[str] = None
244
+ headers = {
245
+ "Authorization": f"Bearer {token}",
246
+ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
247
+ }
248
+
249
+ while True:
250
+ params: Dict[str, Any] = {"limit": 200}
251
+ if cursor:
252
+ params["cursor"] = cursor
253
+
254
+ resp = requests.get("https://slack.com/api/users.list", headers=headers, params=params, timeout=30)
255
+ resp.raise_for_status()
256
+ data = resp.json()
257
+ if not data.get("ok", False):
258
+ raise ValueError(f"Slack API responded with error: {data.get('error', 'unknown_error')}")
259
+
260
+ page_members = data.get("members", [])
261
+ if not include_bots:
262
+ page_members = [m for m in page_members if not m.get("is_bot", False)]
263
+ users.extend(page_members)
264
+
265
+ cursor = (data.get("response_metadata") or {}).get("next_cursor")
266
+ if not cursor:
267
+ break
268
+
269
+ return users
270
+
271
+ def get_slack_usergroups(bot_token: str):
272
+ """
273
+ Lấy danh sách Slack User Groups (subteams).
274
+
275
+ Args:
276
+ bot_token (str): Slack Bot Token (bắt đầu bằng xoxb-...).
277
+
278
+ Returns:
279
+ list[dict]: Danh sách user groups gồm {id, handle, name, description}.
280
+ """
281
+ url = "https://slack.com/api/usergroups.list"
282
+ headers = {
283
+ "Authorization": f"Bearer {bot_token}"
284
+ }
285
+
286
+ response = requests.get(url, headers=headers)
287
+
288
+ if response.status_code == 200:
289
+ data = response.json()
290
+ if data.get("ok"):
291
+ usergroups = []
292
+ for group in data.get("usergroups", []):
293
+ usergroups.append({
294
+ "id": group.get("id"), # subteam ID
295
+ "handle": group.get("handle"), # ví dụ: dev, qa
296
+ "name": group.get("name"), # tên đầy đủ
297
+ "description": group.get("description") # mô tả
298
+ })
299
+ return usergroups
300
+ else:
301
+ raise Exception(f"Slack API error: {data.get('error')}")
302
+ else:
303
+ raise Exception(f"HTTP Error: {response.status_code}")
304
+
305
+
306
+
307
  def main() -> None:
308
  # parser = argparse.ArgumentParser(description="Fetch full details of a Bitbucket Cloud pull request.")
309
  # parser.add_argument("--username", required=True, help="Bitbucket username")